from apps.wpmw.models import Wpr, WprDefect
from apps.utils.serializers import CustomModelSerializer
from rest_framework import serializers
from apps.inm.serializers import MaterialBatchSerializer
from apps.wpm.serializers import WMaterialSerializer
from apps.qm.models import FtestItem

class WprDefectSerializer(CustomModelSerializer):
    defect_name = serializers.CharField(source="defect.name", read_only=True)

    class Meta:
        model = WprDefect
        fields = "__all__"


class WprSerializer(CustomModelSerializer):
    wm_batch = serializers.CharField(source="wm.batch", read_only=True)
    mb_batch = serializers.CharField(source="mb.batch", read_only=True)
    material_name = serializers.StringRelatedField(
        source='material', read_only=True) 
    # material_start_name = serializers.StringRelatedField(source='material_start', read_only=True)
    wm_material_ofrom_name = serializers.StringRelatedField(source="wm.material_ofrom", read_only=True)
    wprdefect = WprDefectSerializer(many=True, read_only=True)  

    class Meta:
        model = Wpr
        fields = '__all__'
    
    def to_representation(self, instance):
        ret = super().to_representation(instance)
        material_name = ret.get("material_name", "")
        if material_name:
            ret["process_name"] = material_name.split("|")[-1]
        return ret

class WprDetailSerializer(WprSerializer):
    mb_ = MaterialBatchSerializer(source='mb', read_only=True)
    wm_ = WMaterialSerializer(source='wm', read_only=True)


class WprNewSerializer(serializers.Serializer):
    year = serializers.IntegerField()
    month = serializers.IntegerField()
    material_start = serializers.CharField(label="物料ID")


class WproutSerializer(serializers.Serializer):
    id = serializers.CharField(label="wprId")
    number_out = serializers.CharField(label="对外编号", allow_null=True)


class WproutListSerializer(serializers.Serializer):
    items = WproutSerializer(many=True)


class WprChangeNumberSerializer(serializers.Serializer):
    old_number = serializers.CharField(label="原编号")
    new_number = serializers.CharField(label="新编号")


class WprPreInfoSerializer(serializers.Serializer):
    tooling = serializers.CharField(label="工装ID")