# coding=utf-8

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


class Option(models.Model):
    COMMODITY_CATEGORY = 1
    EXPRESS_COMPANY = 2

    TYPE_CHOICES = (
        (COMMODITY_CATEGORY, u'商品类别'),
        (EXPRESS_COMPANY, 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=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'创建人', editable=False, on_delete=models.PROTECT)
    create_time = models.DateTimeField(verbose_name=u"创建时间", default=timezone.now, editable=False)

    class Meta:
        db_table = "system_option"
        verbose_name = u'自定义项'
        ordering = ['type', 'sort', ]
        index_together = (
            'type',
            'name',
        )
        default_permissions = ()
        permissions = []

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