#coding=utf-8

from django.contrib.auth import get_user_model
from django.conf import settings
from django.db.models import Q

from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from apps.customer.models import Customer, CustomerWechat, CustomerAddress
from apps.foundation.models import BizLog, Config
from utils.exceptions import CustomError
from apps.account import tenant_log


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


class CustomerMobileSignSerializer(serializers.Serializer):
    def validate(self, attrs):
        mobile = self.initial_data.get('mobile')
        appid = Config.getConfigValue(Config.KEY_WECHAT_APPID)

        if mobile and appid:
            user = User.objects.filter(username=mobile).first()
            if not user:
                user = User.objects.create_customer(username=mobile)

            if user.status == User.DIMISSION:
                msg = '该账户已被禁用'
                raise serializers.ValidationError(msg)

            try:
                customer = Customer.getOrRegister(user=user)
            except:
                msg = '客户注册失败！'
                raise serializers.ValidationError(msg)

            payload = jwt_payload_handler(user)

            return {
                'token': jwt_encode_handler(payload),
                'user_id': user.id,
                'customer': customer.id,
                'username': user.username,
                'name': customer.name or '',
                'tel': customer.tel or '',
                'face': customer.face or '',
                'gender': customer.gender or 0,
            }
        else:
            msg = '参数无效'
            raise serializers.ValidationError(msg)


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

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

            user = customer_wechat.customer.user
            if user.status == User.DIMISSION:
                msg = '用户帐户已禁用.'
                raise serializers.ValidationError(msg)

            payload = jwt_payload_handler(user)
            tenant_log(user, BizLog.INSERT, u'用户微信登录，username=%s' % user.username)
            result = {
                'bind': 1,
                'token': 'JWT {}'.format(jwt_encode_handler(payload)),
                'openid': customer_wechat.openid,
                'customer': customer_wechat.customer_id,
                'name': customer_wechat.customer.name or '',
                'tel': customer_wechat.customer.tel or '',
                'face': customer_wechat.customer.face or '',
                'gender': customer_wechat.customer.gender or 0,
            }
            return result

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

class WechatBindSerializer(serializers.Serializer):
    def validate(self, attrs):
        appid = Config.getConfigValue(Config.KEY_WECHAT_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)
            tenant_log(user, BizLog.INSERT, u'用户微信登录，username=%s' % user.username)

            return {
                'token': 'JWT {}'.format(jwt_encode_handler(payload)),
                'customer': customer.id or '',
                'name': customer.name or '',
                'tel': customer.tel or '',
                'face': customer.face or '',
                'gender': customer.gender or 0,
            }

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


class CustomerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Customer
        fields = ('name', 'tel', 'face')


class CustomerAddressSerializer(serializers.ModelSerializer):
    full_addr = serializers.SerializerMethodField()

    def get_full_addr(self, obj):
        full_addr = obj.area + obj.addr
        return full_addr

    class Meta:
        model = CustomerAddress
        fields = '__all__'

    def create(self, validated_data):
        customer = self.context['request'].customer
        validated_data['customer'] = customer
        if validated_data['default']:
            CustomerAddress.objects.filter(Q(customer=customer), Q(delete=False)).update(default=False)
        instance = super(CustomerAddressSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        if instance.delete:
            raise CustomError(u'该收货地址已经被删除,禁止操作')
        if validated_data['default']:
            CustomerAddress.objects.filter(Q(customer=instance.customer), Q(delete=False), ~Q(id=instance.id)).update(default=False)
        instance = super(CustomerAddressSerializer, self).update(instance, validated_data)
        return instance
