# coding=utf-8
from django.contrib.auth import get_user_model, authenticate
from django.db.models import F

from rest_framework import serializers
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.settings import api_settings

from utils import get_remote_addr
from utils.exceptions import CustomError

from apps.system.models import SysLog
from .models import Department

User = get_user_model()
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

class AdminUserJWTSerializer(JSONWebTokenSerializer):
    def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                if not user.is_active:
                    msg = u'禁用帐户，禁止登录'
                    SysLog.objects.addnew(user, SysLog.INSERT,u'禁用帐户[%s]尝试登录管理系统,IP[%s]' % (user.username, get_remote_addr(self.request)))
                    raise serializers.ValidationError(msg)

                if not user.is_administrator():
                    msg = u'非管理员账号，禁止登录'
                    SysLog.objects.addnew(user, SysLog.INSERT,u'非管理员账号[%s]尝试登录管理系统,IP[%s]' % (user.username, get_remote_addr(self.request)))
                    raise serializers.ValidationError(msg)

                payload = jwt_payload_handler(user)
                SysLog.objects.addnew(user, SysLog.INSERT, u'[%s]登录管理系统,IP[%s]' % (user.username,get_remote_addr(self.request)))

                return {
                    'token': jwt_encode_handler(payload),
                    'user_id': user.id,
                    'username': user.username
                }
            else:
                msg = u'账号或者密码错误!'
                SysLog.objects.addnew(None, SysLog.INSERT, u'登录管理系统失败[%s][%s],IP[%s]' % (attrs[self.username_field], attrs['password'], get_remote_addr(self.request)))
                raise serializers.ValidationError(msg)
        else:
            msg = u'必须包含“{username field}”和“password'
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)

class StaffUserJWTSerializer(JSONWebTokenSerializer):
    def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                if not user.is_active:
                    msg = u'禁用帐户，禁止登录'
                    SysLog.objects.addnew(user, SysLog.INSERT,u'禁用帐户[%s]尝试登录答题系统,IP[%s]' % (user.username, get_remote_addr(self.request)))
                    raise serializers.ValidationError(msg)

                if not user.is_staff():
                    msg = u'非工作账号，禁止登录'
                    SysLog.objects.addnew(user, SysLog.INSERT,u'非工作账号[%s]尝试登录答题系统,IP[%s]' % (user.username, get_remote_addr(self.request)))
                    raise serializers.ValidationError(msg)

                payload = jwt_payload_handler(user)
                SysLog.objects.addnew(user, SysLog.INSERT, u'[%s]登录答题系统,IP[%s]' % (user.username,get_remote_addr(self.request)))

                return {
                    'token': jwt_encode_handler(payload),
                    'user_id': user.id,
                    'username': user.username
                }
            else:
                msg = u'账号或者密码错误!'
                SysLog.objects.addnew(None, SysLog.INSERT, u'登录答题系统失败[%s][%s],IP[%s]' % (attrs[self.username_field], attrs['password'], get_remote_addr(self.request)))
                raise serializers.ValidationError(msg)
        else:
            msg = u'必须包含“{username field}”和“password'
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)


class DepartmentSerializer(serializers.ModelSerializer):
    lft = serializers.IntegerField(read_only=True)
    rgt = serializers.IntegerField(read_only=True)
    out_parent_id = serializers.SerializerMethodField()

    class Meta:
        model = Department
        fields = '__all__'

    def get_out_parent_id(self, obj):
        if obj.parent_id:
            return obj.parent_id
        return 0

    def create(self, validated_data):
        count = Department.objects.filter(name=validated_data['name']).count()
        if count:
            raise CustomError(u'名称为[%s]的部门已存在！' % validated_data['name'])
        parent = None
        if 'parent_id' in validated_data:
            parent = Department.getById(validated_data['parent_id'])
            validated_data['parent_id'] = parent.id

        lft = Department.getLft(parent)
        Department.objects.filter(rgt__gt=lft).update(rgt=F('rgt') + 2)
        Department.objects.filter(lft__gt=lft).update(lft=F('lft') + 2)

        validated_data['lft'] = lft + 1
        validated_data['rgt'] = lft + 2

        instance = super(DepartmentSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        print(validated_data)
        name = validated_data['name']
        count = Department.objects.filter(name=name).exclude(id=instance.id).count()
        if count:
            raise CustomError(u'名称为[%s]的部门已存在！' % name)
        instance = super(DepartmentSerializer, self).update(instance, validated_data)
        return instance


class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, allow_blank=True)
    status_text = serializers.SerializerMethodField()
    department_text = serializers.CharField(source='department.name', read_only=True)
    type_text = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = '__all__'

    def get_status_text(self, obj):
        if obj.is_active:
            return u'是'
        return u'否'

    def get_type_text(self, obj):
        if obj.type == User.ADMINSTRATOR:
            return u'管理员'
        elif obj.type == User.STAFF:
            return u'员工'
        return ''

    def create(self, validated_data):
        if validated_data['password'].strip() == '':
            raise CustomError(u'密码不能为空！')
        if 'type' in validated_data and validated_data['type'] == User.STAFF:
            user = User.objects.create_staff(validated_data['username'], validated_data['password'], is_active=validated_data['is_active'], department=validated_data['department'])
        else:
            user = User.objects.create_administrator(validated_data['username'], validated_data['password'], is_active=validated_data['is_active'], department=validated_data['department'])
        return user

    def update(self, instance, validated_data):
        instance.update_item(validated_data)
        return instance
