from apps.em.serializers import EquipmentSimpleSerializer
from rest_framework import serializers
from rest_framework.exceptions import ParseError, ValidationError
from .models import Material, Process, RecordForm, RecordFormField, Step, SubprodctionMaterial, TechDoc, UsedStep, SubProduction
from apps.system.serializers import FileSimpleSerializer, OrganizationSimpleSerializer


class MaterialSerializer(serializers.ModelSerializer):
    class Meta:
        model = Material
        fields = '__all__'

class MaterialDetailSerializer(serializers.ModelSerializer):
    processes_ = serializers.SerializerMethodField()
    class Meta:
        model = Material
        fields = '__all__'
    
    def get_processes_(self, obj):
        # steps = UsedStep.objects.filter(subproduction__product=obj).values_list('step', flat=True)
        # objs = Process.objects.filter(step_process__id__in=steps).distinct().order_by('number')
        objs = Process.objects.filter(subproduction_process__product=obj, subproduction_process__is_deleted=False, is_deleted=False).distinct().order_by('number')
        return ProcessSimpleSerializer(instance=objs, many=True).data


class MaterialSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Material
        fields = ['id', 'name', 'number', 'unit','specification', 'type']

class ProcessSerializer(serializers.ModelSerializer):
    instruction_ = FileSimpleSerializer(source='instruction', read_only=True)
    workshop_ = OrganizationSimpleSerializer(source='workshop', read_only=True)
    class Meta:
        model = Process
        fields = '__all__'

class ProcessSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Process
        fields = ['id', 'name', 'number', 'type']

class StepSerializer(serializers.ModelSerializer):
    class Meta:
        model = Step
        fields = '__all__'

class StepSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Step
        fields = ['id', 'name', 'sort']

class StepDetailSerializer(serializers.ModelSerializer):
    equipments_ = EquipmentSimpleSerializer(source='equipments', many=True, required=False)
    class Meta:
        model = Step
        fields = '__all__'
    
    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.prefetch_related('equipments')
        return queryset

class SubProductionSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubProduction
        fields = ['id', 'name']

class SubProductionSerializer(serializers.ModelSerializer):
    process_ = ProcessSimpleSerializer(source='process', read_only=True)
    class Meta:
        model = SubProduction
        fields = '__all__'

class OtherMaterialSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubprodctionMaterial
        fields = ['sort', 'material', 'subproduction']
    
    def create(self, validated_data):
        if SubprodctionMaterial.objects.filter(material=validated_data['material'], subproduction=validated_data['subproduction'], is_deleted=False, type=3).exists():
            raise ValidationError('该物料已存在')
        validated_data['type']=3
        return super().create(validated_data)

class SubprodctionMaterialListSerializer(serializers.ModelSerializer):
    material_ = MaterialSimpleSerializer(source='material', read_only=True)
    class Meta:
        model = SubprodctionMaterial
        fields = '__all__'

class InputMaterialSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubprodctionMaterial
        fields = ['count', 'sort', 'material', 'subproduction']
    
    def create(self, validated_data):
        if SubprodctionMaterial.objects.filter(material=validated_data['material'], subproduction=validated_data['subproduction'], is_deleted=False, type=SubprodctionMaterial.SUB_MA_TYPE_IN).exists():
            raise ValidationError('该物料已存在')
        validated_data['type']=SubprodctionMaterial.SUB_MA_TYPE_IN
        return super().create(validated_data)

class InputMaterialUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubprodctionMaterial
        fields = ['count', 'sort']

class OutputMaterialSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubprodctionMaterial
        fields = ['count', 'sort', 'material', 'subproduction', 'is_main']
    
    def create(self, validated_data):
        if SubprodctionMaterial.objects.filter(subproduction=validated_data['subproduction'], is_deleted=False, is_main=True, type=SubprodctionMaterial.SUB_MA_TYPE_OUT).exists():
            raise ValidationError('主产出只能有1个')
        if SubprodctionMaterial.objects.filter(material=validated_data['material'], subproduction=validated_data['subproduction'], is_deleted=False, type=SubprodctionMaterial.SUB_MA_TYPE_OUT).exists():
            raise ValidationError('该物料已存在')
        validated_data['type']=SubprodctionMaterial.SUB_MA_TYPE_OUT
        return super().create(validated_data)

class OutputMaterialUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = SubprodctionMaterial
        fields = ['count', 'sort', 'is_main']



class UsedStepCreateSerializer(serializers.ModelSerializer):
    """
    产品生产子工序创建
    """
    class Meta:
        model = UsedStep
        fields =  ['step', 'subproduction', 'remark']

class UsedStepUpdateSerializer(serializers.ModelSerializer):
    """
    产品生产子工序编辑
    """
    class Meta:
        model = UsedStep
        fields =  ['remark']

class UsedStepListSerializer(serializers.ModelSerializer):
    """
    产品生产子工序序列化
    """
    step_ = StepSimpleSerializer(source='step', read_only=True)
    class Meta:
        model = UsedStep
        fields = '__all__'
    
    @staticmethod
    def setup_eager_loading(queryset):
        """ Perform necessary eager loading of data. """
        queryset = queryset.select_related('step')
        return queryset

class RecordFormSimpleSerializer(serializers.ModelSerializer):

    class Meta:
        model = RecordForm
        fields = ['id', 'name', 'number', 'enabled']
class RecordFormSerializer(serializers.ModelSerializer):
    step_ = StepSimpleSerializer(source='step', read_only=True)
    material_ = MaterialSimpleSerializer(source='material', read_only=True)
    """
    记录表格序列化
    """
    class Meta:
        model = RecordForm
        fields = '__all__'

    @staticmethod
    def setup_eager_loading(queryset):
        """ Perform necessary eager loading of data. """
        queryset = queryset.select_related('step', 'material')
        return queryset

class RecordFormCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = RecordForm
        fields = ['name', 'type', 'step', 'material', 'number', 'enabled']

class RecordFormUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = RecordForm
        fields = ['name', 'type', 'number', 'enabled']

class RecordFormFieldSerializer(serializers.ModelSerializer):
    class Meta:
        model = RecordFormField
        fields = '__all__'

class RecordFormDetailSerializer(serializers.ModelSerializer):
    step_ = StepSimpleSerializer(source='step', read_only=True)
    material_ = MaterialSimpleSerializer(source='material', read_only=True)
    form_fields = serializers.SerializerMethodField()

    class Meta:
        model = RecordForm
        fields = '__all__'

    @staticmethod
    def setup_eager_loading(queryset):
        """ Perform necessary eager loading of data. """
        queryset = queryset.select_related('step', 'material')
        return queryset
    
    def get_form_fields(self, obj):
        serializer = RecordFormFieldSerializer(instance=RecordFormField.objects.filter(form=obj, is_deleted=False), many=True)
        data = serializer.data
        if obj.type == RecordForm.RF_TYPE_TEST:
            for i in data:
                if i['need_judge']:
                    i['is_testok'] = False
                    i['is_teskok_robot'] = False
        return data


class RecordFormFieldCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = RecordFormField
        fields = '__all__'
    
    def validate(self, data):
        if RecordFormField.objects.filter(field_key=data['field_key'], form=data['form'], is_deleted=False).exists():
            raise ValidationError('字段key已存在!')
        return data

class RecordFormFieldUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = RecordFormField
        exclude = ['field_key']

class RecordFormFieldSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = RecordFormField
        fields = '__all__'

class TechDocListSerializer(serializers.ModelSerializer):
    file_ = FileSimpleSerializer(source='file', read_only=True)
    class Meta:
        model =  TechDoc
        fields = '__all__'
    
class TechDocCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = TechDoc
        fields = ['file', 'subproduction', 'name', 'content', 'enabled']

class TechDocUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = TechDoc
        fields = ['file', 'name', 'content', 'enabled']
