from rest_framework import serializers
from apps.utils.serializers import CustomModelSerializer
from apps.utils.constants import EXCLUDE_FIELDS_DEPT, EXCLUDE_FIELDS_BASE, EXCLUDE_FIELDS
from rest_framework.exceptions import ValidationError

from apps.pum.models import Supplier, PuPlan, PuPlanItem, PuOrder, PuOrderItem
from apps.mtm.serializers import MaterialSerializer, MaterialSimpleSerializer
from django.db import transaction
from .services import PumService


class SupplierSerializer(CustomModelSerializer):
    class Meta:
        model = Supplier
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS_DEPT


class PuPlanSerializer(CustomModelSerializer):
    class Meta:
        model = PuPlan
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS_DEPT + ['state', 'submit_time', 'total_price']

    def update(self, instance, validated_data):
        if instance.state != PuPlan.PUPLAN_CREATE:
            raise ValidationError('该状态下不可编辑')
        return super().update(instance, validated_data)


class PuPlanItemSerializer(CustomModelSerializer):
    material_ = MaterialSerializer(source='material', read_only=True)
    pu_plan_number = serializers.CharField(
        source='pu_plan.number', read_only=True)
    create_by_name = serializers.CharField(
        source='create_by.name', read_only=True)
    belong_dept_name = serializers.CharField(
        source='belong_dept.name', read_only=True)
    note = serializers.CharField(required=False, allow_blank=True)

    class Meta:
        model = PuPlanItem
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS + ['pu_order']

    @transaction.atomic
    def create(self, validated_data):
        pu_plan = validated_data['pu_plan']
        if pu_plan.state != PuPlan.PUPLAN_CREATE:
            raise ValidationError('该状态下不可添加需求')
        material = validated_data['material']
        self.complete_belong_dept(validated_data)
        if PuPlanItem.objects.filter(material=material, belong_dept=validated_data['belong_dept']).exists():
            raise ValidationError('同部门已提交该物料需求,请确认!')
        ins = super().create(validated_data)
        PumService.cal_pu_plan_total_price(pu_plan)
        return ins

    def complete_belong_dept(self, validated_data):
        belong_dept = validated_data.get('belong_dept', None)
        if belong_dept is None:
            belong_dept = self.context['request'].user.belong_dept
            if belong_dept is None:
                raise ValidationError('所属部门不可为空')
            else:
                validated_data['belong_dept'] = belong_dept
    
    @transaction.atomic
    def update(self, instance, validated_data):
        validated_data.pop('pu_plan')
        pu_plan = instance.pu_plan
        if pu_plan.state != PuPlan.PUPLAN_CREATE:
            raise ValidationError('该状态下不可编辑需求')
        material = validated_data['material']
        user = self.context['request'].user

        if instance.create_by != user:
            raise ValidationError('非创建人不可编辑')
        self.complete_belong_dept(validated_data)
        if PuPlanItem.objects.exclude(id=instance.id).filter(material=material, belong_dept=validated_data['belong_dept']).exists():
            raise ValidationError('同部门已提交该物料需求,请确认!')
        ins = super().update(instance, validated_data)
        PumService.cal_pu_plan_total_price(pu_plan)
        return ins


class PuOrderSerializer(CustomModelSerializer):
    supplier_name = serializers.CharField(
        source='supplier.name', read_only=True)
    create_by_name = serializers.CharField(
        source='create_by.name', read_only=True)
    update_by_name = serializers.CharField(
        source='update_by.name', read_only=True)
    materials_ = MaterialSimpleSerializer(
        source='materials', many=True, read_only=True)

    class Meta:
        model = PuOrder
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS_DEPT + ['state', 'submit_time', 'total_price']

    def update(self, instance, validated_data):
        validated_data.pop('supplier')
        if instance.state != PuOrder.PUORDER_CREATE:
            raise ValidationError('该状态下不可编辑')
        return super().update(instance, validated_data)


class PuOrderItemSerializer(CustomModelSerializer):
    material_ = MaterialSerializer(source='material', read_only=True)

    class Meta:
        model = PuOrderItem
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS_BASE + ['delivered_count']

    @transaction.atomic
    def create(self, validated_data):
        pu_order = validated_data['pu_order']
        material = validated_data['material']
        if pu_order.state != PuOrder.PUORDER_CREATE:
            raise ValidationError('采购订单该状态下不可添加明细')
        if PuOrderItem.objects.filter(pu_order=pu_order, material=material).exists():
            raise ValidationError('该物料已添加')
        ins = super().create(validated_data)
        PumService.cal_pu_order_total_price(pu_order)
        return ins

    @transaction.atomic
    def update(self, instance, validated_data):
        validated_data.pop('material')
        validated_data.pop('pu_order')
        pu_order = instance.pu_order
        if pu_order.state != PuOrder.PUORDER_CREATE:
            raise ValidationError('采购订单该状态下不可编辑')
        ins = super().update(instance, validated_data)
        PumService.cal_pu_order_total_price(pu_order)
        return ins


class AddSerializer(serializers.Serializer):
    pu_order = serializers.PrimaryKeyRelatedField(
        label='采购订单ID', queryset=PuOrder.objects.all())
    pu_planitems = serializers.PrimaryKeyRelatedField(
        label='计划明细ID', queryset=PuPlanItem.objects.all(), many=True)
