# coding=utf-8

import json

from django.contrib.auth import get_user_model, authenticate

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

from apps.employee.models import Employee
from apps.log.models import BizLog

from utils import get_remote_addr
from utils.exceptions import CustomError

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


class JWTSerializer(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_employee():
                    msg = u'非工作账号，禁止登录'
                    raise serializers.ValidationError(msg)

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

                payload = jwt_payload_handler(user)
                BizLog.objects.addnew(user, BizLog.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'账号或者密码错误!'
                raise serializers.ValidationError(msg)
        else:
            msg = u'必须包含“{username field}”和“password.'
            msg = msg.format(username_field=self.username_field)
            raise serializers.ValidationError(msg)


class EmployeeSerializer(serializers.ModelSerializer):
    password = serializers.CharField(source='user.password', write_only=True, allow_blank=True)
    username = serializers.CharField(source='user.username')
    is_active = serializers.IntegerField(source='user.is_active')
    gender_text = serializers.CharField(source='get_gender_display', read_only=True)
    create_time = serializers.DateTimeField(source='user.date_joined', format='%Y-%m-%d %H:%M', read_only=True)
    is_active_text = serializers.SerializerMethodField()

    class Meta:
        model = Employee
        fields = '__all__'

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

    def create(self, validated_data):
        if validated_data['user']['password'].strip() == '':
            raise CustomError(u'密码不能为空！')
        user = User.objects.create_employee(validated_data['user']['username'], validated_data['user']['password'], is_active=validated_data['user']['is_active'])
        validated_data['user'] = user
        instance = super(EmployeeSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        if 'user' in validated_data:
            instance.user.update_item(validated_data['user'])
            validated_data.pop('user')
        instance = super(EmployeeSerializer, self).update(instance, validated_data)
        return instance
