from django.db import models

from apps.qm.models import FtestDefect, FtestItem
from apps.utils.models import BaseModel
from apps.mtm.models import Material
from rest_framework.exceptions import ParseError

# Create your models here.
class Wpr(BaseModel):
    """
    动态半成品表
    """

    number = models.CharField("编号", max_length=50, unique=True, null=True, blank=True)
    state = models.PositiveSmallIntegerField('状态', default=10, choices=((10, '合格'), (20, '不合格'), (30, '返修'), (40, '检验'), (50, '报废')))
    material = models.ForeignKey(Material, verbose_name="当前物料形态", on_delete=models.CASCADE)
    defects = models.ManyToManyField("qm.defect", through="wpmw.wprdefect", verbose_name="缺陷项")


    mb = models.ForeignKey("inm.materialbatch", verbose_name="仓库物料", on_delete=models.CASCADE, null=True, blank=True)
    wm = models.ForeignKey("wpm.wmaterial", verbose_name="车间物料", on_delete=models.CASCADE, null=True, blank=True)
    oinfo = models.JSONField(verbose_name="其他信息", default=dict, blank=True)

    @classmethod
    def change_or_new(cls, wpr=None, number=None, mb=None, wm=None, old_mb=None, old_wm=None, ftest=None):
        if wpr is None and number is None:
            raise ParseError("id和number不能同时为空")
        if mb and wm:
            raise ParseError("所属仓库批次和车间批次不可同时存在")

        if wpr:
            ins = wpr
        elif number:
            try:
                ins = cls.objects.get(number=number)
                if ins.wm or ins.wm:
                    raise ParseError("该物料编号已存在不可使用")
            except cls.DoesNotExist:
                ins = cls(number=number)

        if old_mb and ins.mb != old_mb:
            raise ParseError(f"请检查-{ins.number}-所属仓库批次")
        if old_wm and ins.wm != old_wm:
            raise ParseError(f"请检查-{ins.number}-所属车间批次")

        if number:
            ins.number = number

        ins.mb = mb
        if mb:
            ins.material = mb.material

        ins.wm = wm
        if wm:
            ins.material = wm.material
            ins.state = wm.state
            WprDefect.objects.filter(wpr=ins).delete()
            if wm.defect:
                WprDefect.objects.create(wpr=ins, defect=wm.defect, is_main=True)
        ins.save()
        if ftest: 
            # 通过检验变更其缺陷项
            WprDefect.objects.filter(wpr=ins).delete()
            for ftestdefect in FtestDefect.objects.filter(ftest=ftest, has=True):
                WprDefect.objects.create(wpr=ins, defect=ftestdefect.defect, is_main=ftestdefect.is_main)
            # 携带某些检测信息
            oinfo = {}
            for ftestitem in FtestItem.objects.filter(ftest=ftest, addto_wpr=True):
                if ftestitem.test_val_json:
                    oinfo[ftestitem.id] = {"name": ftestitem.testitem.name, "val": ftestitem.test_val_json}
            ins.oinfo = ins.oinfo.update(oinfo) if ins.oinfo else oinfo
            ins.save()
        return ins

    @classmethod
    def clear(cls, number_list):
        cls.objects.filter(number__in=number_list).update(mb=None, wm=None)

    @classmethod
    def get_qs_by_mb(cls, mb):
        return cls.objects.filter(mb=mb, wm=None)

    @classmethod
    def get_qs_by_wm(cls, wm):
        return cls.objects.filter(wm=wm, mb=None)

    @property
    def wprdefect(self):
        return WprDefect.objects.filter(wpr=self)

class WprDefect(BaseModel):
    wpr = models.ForeignKey(Wpr, verbose_name="关联产物", on_delete=models.CASCADE)
    defect = models.ForeignKey("qm.defect", verbose_name="关联缺陷项", on_delete=models.CASCADE)
    is_main = models.BooleanField("是否主要缺陷", default=False)