# coding=utf-8

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
from apps.account.models import User


class Customer(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, on_delete=models.PROTECT, verbose_name=u'用户')
    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.TextField(verbose_name=u'头像', null=True, blank=True)

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

    @staticmethod
    def getOrRegister(user):
        customer = Customer.objects.filter(user=user).first()
        if customer:
            return customer
        with transaction.atomic():
            customer = Customer.objects.create(user=user, tel=user.username, name=user.username)
        return customer

    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):
        secret = Config.getConfigValue(Config.KEY_WECHAT_SESSION_KEY)
        appid = Config.getConfigValue(Config.KEY_WECHAT_APPID)
        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)

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

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

        customer_wechat.customer = customer
        customer_wechat.save()
        return customer

class CustomerVehicle(models.Model):
    customer = models.ForeignKey(Customer, verbose_name=u'客户', on_delete=models.PROTECT, editable=False)
    name = models.CharField(max_length=100, verbose_name=u"姓名")
    tel = models.CharField(max_length=50, verbose_name=u'电话')
    vin = models.CharField(max_length=20, null=True, verbose_name=u'电话')
    number = models.CharField(max_length=20, verbose_name=u'车牌号')
    model = models.CharField(max_length=200, verbose_name=u'车型')
    inspect_end_date = models.DateField(verbose_name=u'年检到期', null=True)
    insure_end_date = models.DateField(verbose_name=u'保险到期', null=True)
    delete = models.BooleanField(verbose_name=u"删除", default=False)

    class Meta:
        db_table = 'customer_vehicle'
        verbose_name = u'客户车辆'
        ordering = ['-id']
        default_permissions = ()


class CustomerAddress(models.Model):
    customer = models.ForeignKey(Customer, verbose_name=u'客户', on_delete=models.PROTECT, editable=False)
    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"详细地址")
    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'客户地址'
        ordering = ['-id']
        default_permissions = ()

    def destory(self, queryset):
        if self.default:
            self.default = False
            default = queryset.first()
            if default:
                default.default = True
                default.save()
        self.delete = True
        self.save()
    
    
