#coding=utf-8

import traceback
import json

from collections import OrderedDict
from django.db import transaction,IntegrityError
from django.db.models import F,ProtectedError
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import Permission, Group
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from libs import utils
from libs.utils import dump_form_errors
from libs.http import JSONError, JSONResponse,DataGridJSONResponse
from apps.dashboard.forms import MyAuthenticationForm
from .decorators import token_required,permission_required
from apps.exceptions import CustomError

from apps.foundation.models import BizLog

from django.db.models import Q
from django.conf import settings
from .models import *
from .serializers import *
from .filters import *

@csrf_exempt
def login(request):
    form = MyAuthenticationForm(data=request.POST, request=request)
    if form.is_valid():
        user = form.get_user()
        if user.type and user.type != User.EMPLOYEE:
            return JSONError(u'非工作帐号，禁止登录！')

        if not user.enabled:
            return JSONError(u'该账号不可用')

        if user.username != 'zzzroor':
            BizLog.objects.addnew(user, BizLog.INSERT,
                                  u"[%s]登录系统,IP[%s]" % (user.username, request.META['REMOTE_ADDR']))

        if user.is_superuser:
            superuser = True
        else:
            superuser = False

        return JSONResponse({
            'user_id': user.id,
            'access_token': form.access_token,
            'name': user.name or user.username,
            'superuser': superuser,
        })
    else:
        if request.POST['username'] != 'zzzroor':
            BizLog.objects.addnew(None, BizLog.INSERT, u"[%s]登录失败,密码[%s],IP[%s]" % (
                request.POST['username'],
                request.POST['password'],
                request.META['REMOTE_ADDR']
            ))
        return JSONError(dump_form_errors(form))


@token_required
@login_required()
def employee_list(request):
    f = EmployeeFilter(request.GET, queryset=User.objects.filter(branch_id__isnull=False))
    rows, total = utils.get_page_data(request, f.qs)
    serializer = EmployeeSafeSerializer(rows, many=True)
    return DataGridJSONResponse(serializer.data, total)


@token_required
@login_required()
def employee_save(request):
    id = request.GET.get('id')
    data = json.loads(request.body)

    try:
        with transaction.atomic():
            serializer = EmployeeSerializer.factory(request.user, data, id)
            if serializer.instance:
                user = serializer.instance
                if not data['password']:
                    data['password'] = user.password
                else:
                    user.set_password(data['password'])
                    data['password'] = user.password
            serializer.validSave()
    except CustomError as e:
        return JSONError(e.get_error_msg())
    except Exception as e:
        traceback.print_exc()
        return JSONError(u'保存失败')
    return JSONResponse()


@token_required
@login_required()
def password_save(request):
    data = json.loads(request.body)
    try:
        data['new_password'] = data['new_password'].strip(u' ')
        data['confirm_password'] = data['confirm_password'].strip(u' ')
        data['old_password'] = data['old_password'].strip(u' ')

        if data['new_password'] != data['confirm_password']:
            raise CustomError(u'两次输入的密码不一致， 请检查')

        with transaction.atomic():
            if not request.user.check_password(data['old_password']):
                raise CustomError(u'原密码输入错误， 请检查')
            request.user.set_password(data['new_password'])
            request.user.save()
    except CustomError as e:
        return JSONError(e.get_error_msg())
    except Exception as e:
        traceback.print_exc()
        return JSONError(u'保存失败！')
    return JSONResponse()
