from apps.sam.models import Order, OrderItem
from rest_framework.exceptions import ValidationError
from django.db.models import F
from apps.inm.models import MIO, MIOItem


class SamService:

    def mio_saleout(mio: MIO):
        """
        销售出库成功后的操作
        """
        order = mio.order
        for i in MIOItem.objects.filter(mio=mio):
            orderitem = OrderItem.objects.get(order=order, material=i.material)
            delivered_count = orderitem.delivered_count + i.count
            if delivered_count > orderitem.count:
                raise ValidationError((f'{i.material.name}-超出订单所需数量'))
            orderitem.delivered_count = delivered_count
            orderitem.save()
        # 更新order的状态
        qs = OrderItem.objects.filter(
            order=order, count__lte=F('delivered_count'))
        if qs.exists():
            pass
        else:
            order.state = Order.ORDER_DELIVERED
            order.save()
