from django.db.models.signals import post_save
from django.dispatch import receiver

from apps.inm.models import FIFOItemProduct, IProduct, Inventory, MaterialBatch, FIFO, FIFOItem


def update_inm(instance:FIFO, type:int=1):
    """
    更新库存(正反)
    """
    if instance.type in [FIFO.FIFO_TYPE_PUR_IN, FIFO.FIFO_TYPE_DO_IN]: # 采购入库, 生产入库
        # 更新相关表
        for i in FIFOItem.objects.filter(fifo=instance):
            material = i.material
            warehouse = i.warehouse
            o1, _ = Inventory.objects.get_or_create(material=material, warehouse=warehouse, \
                defaults={'material':material, 'warehouse':warehouse, 'count':0})
            o1.count = o1.count + i.count
            o1.save()
            o2, _ = MaterialBatch.objects.get_or_create(material=material, warehouse=warehouse, batch=i.batch,\
                defaults={'material':material, 'warehouse':warehouse, 'count':0, 'batch':i.batch})
            o2.count = o2.count + i.count
            o2.save()
            material.count = material.count + i.count
            material.save()
    
            # 创建IProduct
            ips2 = []
            for m in FIFOItemProduct.objects.filter(fifoitem=i):
                ip = {}
                ip['warehouse'] = warehouse
                ip['batch'] = i.batch
                ip['wproduct'] = m.wproduct
                ip['number'] = m.number
                ip['material'] = m.material
                ips2.append(IProduct(**ip))
            IProduct.objects.bulk_create(ips2)

    elif instance.type in [FIFO.FIFO_TYPE_DO_OUT, FIFO.FIFO_TYPE_SALE_OUT]: # 生产领料 销售出库
        # 更新相关表
        for i in FIFOItem.objects.filter(fifo=instance):
            material = i.material
            warehouse = i.warehouse
            o1 = Inventory.objects.get(material=material, warehouse=warehouse)
            o1.count = o1.count - i.count
            o1.save()
            o2 = MaterialBatch.objects.get(material=material, warehouse=warehouse, batch=i.batch)
            o2.count = o2.count - i.count
            o2.save()
            material.count = material.count - i.count
            material.save()

            # 删除IProduct
            if instance.type == FIFO.FIFO_TYPE_DO_OUT:
                numbers = FIFOItemProduct.objects.filter(fifoitem=i).values_list('number', flat=True)
                IProduct.objects.filter(number__in=numbers).delete()
            
