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

class Tenant(models.Model):

    company_no = models.CharField(max_length=10, verbose_name=u'单位编号', blank=True, null=True)
    company_name = models.CharField(max_length=200, verbose_name=u'单位名称', blank=True, null=True)
    organ_code = models.CharField(max_length=200, verbose_name=u'组织代码', blank=True, null=True)
    # images = models.ForeignKey('Upload', verbose_name='营业执照图片',on_delete=models.PROTECT, blank=True)
    name = models.CharField(max_length=20, verbose_name=u'联系人名称')
    tel = models.CharField(max_length=20, verbose_name=u'联系人电话')
    address = models.CharField(max_length=20, verbose_name=u'地址', blank=True, null=True)
    create_time = models.DateTimeField(verbose_name=u'申请时间', auto_now_add=True, editable=False)
    end_date = models.DateField(verbose_name=u'到期时间', editable=False, blank=True, null=True)
    status = models.PositiveSmallIntegerField(choices=settings.CHECK_STATE_CHOICES, verbose_name=u'审核状态',
                                              default=settings.DEFAULT)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u"申请人", on_delete=models.PROTECT,
                             editable=False, null=True)
    reject_reason = models.CharField(max_length=200, verbose_name=u'拒绝原因', blank=True, null=True)
    delete = models.BooleanField(verbose_name=u'删除', default=False, editable=False)

    class Meta:
        db_table = 'tenant'
        ordering = ['-id']
        verbose_name = '租户'
        default_permissions = ()

    def get_no(self):
        now = int(timezone.now().strftime('%H%M%S')) * 1.3
        no = '{0}{1}'.format(self.id, now)
        return no

    @staticmethod
    def is_exist(company_name, exclude_id=None):
        rows = Tenant.objects.filter(delete=False, company_name=company_name)
        if exclude_id:
            rows = rows.filter(~Q(id=exclude_id))
        return rows.count()

    @staticmethod
    def getById(id):
        try:
            id = int(id)
        except:
            raise CustomError(u'无效的租户id！')
        tenant = Tenant.objects.filter(id=id, delete=False).first()
        if not tenant:
            raise CustomError(u'未找到相应的租户信息！')
        return tenant


class RenewLog(models.Model):

    tenant = models.ForeignKey(Tenant, verbose_name=u"租户", on_delete=models.PROTECT, editable=False, )
    amount = models.FloatField(verbose_name='金额')
    create_time = models.DateTimeField(verbose_name=u'续费时间', auto_now_add=True, editable=False)
    end_date = models.DateField(verbose_name=u'到期时间', editable=False, blank=True, null=True)

    class Meta:
        db_table = 'tenant_renew_log'
        ordering = ['-id']
        verbose_name = '租户续费记录'
