from apps.utils.serializers import CustomModelSerializer
from apps.qm.serializers import FtestProcessSerializer
from apps.inm.models import MIOItemw, MIOItem, MIO
from django.db import transaction
from rest_framework.exceptions import ParseError
from apps.wpmw.models import Wpr
from apps.mtm.models import Material
from rest_framework import serializers

class MIOItemwCreateUpdateSerializer(CustomModelSerializer):
    ftest = FtestProcessSerializer(required=False)
    wpr_number_out = serializers.CharField(source="wpr.number_out", read_only=True)

    class Meta:
        model = MIOItemw
        fields = ["id", "number", "wpr", "note", "mioitem", "ftest", "wpr_number_out"]

    def validate(self, attrs):
        mioitem: MIOItem = attrs["mioitem"]
        mio: MIO = mioitem.mio
        ftest_data = attrs.get("ftest", None)
        if ftest_data and mio.type == MIO.MIO_TYPE_PUR_IN:
            ftest_data["type"] = "purin"
        else:
            raise ParseError('采购入库才可进行检验')
        if mioitem.mio.submit_time is not None:
            raise ParseError('出入库已提交不可编辑')
        wpr: Wpr = attrs.get("wpr", None)
        material:Material = mioitem.material
        if material.tracking != Material.MA_TRACKING_SINGLE:
            raise ParseError('非单件追踪不可使用')
        if mio.type in [MIO.MIO_TYPE_DO_IN, MIO.MIO_TYPE_DO_OUT, MIO.MIO_TYPE_SALE_OUT] and not wpr:
            raise ParseError('请选择相应产品')
        return attrs

    def save_ftest(self, mioitemw, ftest_data):
        ftest = mioitemw.ftest
        if not ftest:
            ftest_sr = FtestProcessSerializer(data=ftest_data)
            ftest = ftest_sr.create(ftest_data)
            mioitemw.ftest = ftest
            mioitemw.save()
        else:
            ftest_sr = FtestProcessSerializer()
            ftest_sr.update(instance=ftest, validated_data=ftest_data)
        return mioitemw

    def create(self, validated_data):
        wpr: Wpr = validated_data.get("wpr", None)
        if wpr:
            mioitem: MIOItem = validated_data["mioitem"]
            if MIOItemw.objects.filter(mioitem=mioitem, wpr=wpr).exists():
                raise ParseError('该产品已选入')
        ftest_data = validated_data.pop("ftest", None)
        mioitemw = super().create(validated_data)
        if ftest_data:
            mioitemw = self.save_ftest(mioitemw, ftest_data)
        return mioitemw

    def update(self, instance, validated_data):
        validated_data.pop("mioitem")
        ftest_data = validated_data.pop("ftest", None)
        mioitemw = super().update(instance, validated_data)
        if ftest_data:
            mioitemw = self.save_ftest(mioitemw, ftest_data)
        return mioitemw