from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from .models import TableAllDevCmdDefine, TableDevCmdNamePoll, TableSoftLimitAngle, TableXproAllDevinfo


class TableAllDevCmdDefineSerializer(ModelSerializer):
    # 新增或修改字段时，需要用到 protocol_name 来获取当前协议的当前版本
    protocol_name = serializers.CharField(max_length=50, required=True, write_only=True)

    class Meta:
        model = TableAllDevCmdDefine
        fields = ['id', 'cmd_name', 'cmd_type', 'fieldindex', 'fieldname', 'fieldsize', 'value', 'minvalue', 'maxvalue',
                  'datatype', 'operation_in', 'operation_in_num', 'operation_out', 'operation_out_num', 'operabo_in',
                  'operabo_out', 'lua_script_in', 'lua_script_out', 'protocol_name']

    def create(self, validated_data):
        protocol_name = validated_data.pop('protocol_name')
        instance = super().create(validated_data)
        # 执行额外的逻辑或将protocol_name字段与实例关联
        instance.protocol_name = protocol_name
        instance.save()
        return instance

class TableDevCmdNamePollSerializer(ModelSerializer):
    class Meta:
        model = TableDevCmdNamePoll
        fields = '__all__'


class TableSoftLimitAngleSerializer(ModelSerializer):

    def validate_remarks(self, value):
        """
        当传过来的值为 none 时，则在数据库里存一个空值
        
        :param value: 通过基本校验之后的值
        """
        if value == "none":
            return "" 
        return value

    class Meta:
        model = TableSoftLimitAngle
        fields = '__all__'


class TableXproAllDevinfoSerializer(ModelSerializer):

    def allow_none(self, value):
        """
        当传过来的值为 none 时，则在数据库里存一个空值
        
        :param value: 通过基本校验之后的值
        """
        if value == "none":
            return "" 
        return value

    def validate(self, attrs: dict):
        """
        校验字段，在进行基础校验之后，如果字段名称为下面的字段，
        且当传过来的值为 none 时，存一个空值
        
        :param attrs: 通过基本校验之后的值
        """
        for field_name, value in attrs.items():
            if field_name in (['cmd_excel_path', 'udp_ip_src', 'udp_ip_dst',
                               'udpmc_ip', 'udpmc_ip_tx', 'udpmc_ip_rx', 'remarks']):
                attrs[field_name] = self.allow_none(value)
        return attrs

    class Meta:
        model = TableXproAllDevinfo
        fields = '__all__'
