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


class SamService:

    def mio_saleout(mio: MIO, is_reverse: bool = False):
        """
        销售出库成功后的操作
        """
        order = mio.order
        if order is None:
            return
        orderitem_qs = OrderItem.objects.filter(order=order)
        matIds = list(MIOItem.objects.filter(mio=mio).values_list('material__id', flat=True).distinct())
        matIds2 = list(orderitem_qs.values_list('material__id', flat=True).distinct())
        if set(matIds) != set(matIds2):
            raise ValidationError('订单与发货单物料不一致')
        for orderitem in orderitem_qs:
            material = orderitem.material
            delivered_count = MIOItem.objects.filter(
                mio__order=order, material=material, mio__type='sale_out', mio__submit_time__isnull=False).values('count').aggregate(Sum('count'))['count__sum']
            delivered_count = delivered_count if delivered_count else 0
            if delivered_count > orderitem.count:
                raise ValidationError((f'{str(material)}-超出订单所需数量'))
            elif delivered_count < 0:
                raise ValidationError((f'{str(material)}-数量小于0'))
            orderitem.delivered_count = delivered_count
            orderitem.save(update_fields=['delivered_count'])
        # 更新order的状态
        qs = OrderItem.objects.filter(
            order=order, count__gt=F('delivered_count'))
        order_state = Order.ORDER_DOING
        if qs.exists():
            pass
        else:
            order_state = Order.ORDER_DELIVERED
        order.state = order_state
        order.save()
