# coding=utf-8

import json
from django.conf import settings
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 CustomerWechat
from apps.option.models import School, CommodityLevel
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)

                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)
    create_user_text = serializers.CharField(source='create_user.name', read_only=True)
    gender_text = serializers.CharField(source='get_gender_display', read_only=True)
    type_text = serializers.CharField(source='get_type_display', read_only=True)
    date_joined_f = serializers.DateTimeField(source='date_joined', format=settings.SHORT_DATETIME_FORMAT,
                                              read_only=True)
    category_text = serializers.SerializerMethodField()
    school_text = serializers.SerializerMethodField()
    category_ids = serializers.SerializerMethodField()
    groups = serializers.SerializerMethodField()
    group_ids = serializers.PrimaryKeyRelatedField(source='groups', many=True, read_only=True)

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

    def get_category_ids(self, obj):
        return obj.category.split(',')

    def get_school_text(self, obj):
        name = ''
        if obj.school:
            rows = School.objects.filter(id__in=obj.school.split(','))
            for row in rows:
                name += row.name + '，'
        return name

    def get_category_text(self, obj):
        name = ''
        if obj.category:
            rows = CommodityLevel.objects.filter(id__in=obj.category.split(','))
            for row in rows:
                name1 = row.name
                if row.category:
                    name1 = '{}-{}'.format(row.category.name, name1)
                    if row.category.category:
                        name1 = '{}-{}'.format(row.category.category.name, name1)
                name += name1 + '，'
        return name

    class Meta:
        model = User
        # fields = '__all__'
        exclude = ('password',)

    def create(self, validated_data):
        username = self.initial_data['username']
        user = User.objects.filter(username=username,).first()
        if user:
            # 用户可能先登录小程序，创建了user，此时在添加账号，user已经存在了。
            if user.type <= User.AGENT:
                raise CustomError(u'账号[{0}]已存在。'.format(username))
            else:
                validated_data['is_active'] = self.initial_data['is_active'] == '1'
                validated_data['create_user'] = self.context['request'].user
                instance = super(EmployeeSerializer, self).update(user, validated_data)
        else:
            validated_data['is_active'] = self.initial_data['is_active'] == '1'
            user = self.context['request'].user
            validated_data['create_user'] = user
            instance = super(EmployeeSerializer, self).create(validated_data)
        instance.set_password(self.initial_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):
        username = self.initial_data['username']
        user = User.objects.filter(username=username).exclude(id=instance.id).first()
        if user:
            raise CustomError(u'账号[{0}]和代理商账号、游客账号或其他员工账号重复，禁止修改。'.format(username))
        instance.groups.clear()
        password = instance.password
        validated_data['is_superuser'] = instance.is_superuser
        validated_data['is_active'] = self.initial_data['is_active'] == '1'
        instance = super(EmployeeSerializer, self).update(instance, validated_data)
        if not 'password' in self.initial_data or not self.initial_data['password']:
            instance.password = password
        else:
           instance.set_password(self.initial_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',)

class WechatLoginSerializer(serializers.Serializer):
    def validate(self, attrs):
        code = self.initial_data.get('code') # 用户code
        appid = self.initial_data.get('appid') # 小程序appid
        if code and appid:
            customer_wechat = CustomerWechat.login(code, appid)
            if not customer_wechat.customer:
                return {
                    'openid': customer_wechat.openid,
                }

            user = customer_wechat.customer
            if not user.is_active:
                msg = '用户帐户已禁用.'
                raise serializers.ValidationError(msg)

            payload = jwt_payload_handler(user)

            return {
                'user_id': user.id,
                'token': jwt_encode_handler(payload),
                'openid': customer_wechat.openid,
                'name': customer_wechat.customer.name or '',
                'tel': customer_wechat.customer.username or '',
                'face': customer_wechat.customer.face,
            }

        else:
            msg = '参数无效'
            raise serializers.ValidationError(msg)

class WechatBindSerializer(serializers.Serializer):
    def validate(self, attrs):
        appid = self.initial_data.get('appid')
        openid = self.initial_data.get('openid')
        phoneEncryptedData = self.initial_data.get('encryptedData')
        phoneIv = self.initial_data.get('iv')

        if openid and phoneEncryptedData and phoneIv:
            customer = CustomerWechat.bindWechat(appid, openid, phoneEncryptedData, phoneIv)
            payload = jwt_payload_handler(customer)
            return {
                'token': jwt_encode_handler(payload),
                'user_id': customer.id,
                'name': customer.name or '',
                'tel': customer.username or '',
                'face': customer.face,
            }

        else:
            msg = '参数无效'
            raise serializers.ValidationError(msg)
