from rest_framework import serializers
from apps.utils.serializers import CustomModelSerializer
from apps.utils.constants import EXCLUDE_FIELDS
from apps.fim.models import PriceSet, FeeSet, Fee
from apps.mtm.models import Mgroup
from apps.wpm.models import SfLog
from rest_framework.exceptions import ParseError
from apps.fim.tasks import cal_enstat_when_priceset_change, cal_enstat_when_feeset_change

class FeeSerializer(CustomModelSerializer):
    class Meta:
        model = Fee
        fields = '__all__'


class FeeSetSerializer(CustomModelSerializer):
    mgroup_name = serializers.CharField(source='mgroup.name', read_only=True)
    fee_ = FeeSerializer(source='fee', read_only=True)
    class Meta:
        model = FeeSet
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS

    def update(self, instance, validated_data):
        validated_data.pop('year', None)
        validated_data.pop('month', None)
        validated_data.pop('mgroup', None)
        validated_data.pop('fee', None)
        old_cost_unit = instance.cost_unit
        instance = super().update(instance, validated_data)
        new_cost_unit = instance.cost_unit
        if new_cost_unit != old_cost_unit:
            cal_enstat_when_feeset_change.delay(instance.id)
        return instance

class PriceSetSerializer(CustomModelSerializer):
    material_name = serializers.CharField(source='material.name', read_only=True)
    class Meta:
        model = PriceSet
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS

    def update(self, instance, validated_data):
        validated_data.pop('year', None)
        validated_data.pop('month', None)
        validated_data.pop('material', None)
        old_price_unit = instance.price_unit
        instance = super().update(instance, validated_data)
        new_price_unit = instance.price_unit
        if new_price_unit != old_price_unit:
            cal_enstat_when_priceset_change.delay(instance.id)
        return instance


class CostStatSerializer(serializers.Serializer):
    type = serializers.CharField(label="统计维度", help_text="sflog/day_s/month_s/year_s")
    mgroup = serializers.PrimaryKeyRelatedField(label='工段ID', required=False, queryset=Mgroup.objects.all())
    sflog = serializers.PrimaryKeyRelatedField(label='值班记录ID', required=False, queryset=SfLog.objects.all())
    year_s = serializers.IntegerField(label="年", required=False)
    month_s = serializers.IntegerField(label="月", required=False)
    day_s = serializers.IntegerField(label="日", required=False)

    def validate(self, attrs):
        if type == 'sflog' and 'sflog' not in attrs:
            raise ParseError('未提供值班记录')
        elif type in ['year_s', 'month_s', 'day_s'] and 'mgroup' not in attrs:
            raise ParseError('未提供工段ID')
        elif type not in attrs:
            raise ParseError('缺少年月日')
        return super().validate(attrs)

    