# coding=utf-8
from django.db.models import Sum
from django.utils import timezone
from apps.foundation.models import Option
from apps.customer.models import Customer
from apps.exceptions import CustomError
from django.db import models
from django.conf import settings
from apps.account.models import User, Department
from apps.goods.models import Goods


class SalePlan(models.Model):
    no = models.CharField(max_length=20, verbose_name=u"单号", editable=False)
    customer = models.ForeignKey(Customer, verbose_name=u"客户", on_delete=models.PROTECT)
    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)
    create_time = models.DateTimeField(verbose_name=u"创建时间", default=timezone.now)
    create_user = models.ForeignKey(User, verbose_name=u"创建人", related_name='sale_plan_ref_create_user', on_delete=models.PROTECT, blank=True, editable=False)
    department = models.ForeignKey(Department, verbose_name=u"创建部门", editable=False, on_delete=models.PROTECT)
    check_time = models.DateTimeField(verbose_name=u"审核时间", blank=True, null=True)
    check_user = models.ForeignKey(User, verbose_name=u"审核人", related_name='sale_plan_ref_check_user', on_delete=models.PROTECT, blank=True, null=True)
    total_count = models.BigIntegerField(verbose_name=u'合计数量', default=0)
    total_amount = models.BigIntegerField(verbose_name=u'合计金额', null=True, blank=True)
    class Meta:
        db_table = "sale_plan"
        verbose_name = u"销售计划管理"
        ordering = ('-id',)
        index_together = (
            'create_time', 'check_time', 'status'
        )
        unique_together = (
            'no',
        )
        default_permissions = ()
        permissions = (
            ("view_sale_plan", u"浏览"),
            ("add_sale_plan", u"添加"),
            ("check_sale_plan", u"审核"),
            ("delete_sale_plan", u"删除"),
            ("export_sale_plan", u"导出"),
            ("print_sale_plan", u"打印"),
        )

    @staticmethod
    def getById(id):
        instance = SalePlan.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 = SalePlan.objects.filter(create_time__gte=now.strftime('%Y-%m-%d')).order_by('-no')
            count = rows.count()
            if count == 0:
                self.no = 'XS%s%03d' % (now.strftime('%Y%m%d'), count + 1)
            else:
                self.no = rows[0].no[:2] + str(int(rows[0].no[2:]) + 1)
        super(SalePlan, self).save(*args, **kwargs)

    def update_total(self):
        total_count = 0
        total_amount = None
        sum_row = SalePlanDetail.objects.filter(main=self).aggregate(total_count=Sum('require_count'), total_amount=Sum('amount'))
        if sum_row:
            total_count = sum_row['total_count'] or 0
            total_amount = sum_row['total_amount']
        self.total_count = total_count
        self.total_amount = total_amount
        self.save()


class SalePlanDetail(models.Model):
    main = models.ForeignKey(SalePlan, verbose_name=u'销售计划', on_delete=models.PROTECT)
    goods = models.ForeignKey(Goods, verbose_name=u'成品', on_delete=models.PROTECT)
    quality_request = models.ForeignKey(Option, verbose_name=u"质量要求", blank=True, null=True, on_delete=models.PROTECT)
    require_time = models.DateTimeField(verbose_name=u"需求时间", blank=True, null=True)
    require_count = models.BigIntegerField(verbose_name=u'需求数量', default=0)
    price = models.BigIntegerField(verbose_name=u'单价', null=True, blank=True)
    amount = models.BigIntegerField(verbose_name=u'金额', null=True, blank=True)

    class Meta:
        db_table = "sale_plan_detail"
        verbose_name = u"出库查询"
        ordering = ('-id',)
        index_together = (
            'require_time',
        )
        default_permissions = ()
        permissions = (# 销售计划明细
            ("view_material_deliver_query", u"浏览"),
            ("export_material_deliver_query", u"导出"),
            ("print_material_deliver_query", u"打印"),
        )

    @staticmethod
    def getById(id):
        instance = SalePlanDetail.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的销售计划明细')
        return instance


class ProductionPlan(models.Model):
    no = models.CharField(max_length=20, verbose_name=u"单号", editable=False)
    name = models.CharField(max_length=100, verbose_name=u"名称", blank=True)
    status = models.PositiveSmallIntegerField(choices=settings.CHECK_STATUS_CHOICES, verbose_name=u"审核状态", default=settings.DEFAULT)
    create_user = models.ForeignKey(User, verbose_name=u"创建人", related_name='production_plan_ref_create_user', on_delete=models.PROTECT, blank=True, editable=False)
    department = models.ForeignKey(Department, verbose_name=u"所属部门", blank=True, editable=False, on_delete=models.PROTECT)
    create_time = models.DateTimeField(verbose_name=u"创建时间",  default=timezone.now)
    check_user = models.ForeignKey(User, verbose_name=u"审核人",related_name='production_plan_ref_check_user', on_delete=models.PROTECT, null=True, blank=True)
    check_time = models.DateTimeField(verbose_name=u"审核时间", null=True)
    total_count = models.BigIntegerField(u"合计数量", default=0)
    notes = models.CharField(max_length=100, verbose_name=u"备注", null=True, blank=True)

    check_user2 = models.ForeignKey(User, verbose_name=u"复核人",related_name='production_plan_ref_check_user2', on_delete=models.PROTECT, null=True, blank=True)
    check_time2 = models.DateTimeField(verbose_name=u"复核时间", null=True)

    check_user3 = models.ForeignKey(User, verbose_name=u"批准人",related_name='production_plan_ref_check_user3', on_delete=models.PROTECT, null=True, blank=True)
    check_time3 = models.DateTimeField(verbose_name=u"批准时间", null=True)

    class Meta:
        db_table = "production_plan"
        verbose_name = u"生产计划管理"
        ordering = ('-id',)
        index_together = (
            'name',
            'create_time','status','check_time'
        )
        unique_together = (
            'no',
        )
        default_permissions = ()
        permissions = (
            ("view_production_plan", u"浏览"),
            ("add_production_plan", u"添加"),
            ("check_production_plan", u"审核"),
            ("delete_production_plan", u"删除"),
            ("export_production_plan", u"导出"),
            ("print_production_plan", u"打印"),
            ("check2_production_plan", u"复核"),
            ("check3_production_plan", u"批准"),
        )

    def updateTotalCount(self):
        sum_count = 0
        sum_rows = ProductionPlanDetail.objects.filter(production=self).aggregate(sum_count=Sum('count'))
        if sum_rows:
            sum_count = sum_rows['sum_count'] or 0
        self.total_count = sum_count
        self.save()

    @staticmethod
    def getById(id):
        instance = ProductionPlan.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 = ProductionPlan.objects.filter(create_time__gte=now.strftime('%Y-%m-%d')).order_by('-no')
            count = rows.count()
            if count == 0:
                self.no = 'SC%s%03d' % (now.strftime('%Y%m%d'), count + 1)
            else:
                self.no = rows[0].no[:2] + str(int(rows[0].no[2:]) + 1)
        super(ProductionPlan, self).save(*args, **kwargs)


class ProductionPlanDetail(models.Model):
    production = models.ForeignKey(ProductionPlan, verbose_name=u"生产计划", on_delete=models.PROTECT)
    product = models.ForeignKey(Goods, verbose_name=u"产品", on_delete=models.PROTECT)
    quality_request = models.ForeignKey(Option, verbose_name=u"质量要求", on_delete=models.PROTECT, null=True)
    count = models.BigIntegerField(u"数量", default=0)
    product_user = models.ForeignKey(User, verbose_name=u"负责人", on_delete=models.PROTECT, null=True)
    p_department = models.ForeignKey(Department, verbose_name=u"生产车间", related_name='production_detail_ref_p_department', on_delete=models.PROTECT, blank=True, null=True)
    department = models.ForeignKey(Department, verbose_name=u"负责人部门", related_name='production_detail_ref_department', on_delete=models.PROTECT, null=True, blank=True)
    product_time = models.DateTimeField(verbose_name=u"生产时间", null=True)
    notes = models.CharField(max_length=100, verbose_name=u"备注", null=True, blank=True)

    class Meta:
        db_table = "production_plan_detail"
        verbose_name = u"出库查询"
        default_permissions = ()
        permissions = (# 生产计划明细
            ("view_consumable_deliver_query", u"浏览"),
            ("export_consumable_deliver_query", u"导出"),
            ("print_consumable_deliver_query", u"打印"),
        )

    @staticmethod
    def getById(id):
        instance = ProductionPlanDetail.objects.filter(pk=id)
        if not instance:
            raise CustomError(u'未找到相应的生产计划明细')
        return instance