from rest_framework import serializers
from .models import LableMat, LabelTemplate
from apps.qm.models import NotOkOption
from apps.wpm.models import WmStateOption
from apps.utils.serializers import CustomModelSerializer


class TidSerializer(serializers.Serializer):
    tid = serializers.CharField(label='表ID')
    label_template = serializers.CharField(label='标签模板ID', allow_null=True, required=False)
    label_template_name = serializers.CharField(label='标签模板名称', allow_null=True, required=False)
    extra_data = serializers.JSONField(label='额外数据', allow_null=True, required=False)

class Tid2Serializer(serializers.Serializer):
    label_template = serializers.CharField(label='标签模板ID', allow_null=True, required=False)
    label_template_name = serializers.CharField(label='标签模板名称', allow_null=True, required=False)
    data = serializers.JSONField(label='数据', allow_null=True, required=False)


class LabelMatSerializer(serializers.ModelSerializer):
    material_name = serializers.StringRelatedField(source='material', read_only=True)
    material_origin_name = serializers.StringRelatedField(source='material_origin', read_only=True)
    supplier_name = serializers.CharField(source='supplier.name', read_only=True)
    defect_name = serializers.CharField(source="defect.name", read_only=True)
    notok_sign_name = serializers.SerializerMethodField()
    state_name = serializers.SerializerMethodField()
    class Meta:
        model = LableMat
        fields = '__all__'
    
    def get_notok_sign_name(self, obj):
        return getattr(NotOkOption, obj.notok_sign, NotOkOption.qt).label if obj.notok_sign else None
    
    def get_state_name(self, obj):
        return getattr(WmStateOption, str(obj.state), WmStateOption.OK).label if obj.state else None
    

class LabelTemplateSerializer(CustomModelSerializer):
    class Meta:
        model = LabelTemplate
        fields = '__all__'