# coding=utf-8

from django.contrib.auth import get_user_model

from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from apps.customer.models import *
from apps.log.models import BizLog


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


class WechatLoginSerializer(serializers.Serializer):
    def validate(self, attrs):
        code = self.initial_data.get('code')
        appid = self.initial_data.get('appid')

        if code and appid:
            wx_customer = CustomerWechat.login(code, appid)
            if not wx_customer.customer:
                return {
                    'bind': 0,
                    'openid': wx_customer.openid
                }

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

            payload = jwt_payload_handler(user)
            BizLog.objects.addnew(user, BizLog.INSERT, u'用户微信登录，username=%s' % user.username)
            return {
                'bind': 1,
                'token': jwt_encode_handler(payload),
                'openid': wx_customer.openid,
                'name': wx_customer.customer.name or '',
                'tel': wx_customer.customer.tel or '',
                'face': wx_customer.customer.face and wx_customer.customer.face.get_path() or '',
                'gender': wx_customer.customer.gender or 0,
            }

        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)
            user = customer.user
            payload = jwt_payload_handler(user)
            BizLog.objects.addnew(user, BizLog.INSERT, u'用户微信登录，username=%s' % user.username)
            return {
                'token': jwt_encode_handler(payload),
                'name': customer.name or '',
                'tel': customer.tel or '',
                'face': customer.face and customer.face.get_path() or '',
                'gender': customer.gender or 0
            }

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


class CustomerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Customer
        fields = '__all__'

