# coding=utf-8

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

from apps.wechat.models import Wechat

from utils.wx.wechat import WeChat
from utils.wx.WXBizDataCrypt import WXBizDataCrypt
from utils.exceptions import CustomError

User = get_user_model()


class Customer(models.Model):
    app = models.ForeignKey(Wechat, verbose_name=u'小程序', on_delete=models.PROTECT, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, related_name='customer_ref_user_id', on_delete=models.PROTECT, verbose_name=u'用户')
    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"
        verbose_name = u"客户管理"
        ordering = ['-id']
        unique_together = [
            ('openid')
        ]
        index_together = ()
        default_permissions = ()

    @staticmethod
    def login(code, appid):
        app = Wechat.getByAppid(appid)
        res = WeChat.code2Session(appid, app.secret, code)
        instance = Customer.objects.filter(openid=res['openid'], app__appid=appid).first()
        if not instance:
            instance = Customer.objects.create(
                app=app,
                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 = Customer.objects.filter(openid=openid, app__appid=appid).first()
        if not customer:
            raise CustomError(u'未找到相应的微信客户！')

        pc = WXBizDataCrypt(appid, customer.session_key)
        phon_data = pc.decrypt(phoneEncryptedData, phoneIv)

        tel = phon_data['purePhoneNumber']

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

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

        customer.user = user
        customer.save()
        return customer
