# coding=utf-8

from django.db import models

from apps.exceptions import CustomError


class Supplier(models.Model):
    MATERIAL = 0
    CONSUMABLE = 1
    TYPE_CHOICES = (
        (MATERIAL, u'原料'),
        (CONSUMABLE, u'耗材'),
    )
    TYPE_CHOICES_DICT = [{'id': x, 'value': y} for x, y in TYPE_CHOICES]

    name = models.CharField(max_length=100, verbose_name=u"名称")
    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, verbose_name=u"类型", default=MATERIAL)
    contacts = models.CharField(max_length=100, verbose_name=u"联系人", null=True, blank=True)
    phone_number = models.CharField(max_length=100, verbose_name=u"电话", null=True, blank=True)
    address = models.CharField(max_length=100, verbose_name=u"地址", null=True, blank=True)
    opening_bank = models.CharField(max_length=100, verbose_name=u"开户行", null=True, blank=True)
    account = models.CharField(max_length=100, verbose_name=u"账号", null=True, blank=True)
    tax_number = models.CharField(max_length=100, verbose_name=u"税号", null=True, blank=True)
    credit_code = models.CharField(max_length=100, verbose_name=u"信用代码", null=True, blank=True)
    notes = models.CharField(max_length=500, verbose_name=u"备注", null=True, blank=True)
    enabled = models.BooleanField(verbose_name=u"在用", default=True)

    class Meta:
        db_table = "supplier"
        verbose_name = u"供应商管理"
        ordering = ('-id',)
        index_together = (
            'name',
            'phone_number',
        )
        default_permissions = ()
        permissions = (
            ("view_supplier", u"浏览"),
            ("add_supplier", u"添加"),
            ("import_supplier", u"导入"),
            ("export_supplier", u"导出"),
            ("delete_supplier", u"删除")
        )

    @staticmethod
    def getById(id):
        instance = Supplier.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的供应商')
        return instance
