#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.tenant.models import Tenant
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)
            tenant_id = customer_wechat.customer.tenant and customer_wechat.customer.tenant.id or ''
            tenant_edition = customer_wechat.customer.tenant and customer_wechat.customer.tenant.edition or Tenant.EDITION_1
            company_no = customer_wechat.customer.tenant and customer_wechat.customer.tenant.company_no or ''
            nick_name = customer_wechat.customer.tenant and customer_wechat.customer.tenant.company_name or settings.WEAPP['nick_name']
            is_validity = Tenant.check_validity(company_no)
            return {
                'bind': 1,
                'user_id': user.id,
                'token': jwt_encode_handler(payload),
                'openid': customer_wechat.openid,
                'tenant_id': tenant_id,
                'tenant_edition': tenant_edition,
                'is_validity': is_validity,
                'nick_name': 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_finish'],settings.WEAPP['message_template_wait_check'],
                               settings.WEAPP['message_template_dispatch'],],
            }

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

        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)
            tenant_id = ''
            tenant_edition = Tenant.EDITION_1
            nick_name = settings.WEAPP['nick_name']
            if customer.tenant:
                tenant_id = customer.tenant.id
                company_no = customer.tenant.company_no
                nick_name = customer.tenant.company_name
                tenant_edition = customer.tenant.edition
            elif company_no:
                # 扫二维码，没有绑定企业的用户之间绑定企业
                tenant = Tenant.objects.filter(company_no=company_no).first()
                if tenant:
                    customer.tenant = tenant
                    customer.save()
                    tenant_id = tenant.id
                    company_no = tenant.company_no
                    nick_name = tenant.company_name
                    tenant_edition = tenant.edition
            is_validity = Tenant.check_validity(company_no)
            return {
                'token': jwt_encode_handler(payload),
                'user_id': user.id,
                'name': customer.name or '',
                'tel': customer.tel or '',
                'face': customer.face,
                'nick_name': nick_name,
                'is_validity': is_validity,
                'user_type': customer.type,  # 用户类别，1为平台管理员，2为管理者，3检修人，4报修人
                'forbid_baoxiu': 'true' and customer.status == Employee.DISABLE or 'false',  # 是否禁用报修,
                'tenant_id': tenant_id,
                'tenant_edition': tenant_edition,
                'emplate_id': [settings.WEAPP['message_template_finish'],settings.WEAPP['message_template_wait_check'],
                               settings.WEAPP['message_template_dispatch'],],
            }

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