# 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 django.contrib.auth.models import Group, Permission
from apps.log.models import BizLog
from utils import get_remote_addr
from utils.booleancharfield import BooleanCharField
from utils.exceptions import CustomError
from apps.account.models import ManageStoreUser

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_active:
                    msg = u'禁用帐户，禁止登录！'
                    BizLog.objects.addnew(user,  BizLog.INSERT,u'禁用帐户[%s]尝试登录系统,IP[%s]' % (user.username, get_remote_addr(self.request)))
                    raise serializers.ValidationError(msg)
                if user.status != User.INSERVICE:
                    raise serializers.ValidationError('当前账号非在职状态，禁止登录！')

                payload = jwt_payload_handler(user)
                BizLog.objects.addnew(user, BizLog.INSERT,
                                      u'[%s]登录系统,IP[%s]' % (user.username,get_remote_addr(self.request)))
                permissions = list(user.get_all_permissions())
                return {
                    'token': jwt_encode_handler(payload),
                    'user_id': user.id,
                    'username': user.username,
                    'permissions': permissions,
                }
            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):
    enable_text = BooleanCharField(source='is_active', read_only=True)
    agent_text = serializers.CharField(source='agent.name', read_only=True)
    store_text = serializers.CharField(source='store.name', read_only=True)
    gender_text = serializers.CharField(source='get_gender_display', read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    check_user_text = serializers.CharField(source='check_user.name', read_only=True)
    groups = serializers.SerializerMethodField()
    group_ids = serializers.PrimaryKeyRelatedField(source='groups', many=True, read_only=True)
    manager_barnchs = serializers.SerializerMethodField()

    def get_manager_barnchs(self, obj):
        stores = ManageStoreUser.objects.filter(manage_user=obj)
        return ','.join(stores.values_list('store__name', flat=True))

    def get_groups(self, obj):
        return ','.join(obj.groups.values_list('name', flat=True))

    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        username = self.initial_data['username']
        user = User.objects.filter(username=username).first()
        if user:
            raise CustomError(u'账号[{0}]已存在。'.format(username))
        # 代理商添加的账号，默认就是操作人所在的代理商
        user = self.context['request'].user
        validated_data['create_user'] = user
        validated_data['check_user'] = user
        validated_data['status'] = User.INSERVICE
        instance = super(EmployeeSerializer, self).create(validated_data)
        instance.set_password(validated_data['password'])
        instance.save()
        groups = self.context['request'].data.get('groups', None)
        if groups:
            groups = json.loads(groups)
        else:
            groups = []
        for group in groups:
            instance.groups.add(group)
        return instance

    def update(self, instance, validated_data):
        instance.groups.clear()
        password = instance.password
        validated_data['is_superuser'] = instance.is_superuser
        instance = super(EmployeeSerializer, self).update(instance, validated_data)
        if not 'password' in validated_data or not validated_data['password']:
            instance.password = password
        else:
           instance.set_password(validated_data['password'])
        instance.save()

        groups = self.context['request'].data.get('groups', None)
        if groups:
            groups = json.loads(groups)
        else:
            groups = []
        for group in groups:
            instance.groups.add(group)
        return instance

class PermissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = ('id', 'name',)

class GroupSerializer(serializers.ModelSerializer):
    employees = serializers.SerializerMethodField()
    permissions = PermissionSerializer(many=True, read_only=True)

    def get_employees(self, obj):
        users = obj.user_set.all()
        data = []
        for user in users:
            data.append(user.name)
        return data

    class Meta:
        model = Group
        fields = ('id', 'name', 'permissions', 'employees',)

    def create(self, validated_data):
        user = self.context['request'].user
        validated_data['create_user'] = user
        group = Group.objects.filter(name=validated_data['name']).first()
        if group:
            raise CustomError(u'名称为[%s]的权限组已存在' % validated_data['name'])

        permissions = self.context['request'].data.get('permissions', None)
        if permissions:
            permissions = json.loads(permissions)
        else:
            permissions = []
        instance = super(GroupSerializer, self).create(validated_data)
        instance.permissions.set(permissions)
        return instance

    def update(self, instance, validated_data):
        group = Group.objects.filter(name=validated_data['name']).exclude(id=instance.id).first()
        if group:
            raise CustomError(u'名称为[%s]的权限组已存在' % validated_data['name'])
        permissions = self.context['request'].data.get('permissions', None)
        if permissions:
            permissions = json.loads(permissions)
        else:
            permissions = []
        instance = super(GroupSerializer, self).update(instance, validated_data)
        instance.permissions.set(permissions)
        return instance

class GroupDictSerializer(serializers.ModelSerializer):
    value = serializers.CharField(source='id', read_only=True)

    class Meta:
        model = Group
        fields = ('value', 'name',)
