from apps.em.serializers import EquipmentSimpleSerializer
from rest_framework import serializers
from rest_framework.exceptions import ParseError, ValidationError
from .models import InputMaterial, Material, OutputMaterial, Process, RecordForm, RecordFormField, Step, 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).order_by('number')
        return ProcessSimpleSerializer(instance=objs, many=True).data


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

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

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)
    class Meta:
        model = Step
        fields = '__all__'
    
    @staticmethod
    def setup_eager_loading(queryset):
        queryset = queryset.prefetch_related('equipments')
        return queryset

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

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

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


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

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

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

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

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

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

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

class RecordFormFieldCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = RecordFormField
        fields = ['form', 'field_type', 'field_key', 'field_name', 'boolean_field_display', 'field_choice', 'sort']
    
    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
        fields = ['field_type', 'field_name', 'boolean_field_display', 'field_choice', 'sort']

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

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