# coding=utf-8

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.log.models import BizLog
from utils import get_remote_addr
from apps.tenant.employee.models import Employee

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

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

                employee = Employee.objects.filter(user=user).first()
                if not user.is_active:
                    msg = u'禁用帐户，禁止登录'
                    BizLog.objects.addnew(employee.tenant, 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(employee.tenant, 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,
                    'user_type': user.type,
                }
            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)
