# 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.images.models import Images
from utils.wx.wechat import WeChat
from utils.wx.WXBizDataCrypt import WXBizDataCrypt
from utils.exceptions import CustomError
from apps.foundation.models import Config


class Customer(models.Model):
    name = models.CharField(max_length=100, verbose_name=u"姓名")
    tel = models.CharField(max_length=50, verbose_name=u'电话')
    gender = models.PositiveSmallIntegerField(choices=settings.GENDER_CHOICES, verbose_name=u'性别', null=True)
    create_time = models.DateTimeField(verbose_name=u"添加时间", default=timezone.now, editable=False)
    face = models.ForeignKey(Images, verbose_name=u'头像', on_delete=models.PROTECT, null=True)

    class Meta:
        db_table = "customer"
        verbose_name = u"客户管理"
        ordering = ['-id']
        index_together = (
            'name',
            'tel',
        )
        default_permissions = ()

    def setInfo(self, nickName, gender, avatarUrl):
        self.name = nickName
        if gender == 1:
            self.gender = settings.MALE
        elif gender == 2:
            self.gender = settings.FEMALE
        else:
            self.gender = settings.UNKNOW
        if self.face == None and avatarUrl != None:
            self.face = Images.downLoadFace(self, avatarUrl)
        self.save()


class CustomerWechat(models.Model):
    customer = models.ForeignKey(Customer, 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):
        secret = Config.getConfigValue(Config.KEY_WECHAT_SESSION_KEY)
        res = WeChat.code2Session(appid, secret, code)
        instance = CustomerWechat.objects.filter(openid=res['openid']).first()
        if not instance:
            instance = CustomerWechat.objects.create(
                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

        customer = Customer.objects.filter(tel=tel).first()
        if not customer:
            Customer.objects.create(tel=tel, name=tel)
        customer_wechat.customer = customer
        customer_wechat.save()
        return customer

class CustomerVehicle(models.Model):
    customer = models.ForeignKey(Customer, verbose_name=u'客户', on_delete=models.PROTECT)
    number = models.CharField(max_length=20)
    model = models.CharField(max_length=200)
    mileage = models.FloatField(verbose_name=u"车辆里程")
    img = models.ForeignKey(Images, verbose_name=u'行驶证', on_delete=models.PROTECT, null=True)

    class Meta:
        db_table = 'customer_vehicle'
        verbose_name = u'客户车辆'
        default_permissions = ()


class CustomerAddress(models.Model):
    customer = models.ForeignKey(Customer, verbose_name=u'客户', on_delete=models.PROTECT)
    name = models.CharField(max_length=100, verbose_name=u"姓名")
    tel = models.CharField(max_length=50, verbose_name=u'电话')
    area = models.CharField(max_length=200, verbose_name=u"地区")
    addr = models.CharField(max_length=500, verbose_name=u"详细地址")
    is_default = models.BooleanField(verbose_name=u"默认", default=False)
    delete = models.BooleanField(verbose_name=u"删除", default=False)
    create_time = models.DateTimeField(verbose_name=u"添加时间", default=timezone.now, editable=False)

    class Meta:
        db_table = 'customer_address'
        verbose_name = u'客户地址'
        default_permissions = ()
    
    
