from rest_framework.exceptions import ValidationError
from apps.pum.models import PuOrderItem, PuPlan, PuPlanItem, PuOrder, SupplierAudit
from django.db.models import F, Sum
from apps.inm.models import MIO, MIOItem
from rest_framework.exceptions import ParseError
from apps.wf.models import Ticket, Transition

class PumService:

    @staticmethod
    def cal_pu_order_total_price(puorder: PuOrder):
        total_price = PuOrderItem.objects.filter(pu_order=puorder).aggregate(total=Sum("total_price"))["total"] or 0
        puorder.total_price = total_price
        puorder.save()
    
    @staticmethod
    def cal_pu_plan_total_price(puplan: PuPlan):
        total_price = PuPlanItem.objects.filter(pu_plan=puplan).aggregate(total=Sum("total_price"))["total"] or 0
        puplan.total_price = total_price
        puplan.save()

    @staticmethod
    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()

    @staticmethod
    def mio_pur(mio: MIO, is_reverse: bool = False, mioitem: MIOItem = None):
        """
        采购入库成功后的操作
        """
        pu_order = mio.pu_order
        if pu_order is None:
            return
        if mioitem is None:
            qs = MIOItem.objects.filter(mio=mio)
        else:
            qs = MIOItem.objects.filter(id=mioitem.id)
        

        if mio.type == MIO.MIO_TYPE_PUR_IN:
            if is_reverse:
                xtype = "out"
            else:
                xtype = "in"
        elif mio.type == MIO.MIO_TYPE_PUR_OUT:
            if is_reverse:
                xtype = "in"
            else:
                xtype = "out"

        for i in qs:
            try:
                pu_orderitem = PuOrderItem.objects.get(
                    material=i.material, pu_order=pu_order)
            except PuOrderItem.DoesNotExist:
                raise ParseError(f'{str(i.material)}-采购订单中不存在该物料')
            if xtype == "out":
                delivered_count = pu_orderitem.delivered_count - i.count
            else:
                delivered_count = pu_orderitem.delivered_count + i.count
            if delivered_count > pu_orderitem.count:
                raise ValidationError(f'{str(i.material)}-超出采购订单所需数量')
            elif delivered_count < 0:
                raise ValidationError(f'{str(i.material)}-数量小于0')
            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()

def bind_supplieraudit(ticket: Ticket, transition: Transition, new_ticket_data: dict):
    ins = SupplierAudit.objects.get(id=new_ticket_data['t_id'])
    if ins.ticket and ins.ticket.id != ticket.id:
        raise ParseError('重复创建工单')
    ticket_data = ticket.ticket_data
    ticket_data.update({
        't_model': 'supplier_audit',
        't_id': ins.id,
    })
    ticket.ticket_data = ticket_data
    ticket.create_by = ins.create_by
    ticket.save()
    if ins.ticket is None:
        ins.ticket = ticket
        ins.save()