from rest_framework import serializers
from apps.mtm.models import RecordForm, RecordFormField
from apps.mtm.serializers import RecordFormFieldSerializer, RecordFormSimpleSerializer
from apps.system.serializers import FileSimpleSerializer, UserSimpleSerializer
from .models import Standard, TestItem, TestRecord, TestRecordItem
from django.db import transaction

class StandardCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Standard
        fields = ['name', 'file', 'enabled', 'number']

class StandardSerializer(serializers.ModelSerializer):
    file_ = FileSimpleSerializer(source='file', read_only=True)
    class Meta:
        model = Standard
        fields = '__all__'

class StandardSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Standard
        fields = ['id', 'name', 'number']

class TestItemCreateUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = TestItem
        fields = ['name', 'standard', 'term_number']

class TestItemSerializer(serializers.ModelSerializer):
    standard_ = StandardSimpleSerializer(source='standard', read_only=True)
    class Meta:
        model = TestItem
        fields = '__all__'

class AnalysisItemSerializer(serializers.ModelSerializer):
    pass


class TestRecordItemCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = TestRecordItem
        fields = ['form_field', 'field_value', 'is_testok']

class TestRecordItemUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = TestRecordItem
        fields = ['id', 'field_value', 'is_testok', 'is_hidden']


class TestRecordItemSerializer(serializers.ModelSerializer):
    field_key = serializers.CharField(source='form_field.field_key', read_only=True)
    field_name = serializers.CharField(source='form_field.field_name', read_only=True)
    field_type = serializers.CharField(source='form_field.field_type', read_only=True)
    need_judge = serializers.BooleanField(source='form_field.need_judge', read_only=True)
    field_choice = serializers.JSONField(source='form_field.field_choice', read_only=True)
    rule_expression = serializers.JSONField(source='form_field.rule_expression', read_only=True)
    display_expression = serializers.JSONField(source='form_field.display_expression', read_only=True)
    is_hidden = serializers.BooleanField(source='form_field.is_hidden', read_only=True)
    parent = serializers.PrimaryKeyRelatedField(source='form_field.parent', read_only=True)
    help_text = serializers.CharField(source='form_field.help_text', read_only=True)
    sort = serializers.IntegerField(source='form_field.sort', read_only=True)
    class Meta:
        model = TestRecordItem
        fields = '__all__'
        
class TestRecordCreateSerializer(serializers.ModelSerializer):
    record_data = TestRecordItemCreateSerializer(many=True)
    class Meta:
        model = TestRecord
        fields = ['form', 'record_data', 'is_testok', 'fifo_item']

class TestRecordListSerializer(serializers.ModelSerializer):
    form_ = RecordFormSimpleSerializer(source='form', read_only=True)
    create_by_ = UserSimpleSerializer(source='create_by', read_only=True)
    class Meta:
        model = TestRecord
        fields = '__all__'

class TestRecordDetailBaseSerializer(serializers.ModelSerializer):
    form_ = RecordFormSimpleSerializer(source='form', read_only=True)
    record_data = serializers.SerializerMethodField()
    create_by_ = UserSimpleSerializer(source='create_by', read_only=True)
    class Meta:
        model = TestRecord
        fields = '__all__'
    
    def get_record_data(self, obj):
        return TestRecordItemSerializer(instance=obj.item_test_record.order_by('form_field__sort'), many=True).data

class TestRecordDetailSerializer(serializers.ModelSerializer):
    form_ = RecordFormSimpleSerializer(source='form', read_only=True)
    # record_data = TestRecordItemSerializer(source='item_test_record', read_only=True, many=True)
    record_data = serializers.SerializerMethodField()
    origin_test_ = TestRecordDetailBaseSerializer(source='origin_test', read_only=True)
    class Meta:
        model = TestRecord
        fields = '__all__'

    def get_record_data(self, obj):
        return TestRecordItemSerializer(instance=obj.item_test_record.order_by('form_field__sort'), many=True).data

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        if instance.origin_test and instance.type == TestRecord.TEST_PROCESS_RE:
            origin_test = ret['origin_test_']
            o_dict = {}
            for i in origin_test['record_data']:
                o_dict[i['field_key']] = i['field_value']
            for i in ret['record_data']:
                i['origin_value'] = o_dict[i['field_key']] if i['field_key'] in o_dict else None
        return super().to_representation(instance)

class TestRecordItemUpdatexSerializer(serializers.Serializer):
    id = serializers.PrimaryKeyRelatedField(queryset=TestRecordItem.objects.all())
    field_value = serializers.JSONField(allow_null=True, required=False)
    is_testok = serializers.BooleanField(allow_null=True, required=False)
    is_hidden = serializers.BooleanField(default=False)

class TestRecordUpdateSerializer(serializers.ModelSerializer):
    record_data = TestRecordItemUpdatexSerializer(many=True, write_only=True)
    class Meta:
        model = TestRecord
        fields = ['is_testok', 'record_data']

    def update(self, instance, validated_data):
        record_data = validated_data.pop('record_data')
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        for i in record_data:
            tri = i['id']
            tri.field_value = i['field_value']
            tri.is_testok = i['is_testok']
            tri.is_hidden = i['is_hidden']
            tri.save()
        return instance
