from django.db import models
from apps.utils.models import CommonADModel, CommonBDModel, BaseModel
from apps.mtm.models import Material, Mgroup, RoutePack, Route
from datetime import datetime
from django.db.models import Max

# Create your models here.

TASK_TYPE = (
    ('mass', '量产'),
    ('pilot', '中试')
)
SCHEDULE_TYPE = (
    ('to_day', '排产到天'),
    ('to_mgroup', '排产到工段')
)


class Utask(CommonBDModel):
    """
    TN:生产大任务
    """
    UTASK_CREATED = 10
    UTASK_DECOMPOSE = 14
    UTASK_ASSGINED = 20
    UTASK_WORKING = 30
    UTASK_STOP = 34
    UTASK_SUBMIT = 40
    UTASK_STATES = (
        (UTASK_CREATED, '创建中'),
        (UTASK_DECOMPOSE, '已分解'),
        (UTASK_ASSGINED, '已下达'),
        (UTASK_WORKING, '生产中'),
        (UTASK_STOP, '已停止'),
        (UTASK_SUBMIT, '已提交')
    )
    type = models.CharField('任务类型', max_length=10,
                            help_text=str(TASK_TYPE), default='mass')
    routepack = models.ForeignKey(RoutePack, verbose_name='关联工艺包', on_delete=models.SET_NULL, null=True, blank=True)
    priority = models.PositiveIntegerField('优先级', default=20, help_text="10:低;20:中;30:高")
    state = models.PositiveIntegerField(
        '状态', choices=UTASK_STATES, default=UTASK_CREATED, help_text=str(UTASK_STATES))
    number = models.CharField('编号', max_length=50, unique=True)
    material = models.ForeignKey(
        Material, verbose_name='产品', on_delete=models.CASCADE)
    mgroup = models.ForeignKey(
        Mgroup, verbose_name='工段', on_delete=models.CASCADE, null=True, blank=True)
    material_in = models.ForeignKey(
        Material, verbose_name='领用物', on_delete=models.CASCADE, related_name='utask_material_in', null=True, blank=True)
    count = models.PositiveIntegerField('任务数', default=1)
    count_real = models.PositiveIntegerField('实际生产数', default=0)
    count_day = models.PositiveIntegerField('日均任务数', default=0)
    count_ok = models.PositiveIntegerField('合格数', default=0)
    count_notok = models.PositiveIntegerField('不合格数', default=0)
    start_date = models.DateField('计划开工日期')
    end_date = models.DateField('计划完工日期')

    @classmethod
    def get_a_number(cls):
        today_str = datetime.now().strftime('%Y%m%d')
        prefix = "RW"
        last_record = Utask.objects.filter(number__startswith=f"{prefix}-{today_str}") \
                                       .aggregate(Max('number'))['number__max']
        if last_record:
            last_number = int(last_record.split('-')[-1]) + 1
        else:
            last_number = 1
        return f"{prefix}-{today_str}-{last_number:02d}"


class Mtask(CommonADModel):
    """
    TN:生产任务
    """
    MTASK_CREATED = 10
    MTASK_ASSGINED = 20
    MTASK_STOP = 34
    MTASK_SUBMIT = 40
    MTASK_STATES = (
        (MTASK_CREATED, '创建中'),
        (MTASK_ASSGINED, '已下达'),
        (MTASK_STOP, '已停止'),
        (MTASK_SUBMIT, '已提交')
    )
    route = models.ForeignKey(Route, verbose_name='关联工艺', on_delete=models.SET_NULL, null=True, blank=True)
    type = models.CharField('任务类型', max_length=10,
                            help_text=str(TASK_TYPE), default='mass')
    state = models.PositiveIntegerField(
        '状态', choices=MTASK_STATES, default=MTASK_CREATED, help_text=str(MTASK_STATES))
    number = models.CharField('编号', max_length=50, unique=True)
    mgroup = models.ForeignKey(
        Mgroup, verbose_name='工段', on_delete=models.CASCADE)
    material_in = models.ForeignKey(
        Material, verbose_name='领用物', on_delete=models.CASCADE, related_name='mtask_material_in', null=True, blank=True)
    material_out = models.ForeignKey(
        Material, verbose_name='产物', on_delete=models.CASCADE, related_name='mtask_material_out')
    is_count_utask = models.BooleanField('是否主任务统计', default=False)
    count = models.DecimalField('任务数', default=1, max_digits=11, decimal_places=1)
    count_real = models.DecimalField('实际生产数', default=0, max_digits=11, decimal_places=1)
    count_ok = models.DecimalField('合格数', default=0, max_digits=11, decimal_places=1)
    count_notok = models.DecimalField('不合格数', default=0, max_digits=11, decimal_places=1)
    start_date = models.DateField('计划开工日期')
    end_date = models.DateField('计划完工日期')
    utask = models.ForeignKey(
        Utask, verbose_name='关联大任务', on_delete=models.CASCADE, related_name='mtask_utask', null=True, blank=True)
    hour_work = models.FloatField('工时', null=True, blank=True)
    peifen_kg = models.FloatField('配粉料数', default=0)

    submit_time = models.DateTimeField('提交时间', null=True, blank=True)
    submit_user = models.ForeignKey(
        'system.user', verbose_name='提交人', on_delete=models.CASCADE, null=True, blank=True, related_name='mtask_submit_user')

    @property
    def related(self):
        """
        TN:当天已下达的所有的兄弟小任务
        """
        if self.utask:
            return Mtask.objects.filter(
                utask=self.utask, mgroup__belong_dept=self.mgroup.belong_dept, start_date=self.start_date, end_date=self.start_date, state=self.MTASK_ASSGINED).order_by(
                    'utask', 'mgroup__process__sort', 'create_time'
            )
        return Mtask.objects.none()

    @property
    def mlogs(self):
        from apps.wpm.models import Mlog
        return Mlog.objects.filter(mtask=self)

    @property
    def mtaskb(self):
        return Mtaskb.objects.filter(mtask=self)


class Mtaskb(BaseModel):
    """TN:生产任务关联表"""
    mtask = models.ForeignKey(Mtask, verbose_name='关联任务', on_delete=models.CASCADE, related_name='b_mtask')
    handle_user = models.ForeignKey(
        'system.user', verbose_name='操作人', on_delete=models.CASCADE, related_name='mtaskb_handle_user')
    count = models.DecimalField('任务数', default=0, max_digits=11, decimal_places=1)