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 CoderSendSerializer(serializers.Serializer):
    tdata_list = serializers.ListField(child=serializers.JSONField(), label='模板数据列表', allow_empty=False)
    coder_ip = serializers.IPAddressField(label='喷码IP')
    coder_port = serializers.IntegerField(label='喷码端口', required=False, allow_null=True)
    coder_field = serializers.CharField(label='默认用户区名', required=False, allow_null=True)
    coder_jobname = serializers.CharField(label='信息模板名', required=False, allow_null=True)


class HanslaserSendSerializer(serializers.Serializer):
    tdata_list = serializers.ListField(child=serializers.JSONField(), label='模板数据列表', allow_empty=False)
    coder_ip = serializers.IPAddressField(label='打标机IP')
    coder_port = serializers.IntegerField(label='打标机端口')
    coder_jobname = serializers.CharField(label='打标文件名', required=False, allow_null=True)


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__'