# 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 Customer


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:
            customer = Customer.login(code, appid)
            if not customer.user:
                return {
                    'openid': customer.openid,
                }

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

            payload = jwt_payload_handler(user)
            return {
                'token': jwt_encode_handler(payload),
                'openid': customer.openid,
                'name': user.name or '',
                'tel': user.tel or '',
                'face': user.face or '',
            }

        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 = Customer.bindWechat(appid, openid, phoneEncryptedData, phoneIv)
            user = customer.user
            payload = jwt_payload_handler(user)
            return {
                'token': jwt_encode_handler(payload),
                'openid': customer.openid,
                'name': user.name or '',
                'tel': user.tel or '',
                'face': user.face or '',
            }

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