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
from .models import Standard, TestItem, TestRecord, TestRecordItem

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

class TestRecordItemSerializer(serializers.ModelSerializer):
    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):
    class Meta:
        model = TestRecord
        fields = '__all__'


class TestRecordDetailSerializer(serializers.ModelSerializer):
    form_ = RecordFormSimpleSerializer(source='form', read_only=True)
    record_data_ = TestRecordItemSerializer(source='item_test_record', read_only=True, many=True)
    class Meta:
        model = TestRecord
        fields = '__all__'
    
    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.select_related('form','fifo_item')
        return queryset

    # def get_record_data_(self, obj):
    #     record_data = obj.record_data
    #     all_fields = RecordFormField.objects.filter(form=obj.form, is_deletd=False).order_by('sort')
    #     all_fields_l = RecordFormFieldSerializer(instance=all_fields, many=True).data
    #     for i in all_fields_l:
    #         key = i['field_key']
    #         i['field_value'] = record_data.get(key, None)
    #     return all_fields_l