#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.WechatApplet.models import WechatApplet
from apps.wxapp.models import CustomerWechat
from apps.log.models import BizLog
from apps.wxapp import customer_log
from utils.exceptions import CustomError
from apps.tenant.employee.models import Employee

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') # 用户code
        appid = self.initial_data.get('appid') # 小程序appid

        if code and appid:
            customer_wechat = CustomerWechat.login(code, appid)
            if not customer_wechat.customer:
                return {
                    'bind': 0,
                    'openid': customer_wechat.openid,
                    'nick_name': settings.WEAPP['nick_name'],
                }

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

            payload = jwt_payload_handler(user)
            customer_log(customer_wechat.customer, BizLog.INSERT, u'用户微信登录，username=%s' % user.username)
            return {
                'bind': 1,
                'user_id': user.id,
                'token': jwt_encode_handler(payload),
                'openid': customer_wechat.openid,
                'tenant_id': customer_wechat.customer.tenant and customer_wechat.customer.tenant.id or '',
                'nick_name': settings.WEAPP['nick_name'],
                'name': customer_wechat.customer.name or '',
                'tel': customer_wechat.customer.tel or '',
                'face': customer_wechat.customer.face,
                'user_type': customer_wechat.customer.type,  # 用户类别，1为平台管理员，2为管理者，3检修人，4报修人
                'forbid_baoxiu': 'true' and customer_wechat.customer.status == Employee.DISABLE or 'false',  # 是否禁用报修,
                'emplate_id': settings.WEAPP['message_template'],
            }

        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)
            customer_log(customer, BizLog.INSERT, u'用户微信登录，username=%s' % user.username)
            return {
                'token': jwt_encode_handler(payload),
                'user_id': user.id,
                'name': customer.name or '',
                'tel': customer.tel or '',
                'face': customer.face,
                'user_type': customer.type,  # 用户类别，1为平台管理员，2为管理者，3检修人，4报修人
                'forbid_baoxiu': 'true' and customer.status == Employee.DISABLE or 'false',  # 是否禁用报修,
                'tenant_id': customer.tenant and customer.tenant.id or '',
            }

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