# coding=utf-8
from django.db import models
from django.conf import settings
from django.utils import timezone

from utils.exceptions import CustomError
from apps.option.models import Option


class ReportCustomer(models.Model):
    NOT_CHECKED = 0
    CHECKED = 1
    REPEAT_REPORT = 2
    STATUS_CHOICES = (
        (NOT_CHECKED, '待审核'),
        (CHECKED, '已审核'),
        (REPEAT_REPORT, '重复报备')
    )

    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'性别',
                                              default=settings.MALE)
    village = models.CharField(max_length=100, verbose_name=u'小区')
    address = models.CharField(max_length=100, verbose_name=u'地址')
    source = models.ForeignKey(Option, verbose_name=u'来源', related_name='customer_source', on_delete=models.PROTECT)
    project = models.ManyToManyField(Option, verbose_name=u'项目', related_name='customer_category', editable=False, null=True,blank=True)
    notes = models.CharField(max_length=500, verbose_name=u"备注", null=True)
    report_status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, verbose_name=u'报备状态', default=NOT_CHECKED)
    check_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u'审核人', related_name='customer_check_user',
                                   on_delete=models.PROTECT, null=True)
    check_time = models.DateTimeField(verbose_name=u'审核时间', null=True)
    create_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u'添加人', related_name='customer_create_user',
                                    editable=False, on_delete=models.PROTECT)
    create_time = models.DateTimeField(verbose_name=u'添加时间', auto_now_add=True, editable=False)


    class Meta:
        db_table = 'report_customer'
        verbose_name = u'客户报备'
        ordering = ['-id']
        default_permissions = ()
        permissions = [
            ('view_customer', u'查看'),
            ('add_customer', u'添加'),
            ('update_customer', u'更新'),
            ('delete_customer', u'删除'),
            ('check_customer', u'审核'),
        ]

    def check_customer(self, user):
        # 审核
        if self.report_status == ReportCustomer.REPEAT_REPORT:
            raise CustomError('当前客户报备状态为重复报备！')

        if self.report_status == ReportCustomer.NOT_CHECKED:
            self.check_user = user
            self.report_status = ReportCustomer.CHECKED
            self.check_time = timezone.now()
            self.save()
        # if self.report_status == Customer.CHECKED:
        #     # 撞单
