from django.db import models
from django.db.models import Q
from django.conf import settings

class Option(models.Model):
    CUSTOMER_SOURCE =1
    CATEGORY = 2
    POTENTIAL_LEVEL = 3
    STAGE_PROGRESS = 4
    TYPE_CHOICES = (
        (CUSTOMER_SOURCE, u'客户来源'),
        (CATEGORY, u'项目类别'),
        (POTENTIAL_LEVEL, u'潜客级别'),
        (STAGE_PROGRESS, u'阶段进度'),
    )

    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=1)
    notes = models.CharField(max_length=500, verbose_name=u"备注",null=True)
    enable = models.BooleanField(verbose_name=u"在用", default=True)
    create_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u"创建人", on_delete=models.PROTECT,
                                    editable=False)
    track_day = models.IntegerField(verbose_name=u"跟踪天数", null=True,default=0)
    end_stage = models.BooleanField(verbose_name=u"是否最终阶段", default=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(type, name, exclude_id=None):
        rows = Option.objects.filter(type=type, name=name)
        if exclude_id:
            rows = rows.filter(~Q(id=exclude_id))
        return rows.count()
