#coding=utf-8

from django.db import models
from django.utils import timezone

from apps.exceptions import CustomError
from apps.foundation.models import Option
from apps.account.models import Department, User
from django.conf import settings


class FinanceCategory(models.Model):
    name = models.CharField(max_length=100, verbose_name=u"名称")
    enabled = models.BooleanField(verbose_name=u"在用", default=True)
    create_user = models.ForeignKey(User, related_name='finance_category_ref_create_user', verbose_name=u"创建人", editable=False ,on_delete=models.PROTECT)
    create_time = models.DateTimeField(verbose_name=u"创建时间", default=timezone.now)

    class Meta:
        db_table = "finance_category"
        ordering = ['-id']
        verbose_name = u"财务收支类别"
        default_permissions = ()
        permissions = (
            ("view_finance_category", u"查看"),
            ("add_finance_category", u"添加"),
            ("delete_finance_category", u"删除"),
        )

    @staticmethod
    def getById(id):
        try:
            id = int(id)
        except:
            raise CustomError(u'无效的财务收支类别ID')
        instance = FinanceCategory.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的财务收支类别')
        return instance


class FinancePurpose(models.Model):
    PAY = 1
    INCOME = 2

    TYPE_CHOICES = (
        (PAY, u'收入'),
        (INCOME, u'支出'),
    )

    name = models.CharField(max_length=100, verbose_name=u"名称")
    type = models.IntegerField(choices=TYPE_CHOICES, verbose_name=u"收支类型")
    category = models.ForeignKey(FinanceCategory, verbose_name=u"类别", on_delete=models.PROTECT)
    enabled = models.BooleanField(verbose_name=u"在用", default=True)
    create_user = models.ForeignKey(User, related_name='finance_product_ref_create_user', verbose_name=u"创建人", editable=False, on_delete=models.PROTECT)
    create_time = models.DateTimeField(verbose_name=u"创建时间", default=timezone.now)

    class Meta:
        db_table = "finance_purpose"
        ordering = ['-id']
        verbose_name = u"财务收支用途"
        default_permissions = ()
        permissions = ()

    @staticmethod
    def getById(id):
        try:
            id = int(id)
        except:
            raise CustomError(u'无效的财务收支用途ID')
        instance = FinancePurpose.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的财务收支用途')
        return instance


class dbFinanceIncome(models.Model):
    USER_DEFINED = 1
    MATERIAL_ENTRY_PAY = 2
    MATERIAL_ENTRY_UNLOAD = 3
    MATERIAL_ENTRY_FARE = 4
    CONSUMABLE_ENTRY_PAY = 5
    CONSUMABLE_ENTRY_UNLOAD = 6
    CONSUMABLE_ENTRY_FARE = 7
    SALE_ENTRY_PAY = 8
    SALE_ENTRY_UNLOAD = 9
    SALE_ENTRY_FARE = 10

    TYPE_CHOICES = (
        (USER_DEFINED, u'自定义'),
        (MATERIAL_ENTRY_PAY, u'原料入库付款'),
        (MATERIAL_ENTRY_UNLOAD, u'原料入库卸车'),
        (MATERIAL_ENTRY_FARE, u'原料入库运费'),
        (CONSUMABLE_ENTRY_PAY, u'耗材入库付款'),
        (CONSUMABLE_ENTRY_UNLOAD, u'耗材入库卸车'),
        (CONSUMABLE_ENTRY_FARE, u'耗材入库运费'),
        (SALE_ENTRY_PAY, u'销售结算'),
        (SALE_ENTRY_UNLOAD, u'销售装车'),
        (SALE_ENTRY_FARE, u'销售运费'),
    )
    PREFIX_CHOICES = (
        (USER_DEFINED, 'UD'),
        (MATERIAL_ENTRY_PAY, 'MP'),
        (MATERIAL_ENTRY_UNLOAD, 'MU'),
        (MATERIAL_ENTRY_FARE, 'MF'),
        (CONSUMABLE_ENTRY_PAY, 'CP'),
        (CONSUMABLE_ENTRY_UNLOAD, 'CU'),
        (CONSUMABLE_ENTRY_FARE, 'CF'),
        (SALE_ENTRY_PAY, 'SP'),
        (SALE_ENTRY_UNLOAD, 'SU'),
        (SALE_ENTRY_FARE, 'SF'),
    )

    no = models.CharField(max_length=50, verbose_name=u"收银单号", editable=False)
    referer_no = models.CharField(max_length=50, verbose_name=u"引用单据编号", null=True)
    department = models.ForeignKey(Department, related_name='finance_income_ref_department', verbose_name=u'部门',null=True,on_delete=models.PROTECT)
    create_user = models.ForeignKey(User, related_name='finance_income_ref_create_user', verbose_name=u"创建人", on_delete=models.PROTECT, editable=False)
    create_time = models.DateTimeField(verbose_name=u"创建时间", default=timezone.now)
    type = models.IntegerField(choices=TYPE_CHOICES, verbose_name=u"类型", null=True, default=USER_DEFINED)
    amount = models.BigIntegerField(verbose_name=u"金额")
    account = models.ForeignKey(Option, related_name='finance_income_ref_account',verbose_name=u"账户", on_delete=models.PROTECT)
    purpose = models.ForeignKey(FinancePurpose, verbose_name=u"用途", on_delete=models.PROTECT, null=True)
    check_user = models.ForeignKey(User, related_name='finance_income_ref_check_user', verbose_name=u"审核人",
                                    on_delete=models.PROTECT, null=True)
    check_time = models.DateTimeField(verbose_name=u"审核时间", null=True)
    check_status = models.PositiveSmallIntegerField(choices=settings.CHECK_STATUS_CHOICES, verbose_name=u"审核状态", default=settings.DEFAULT)
    notes = models.CharField(max_length=200, verbose_name=u"备注", blank=True, null=True)


    def save(self, *args, **kwargs):
        if self.no == None or self.no == '':
            now = timezone.now()
            rows = dbFinanceIncome.objects.filter(create_time__gte=now.strftime('%Y-%m-%d'),  type=self.type).order_by('-no')
            count = rows.count()
            prefix = dbFinanceIncome.PREFIX_CHOICES[self.type-1][1]
            if count == 0:
                self.no = '%s%s%04d' % (prefix, now.strftime('%Y%m%d'), count + 1)
            else:
                suffix = (rows[0].no[2:])
                self.no = prefix+str(int(suffix) + 1)
        # 自定义收支，引用单号=收银单号
        if not self.referer_no:
            self.referer_no = self.no
        super(dbFinanceIncome, self).save(*args, **kwargs)

    @staticmethod
    def getById(id):
        try:
            id = int(id)
        except:
            raise CustomError(u'无效的财务收支单ID')
        instance = dbFinanceIncome.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的收支单')
        return instance

    class Meta:
        db_table = "finance_income"
        verbose_name = u"收支管理"
        ordering = ('-id',)
        unique_together = (
            'no',
        )
        permissions = (
            ("view_finance_income", u"查看"),
            ("add_finance_income", u"添加"),
            ("check_finance_income", u"审核"),
        )
