from django.db import models
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)


    @classmethod
    def change_or_new(cls, number, material, can_new=False, mb=None, wm=None, state=10):
        ins = cls.objects.filter(number=number).first()
        if ins:
            ins.material = material
        elif can_new:
            ins = cls(number=number, material=material)
        else:
            raise ParseError("物料不存在")
        ins.state = state
        ins.mb = mb
        ins.wm = wm
        ins.save()

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


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)