from rest_framework import serializers
from rest_framework.exceptions import ValidationError, ParseError
import math

from apps.mtm.serializers import MaterialSimpleSerializer
from apps.pm.models import Mtask, Utask, SCHEDULE_TYPE, Mtaskb
from apps.sam.models import OrderItem
from apps.utils.serializers import CustomModelSerializer
from apps.system.models import Dept
from apps.wpm.models import Mlog
from apps.utils.constants import EXCLUDE_FIELDS_BASE
from apps.mtm.models import RoutePack, Material
from django.db import transaction


class UtaskSerializer(CustomModelSerializer):
    material_name = serializers.StringRelatedField(
        source='material', read_only=True)
    material_in_name = serializers.StringRelatedField(
        source='material_in', read_only=True)
    material_ = MaterialSimpleSerializer(source='material', read_only=True)
    mgroup_name = serializers.CharField(source='mgroup.name', read_only=True)
    belong_dept = serializers.PrimaryKeyRelatedField(
        queryset=Dept.objects.all(), required=False)

    class Meta:
        model = Utask
        fields = '__all__'
        extra_kwargs = {
            'number': {"required": False, "allow_blank": True},
            "priority": {"required": False, "allow_null": True},
        }

    def create(self, validated_data):
        if not validated_data.get('number', None):
            validated_data["number"] = Utask.get_a_number()
        routepack:RoutePack = validated_data.get("routepack", None)
        material:Material = validated_data.get("material", None)
        if routepack:
            finMatIds = routepack.get_final_material_ids()
            if (material and material.id not in finMatIds) or not material:
                raise ParseError('请指定正确的产品')
        return super().create(validated_data)
    
    def validate(self, attrs):
        end_date = attrs['end_date']
        start_date = attrs['start_date']
        if 'mgroup' in attrs and attrs['mgroup']:
            attrs['belong_dept'] = attrs['mgroup'].belong_dept
        try:
            rela_days = (end_date - start_date).days + 1
            attrs['count_day'] = math.ceil(attrs['count']/rela_days)
        except Exception:
            raise ParseError('日均任务数计划失败')
        attrs["priority"] = attrs.get("priority", 20)
        return attrs

    def update(self, instance, validated_data):
        if instance.state != Utask.UTASK_CREATED:
            raise ValidationError('任务非创建中不可编辑')
        new_data = {key: validated_data[key] for key in ['count', 'start_date', 'end_date']}
        return super().update(instance, new_data)


class MlogSimpleSerializer(CustomModelSerializer):
    shift_name = serializers.CharField(source='shift.name', read_only=True)

    class Meta:
        model = Mlog
        fields = ['id', 'shift_name', 'count_use',
                  'count_ok', 'count_real', 'submit_time']

class MtaskbAddSerializer(CustomModelSerializer):
    handle_user_name = serializers.StringRelatedField(
        source='handle_user.name', read_only=True)
    class Meta:
        model = Mtaskb
        fields = ['id', 'handle_user', 'handle_user_name', 'count']

class MtaskbSerializer(CustomModelSerializer):
    handle_user_name = serializers.StringRelatedField(
        source='handle_user.name', read_only=True)
    class Meta:
        model = Mtaskb
        fields = '__all__'
        read_only_fields = EXCLUDE_FIELDS_BASE

class MtaskbUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = Mtaskb
        fields = ['id', 'count']

class MtaskSerializer(CustomModelSerializer):
    material_out_ = MaterialSimpleSerializer(
        source='material_out', read_only=True)
    material_out_name = serializers.StringRelatedField(
        source='material_out', read_only=True)
    material_in_name = serializers.StringRelatedField(
        source='material_in', read_only=True)
    submit_user_name = serializers.StringRelatedField(
        source='submit_user.name', read_only=True)
    mgroup_name = serializers.CharField(source='mgroup.name', read_only=True)
    mlogs = MlogSimpleSerializer(label='日志信息', many=True, required=False)
    mtaskb = MtaskbSerializer(label='子任务信息', many=True, required=False, read_only=True)

    class Meta:
        model = Mtask
        fields = '__all__'
        read_only_fields = ['utask']

    def update(self, instance, validated_data):
        if instance.state != Mtask.MTASK_CREATED:
            raise ValidationError('任务非创建中不可编辑')
        if instance.utask is not None:
            new_data = {'count': validated_data['count']}
        else:
            new_data = {key: validated_data[key] for key in [
                'number', 'count', 'start_date', 'end_date']}
        return super().update(instance, new_data)

class SchedueMtasksSerializer(serializers.Serializer):
    ids = serializers.ListField(
        child=serializers.CharField(max_length=20), label="utask ID列表")
    schedule_type = serializers.ChoiceField(label='排产类型', choices=SCHEDULE_TYPE, required=False)

    def validate(self, attrs):
        if "schedule_type" not in attrs:
            attrs["schedule_type"] = "to_day"
        return super().validate(attrs)

class SchedueSerializer(serializers.Serializer):
    orderitems = serializers.PrimaryKeyRelatedField(
        label='orderitem的ID列表', queryset=OrderItem.objects.all(), many=True)
    start_date = serializers.DateField(label='计划开工日期')
    end_date = serializers.DateField(label='计划完工日期')
    belong_dept = serializers.PrimaryKeyRelatedField(
        label='车间ID', queryset=Dept.objects.all(), required=False)


class MtaskDaySerializer(serializers.Serializer):
    belong_dept_name = serializers.CharField(label='车间名称')
    date = serializers.DateField(label='日期')


class MtaskAddInfoSerializer(CustomModelSerializer):
    class Meta:
        model = Mtask
        fields = ['peifen_kg']