from apps.inm.models import MIO, MIOItem, MaterialBatch, MaterialBatchA, MIOItemA
from rest_framework.exceptions import ValidationError, ParseError
from django.db.models.aggregates import Sum
from apps.wpm.services import do_out, do_in
from apps.mtm.models import Material


class InmService:

    @classmethod
    def update_inm(cls, instance: MIO):
        """
        更新库存, 暂不支持反向操作
        """
        if instance.type in [MIO.MIO_TYPE_PUR_IN, MIO.MIO_TYPE_DO_IN, MIO.MIO_TYPE_OTHER_IN]:  # 采购入库, 生产入库, 其他入库
            cls.update_mb(instance)
            if instance.type == MIO.MIO_TYPE_PUR_IN:  # 需要更新订单
                from apps.pum.services import PumService
                PumService.mio_purin(instance)
            elif instance.type == MIO.MIO_TYPE_DO_IN:
                do_in(instance)
        elif instance.type in [MIO.MIO_TYPE_DO_OUT, MIO.MIO_TYPE_SALE_OUT, MIO.MIO_TYPE_OTHER_OUT]:  # 生产领料 销售出库
            cls.update_mb(instance, -1)
            if instance.type == MIO.MIO_TYPE_SALE_OUT:
                from apps.sam.services import SamService
                SamService.mio_saleout(instance)
            elif instance.type == MIO.MIO_TYPE_DO_OUT:
                do_out(instance)

    @classmethod
    def update_mb(cls, instance: MIO, in_or_out: int = 1):
        """
        更新物料批次
        """
        mioitems = MIOItem.objects.filter(mio=instance)
        if not mioitems.exists():
            raise ParseError('未填写物料明细')
        for i in MIOItem.objects.filter(mio=instance):
            material = i.material
            warehouse = i.warehouse
            mb, is_created = MaterialBatch.objects.get_or_create(material=material, warehouse=warehouse, batch=i.batch,
                                                                 defaults={'material': material, 'warehouse': warehouse, 'count': 0, 'batch': i.batch})
            if in_or_out == 1:
                mb.count = mb.count + i.count
                # if mb.expiration_date is None:
                #     mb.expiration_date = i.expiration_date
                mb.save()
                mias = MIOItemA.objects.filter(mioitem=i)
                if mias.exists():  # 组合件入库
                    if not is_created:
                        raise ParseError('该批次组合件已存在')
                    for mia in mias:
                        MaterialBatchA.objects.create(
                            mb=mb, material=mia.material, batch=mia.batch)
            elif in_or_out == -1:
                mb.count = mb.count - i.count
                if mb.count < 0:
                    raise ParseError('批次库存不足,操作失败')
                elif mb.count == 0:
                    mb.delete()
                else:
                    mb.save()
            else:
                raise ParseError('不支持的操作')
            material_count = MaterialBatch.objects.filter(
                material=material).aggregate(total=Sum('count')).get('total', 0)
            Material.objects.filter(id=material.id).update(
                count=material_count)
