# 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
from apps.base import Formater


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 '',
                'customer_id': wx_customer.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')
        referrer = self.initial_data.get('referrer')

        if openid and phoneEncryptedData and phoneIv:
            customer = CustomerWechat.bindWechat(appid, openid, phoneEncryptedData, phoneIv, referrer)
            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 '',
                'customer_id': customer.id,
            }

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


class CustomerSerializer(serializers.ModelSerializer):
    gender_text = serializers.CharField(source='get_gender_display', read_only=True)
    is_distributor_text = serializers.SerializerMethodField()
    balance = serializers.SerializerMethodField()
    total_amount = serializers.SerializerMethodField()
    date_join = serializers.DateTimeField(source='user.date_joined', format='%Y-%m-%d %H:%M', read_only=True)

    class Meta:
        model = Customer
        fields = '__all__'

    def get_is_distributor_text(self, obj):
        if obj.is_distributor:
            return u'是'
        return u'否'

    def get_balance(self, obj):
        return Formater.formatAmountShow(obj.balance)

    def get_total_amount(self, obj):
        return Formater.formatAmountShow(obj.total_amount)
