#coding=utf-8
from django.db import models
from django.db.models import Sum
from django.utils import timezone

from apps.account.models import User, Department
from apps.exceptions import CustomError
from apps.product.models import ProductBase
from apps.warehouse.models import Warehouse, WarehouseStock, WarehouseStockRecord
from django.conf import settings

class Goods(models.Model):
    product_base = models.ForeignKey(ProductBase, verbose_name=u"产品", on_delete=models.PROTECT, blank=True)
    retail_price = models.BigIntegerField(verbose_name=u"销售价", help_text=u"元", default=0)
    standard = models.CharField(max_length=100, verbose_name=u"标准", null=True, blank=True)
    goods_pack = models.CharField(max_length=100, verbose_name=u"包装", null=True, blank=True)

    class Meta:
        db_table = "goods"
        verbose_name = u"成品产品管理"
        ordering = ('-id',)
        default_permissions = ()
        permissions = (
            ("view_goods", u"浏览"),
            ("add_goods", u"添加"),
            ("delete_goods", u"删除"),
            ("export_goods", u"导出"),
            ("import_goods", u"导入"),
            ("view_goods_cost", u"查看成本"),
        )

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

    @staticmethod
    def getByBaseId(base_id):
        instance = Goods.objects.filter(product_base_id=base_id).first()
        if not instance:
            raise CustomError(u'未找到相应的成品')
        return instance

class GoodsGodownEntry(models.Model):
    no = models.CharField(max_length=20, verbose_name=u"入库单号", editable=False)
    warehouse = models.ForeignKey(Warehouse, verbose_name=u'仓别', on_delete=models.PROTECT)
    create_time = models.DateTimeField(verbose_name=u"创建时间", default=timezone.now)
    create_user = models.ForeignKey(User, related_name='goods_godown_entry_ref_create_user', verbose_name=u"创建人", on_delete=models.PROTECT, editable=False)
    department = models.ForeignKey(Department, verbose_name=u"创建部门", on_delete=models.PROTECT, editable=False)
    check_time = models.DateTimeField(verbose_name=u"审核时间", blank=True, null=True)
    check_user = models.ForeignKey(User, related_name='goods_godown_entry_ref_check_user', verbose_name=u"审核人", on_delete=models.PROTECT, blank=True, null=True)
    status = models.PositiveSmallIntegerField(choices=settings.CHECK_STATUS_CHOICES, default=settings.DEFAULT, verbose_name=u"审核状态")
    notes = models.CharField(max_length=200, verbose_name=u"备注", blank=True, null=True)

    total_count = models.BigIntegerField(verbose_name=u'合计数量', default=0)
    total_amount = models.BigIntegerField(verbose_name=u'合计金额', default=0)
    total_invoice_amount = models.BigIntegerField(verbose_name=u'发票金额合计', default=0)  # 等于明细里面的发票金额合计
    total_deliver_count = models.BigIntegerField(verbose_name=u"出库数量合计", default=0)
    total_deliver_amount = models.BigIntegerField(verbose_name=u"出库金额合计", default=0)

    class Meta:
        db_table = "goods_godown_entry"
        verbose_name = u"入库管理"
        ordering = ('-id',)
        index_together = (
            'create_time', 'check_time', 'status'
        )
        unique_together = (
            'no',
        )
        default_permissions = ()
        permissions = (
            ("view_goods_godown_entry", u"浏览"),
            ("add_goods_godown_entry", u"添加"),
            ("check_goods_godown_entry", u"审核"),
            ("delete_goods_godown_entry", u"删除"),
            ("export_goods_godown_entry", u"导出"),
            ("import_goods_godown_entry", u"导入"),
            ("print_goods_godown_entry", u"打印"),
            ("edit_goods_godown_entry", u"高级修改"),
        )

    @staticmethod
    def getById(id):
        instance = GoodsGodownEntry.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的成品入库单')
        return instance

    def save(self, *args, **kwargs):
        if self.no == None or self.no == '':
            now = timezone.now()
            rows = GoodsGodownEntry.objects.filter(create_time__gte=now.strftime('%Y-%m-%d')).order_by('-no')
            count = rows.count()
            if count == 0:
                self.no = 'GR%s%03d' % (now.strftime('%Y%m%d'), count + 1)
            else:
                self.no = rows[0].no[:2] + str(int(rows[0].no[2:]) + 1)
        super(GoodsGodownEntry, self).save(*args, **kwargs)

    def update_total(self):
        total_count = 0
        total_amount = 0
        total_invoice_amount = 0
        sum_row = GoodsGodownEntryDetail.objects.filter(main=self).aggregate(total_count=Sum('count'),
                                                total_amount=Sum('amount'), total_invoice_amount=Sum('invoice_amount'))
        if sum_row:
            total_count = sum_row['total_count'] or 0
            total_amount = sum_row['total_amount'] or 0
            total_invoice_amount = sum_row['total_invoice_amount'] or 0
        self.total_count = total_count
        self.total_amount = total_amount
        self.total_invoice_amount = total_invoice_amount
        self.save()

    def update_redundant(self):
        sum_count = 0
        sum_amount = 0
        sum_row = GoodsGodownEntryDetail.objects.filter(main=self).aggregate(sum_count=Sum('deliver_count'),
                                                                             sum_amount=Sum('deliver_amount'))
        if sum_row:
            sum_count = sum_row['sum_count'] or 0
            sum_amount = sum_row['sum_amount'] or 0
        self.total_deliver_count = sum_count
        self.total_deliver_amount = sum_amount
        self.save()


class GoodsGodownEntryDetail(models.Model):
    main = models.ForeignKey(GoodsGodownEntry, related_name='goods_godown_entry_detail_ref_main', verbose_name=u"成品入库单", on_delete=models.PROTECT)
    goods = models.ForeignKey(Goods, verbose_name=u"成品", on_delete=models.PROTECT)
    count = models.BigIntegerField(verbose_name=u"数量", default=0)
    price = models.BigIntegerField(verbose_name=u'单价', default=0)
    warehouse_stock = models.ForeignKey(WarehouseStock, verbose_name=u'仓别库存', on_delete=models.PROTECT, editable=False)
    stock_record = models.ForeignKey(WarehouseStockRecord, verbose_name=u'库存记录', on_delete=models.PROTECT, null=True, blank=True, related_name='goods_godown_entry_detail_ref_stock_record')

    amount = models.BigIntegerField(verbose_name=u'金额', default=0)
    invoice_amount = models.BigIntegerField(verbose_name=u'发票金额', default=0) #手工录入
    deliver_count = models.BigIntegerField(verbose_name=u"出库数量", default=0)
    deliver_amount = models.BigIntegerField(verbose_name=u"出库金额", default=0)
    notes = models.CharField(max_length=200, verbose_name=u"备注", blank=True, null=True)

    class Meta:
        db_table = "goods_godown_entry_detail"
        verbose_name = u"盘存管理"
        ordering = ('-id',)
        default_permissions = ()
        permissions = ( # 成品入库明细
            ("view_goods_inventory", u"浏览"),
            ("add_goods_inventory", u"添加"),
            ("check_goods_inventory", u"审核"),
            ("delete_goods_inventory", u"删除"),
            ("export_goods_inventory", u"导出"),
            ("print_goods_inventory", u"打印"),
        )