from django.db import models
from apps.tenant.models import Tenant
from django.db.models import Q
from django.conf import settings

class Option(models.Model):
    REPAIRS_TYPE =1
    FAULT_CAUSE = 2
    TYPE_CHOICES = (
        (REPAIRS_TYPE, u'报修类型'),
        (FAULT_CAUSE, u'故障原因'),
    )

    tenant = models.ForeignKey(Tenant, verbose_name=u'租户', on_delete=models.PROTECT, editable=False)
    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, verbose_name=u"类别")
    name = models.CharField(verbose_name=u'名称', max_length=100)
    sort = models.PositiveSmallIntegerField(verbose_name=u'排序', help_text=u'越小越靠前', default=0)
    notes = models.CharField(max_length=500, verbose_name=u"备注",null=True)
    enable = models.BooleanField(verbose_name=u"在用", default=True)
    delete = models.BooleanField(verbose_name=u"删除", default=False, editable=False)
    create_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u"创建人", on_delete=models.PROTECT,
                                    editable=False)

    class Meta:
        db_table = 'system_option'
        verbose_name = u"系统选项"
        ordering = ['type', 'sort', ]
        index_together = (
            'type',
            'name',
        )
        default_permissions = ()
        permissions = [
            ('browse_option', u'查看'),
            ('add_option', u'添加'),
            ('delete_option', u'删除'),
        ]

    @staticmethod
    def is_exist(tenant, type, name, exclude_id=None):
        rows = Option.objects.filter(tenant=tenant, type=type, name=name, delete=False)
        if exclude_id:
            rows = rows.filter(~Q(id=exclude_id))
        return rows.count()
