# coding=utf-8

import requests
from django.db import transaction
from django.db import models
from django.utils import timezone
from django.conf import settings

from apps.tenant.models import Tenant
from apps.WechatApplet.models import WechatApplet
from apps.account.models import User

from utils.wx.wechat import WeChat
from utils.wx.WXBizDataCrypt import WXBizDataCrypt
from utils.exceptions import CustomError
from apps.tenant.employee.models import Employee

class CustomerWechat(models.Model):
    # wechat_app = models.ForeignKey(WechatApplet, verbose_name=u'小程序', on_delete=models.PROTECT, editable=False)
    customer = models.ForeignKey(Employee, verbose_name=u'用户', on_delete=models.PROTECT, editable=False, null=True)
    openid = models.CharField(max_length=512, verbose_name=u"openid")
    session_key = models.CharField(max_length=512, verbose_name=u'session_key',null=True)

    class Meta:
        db_table = 'customer_wechat'
        verbose_name = u'微信客户'
        unique_together = [
            ('openid')
        ]
        default_permissions = ()

    @staticmethod
    def login(code, appid):
        # wechat_applet = WechatApplet.getByAppid(appid)
        secret = settings.WEAPP['secret']
        res = WeChat.code2Session(appid, secret, code)
        instance = CustomerWechat.objects.filter(openid=res['openid']).first()
        if not instance:
            instance = CustomerWechat.objects.create(
                # wechat_app=wechat_applet,
                openid=res['openid'],
                session_key=res['session_key']
            )
        else:
            instance.session_key = res['session_key']
            instance.save()
        return instance

    @staticmethod
    def bindWechat(appid, openid, phoneEncryptedData, phoneIv):
        customer_wechat = CustomerWechat.objects.filter(openid=openid).first()
        if not customer_wechat:
            raise CustomError(u'未找到相应的微信客户！')

        pc = WXBizDataCrypt(appid, customer_wechat.session_key)
        phon_data = pc.decrypt(phoneEncryptedData, phoneIv)
        tel = phon_data['purePhoneNumber']

        if customer_wechat.customer:
            if customer_wechat.customer.user.username != tel:
                raise CustomError(u'微信绑定的手机号与系统记录的不符！')
            else:
                return customer_wechat.customer

        user = User.objects.filter(username=tel).first()
        if not user:
            user = User.objects.create_customer(tel, password='')

        try:
            with transaction.atomic():
                customer = Employee.getOrRegister(user=user)
        except:
            raise CustomError(u'用户注册失败！')
        customer_wechat.customer = customer
        customer_wechat.save()
        return customer

    @staticmethod
    def sendMsg(user, name, address, fault_des, no):
        wechat_customer = CustomerWechat.objects.filter(customer__user=user, wechat_app__is_authorize=True).first()
        if wechat_customer:
            wechat_customer.wechat_app.sendMsg(wechat_customer.openid, name, address, fault_des, no)
