from apps.system.models import CommonAModel, Organization
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db.models.base import Model
import django.utils.timezone as timezone
from django.db.models.query import QuerySet

from utils.model import SoftModel, BaseModel
from apps.mtm.models import Material, Process, SubProduction
from apps.sam.models import Order

class ProductionPlan(CommonAModel):
    """
    生产计划
    """
    number = models.CharField('编号', max_length=50, unique=True)
    order = models.ForeignKey(Order, verbose_name='关联订单', null=True, blank=True, on_delete=models.SET_NULL)
    product = models.ForeignKey(Material, verbose_name='生产产品', on_delete=models.CASCADE)
    count = models.IntegerField('生产数量', default=1)
    start_date = models.DateField('计划开工日期')
    end_date = models.DateField('计划完工日期')
    is_planed = models.BooleanField('是否已排产', default=False)
    class Meta:
        verbose_name = '生产计划'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.number

class SubProductionPlan(CommonAModel):
    """
    子生产计划
    """
    state_choices=(
        (0, '制定中'),
        (1, '已下达'),
        (2, '已接收'),
        (3, '生产中'),
        (4, '已完成')
    )
    production_plan = models.ForeignKey(ProductionPlan, verbose_name='关联主生产计划', on_delete=models.CASCADE)
    subproduction = models.ForeignKey(SubProduction, verbose_name='关联生产分解', on_delete=models.CASCADE)
    start_date = models.DateField('计划开工日期')
    end_date = models.DateField('计划完工日期')
    workshop = models.ForeignKey(Organization, verbose_name='生产车间', on_delete=models.CASCADE)
    process = models.ForeignKey(Process, verbose_name='关联大工序', on_delete=models.CASCADE)
    steps = models.JSONField('工艺步骤', default=list)
    state = models.IntegerField('状态', default=0)
    start_date_real = models.DateField('实际开工日期', null=True, blank=True)
    end_date_real = models.DateField('实际完工日期', null=True, blank=True)
    class Meta:
        verbose_name = '子生产计划'
        verbose_name_plural = verbose_name

class SubProductionProgress(BaseModel):
    """
    子计划生产进度统计表
    """
    type_choices=(
        (1, '输入物料'),
        (2, '输出物料')
    )
    subproduction_plan = models.ForeignKey(SubProductionPlan, verbose_name='关联子生产计划', on_delete=models.CASCADE, related_name='progress_subplan')
    material = models.ForeignKey(Material, verbose_name='关联物料', on_delete=models.CASCADE)
    type = models.IntegerField('物料应用类型', default=1)
    count = models.IntegerField('应出入数')
    count_real = models.IntegerField('实际出入数', default=0)
