from rest_framework.exceptions import ValidationError
from apps.pum.models import PuOrderItem, PuPlan, PuPlanItem, PuOrder
from django.db.models import F
from apps.inm.models import MIO, MIOItem


class PumService:

    def change_puplan_state_when_puorder_sumbit(puorder: PuOrder):
        puplanIds = PuPlanItem.objects.filter(
            pu_order=puorder).values_list('pu_plan', flat=True)
        for id in puplanIds:
            puplan = PuPlan.objects.get(id=id)
            state = puplan.state
            if PuPlanItem.objects.filter(pu_plan=puplan).count() == PuPlanItem.objects.filter(pu_plan=puplan, pu_order__state__gte=PuOrder.PUORDER_SUBMITED).count():
                state = PuPlan.PUPLAN_ORDERED
            else:
                state = PuPlan.PUPLAN_ORDERING
            puplan.state = state
            puplan.save()

    def mio_purin(mio: MIO):
        """
        采购入库成功后的操作
        """
        pu_order = mio.pu_order
        for i in MIOItem.objects.filter(mio=mio):
            pu_orderitem = PuOrderItem.objects.get(
                material=i.material, pu_order=pu_order)
            delivered_count = pu_orderitem.delivered_count + i.count
            if delivered_count > pu_orderitem.count:
                raise ValidationError(f'{i.material.name}-超出采购订单所需数量')
            pu_orderitem.delivered_count = delivered_count
            pu_orderitem.save()
        pu_order_state = PuOrder.PUORDER_SHIP
        qs = PuOrderItem.objects.filter(
            pu_order=pu_order, count__gt=F('delivered_count'))  # 查询未完全到货的
        if qs.exists():
            pass
        else:
            pu_order_state = PuOrder.PUORDER_DONE
        pu_order.state = pu_order_state
        pu_order.save()

        # 更新采购计划进度
        qs2 = PuPlanItem.objects.filter(pu_order=pu_order).values_list(
            'pu_plan').distinct()
        for puplan in qs2:
            qs3 = PuPlanItem.objects.filter(pu_plan=puplan).values_list(
                'pu_order__state', flat=True)
            states = set(list(qs3))
            if len(states) == 1 and list(states)[0] == PuOrder.PUORDER_DONE:
                puplan.state = PuPlan.PUPLAN_DONE
                puplan.save()
