# 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.foundation.models import BizLog
from apps.customer.tool import WechatHandel

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


class WechatLoginSerializer(serializers.Serializer):
    def validate(self, attrs):
        code = self.initial_data.get('code') # 用户code
        appid = self.initial_data.get('appid') # 小程序appid
        activity_id = self.initial_data.get('activity_id') # 活动id

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

            user = customer_wechat.customer.user
            if not user.enabled:
                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': customer_wechat.openid,
                'name': customer_wechat.customer.name or '',
                'tel': customer_wechat.customer.tel or '',
                'face': customer_wechat.customer.face or '',
                'activity_id': activity_id,
                'user_id': customer_wechat.customer.id,
            }

        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')
        activity_id = self.initial_data.get('activity_id')

        if openid and phoneEncryptedData and phoneIv:
            customer = WechatHandel.bindWechat(appid, openid, phoneEncryptedData, phoneIv, activity_id)
            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 or '',
                'gender': customer.gender or 0,
                'user_id': customer.id,
            }

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