package com.hw.wms.service.impl;

import com.hw.common.core.constant.WmsConstants;
import com.hw.common.core.exception.ServiceException;
import com.hw.wms.domain.WmsProductStock;
import com.hw.wms.domain.WmsTransfer;
import com.hw.wms.mapper.WmsProductStockMapper;
import com.hw.wms.mapper.WmsTransferMapper;
import com.hw.wms.service.IWmsTransactionalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @Description:用来在循环内执行事务时调用
 * @ProjectName:HwMes
 * @Author:xins
 * @Date:2024-01-15 10:29
 * @Version:1.0
 */
@Service
public class WmsTransactionalServiceImpl implements IWmsTransactionalService {
    @Autowired
    private WmsProductStockMapper wmsProductStockMapper;

    @Autowired
    private WmsTransferMapper wmsTransferMapper;


    /**
     * @Description: 申请转库（适合五楼半成品出半成品库入成品库）
     * @ClassName: WmsTransactionalServiceImpl
     * @Author : xins
     * @Date :2024-01-15  10:37
     * @Version :1.0
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void applyTransfer(WmsTransfer wmsTransfer, String userName, Date currentDate) {
        BigDecimal applyQty = wmsTransfer.getApplyQty();
        String productBatch = wmsTransfer.getProductBatch();
        String oriLocationCode = wmsTransfer.getOriLocationCode();
        WmsProductStock wmsProductStock = wmsProductStockMapper.selectProductStockByBatch(productBatch);
        if (wmsProductStock == null) {
            throw new ServiceException("库位["+oriLocationCode+"]没有此批次["+productBatch+"]的库存");
        }
        BigDecimal totalAmount = wmsProductStock.getTotalAmount() == null ? BigDecimal.ZERO : wmsProductStock.getTotalAmount();
        BigDecimal frozenAmount = wmsProductStock.getFrozenAmount() == null ? BigDecimal.ZERO : wmsProductStock.getFrozenAmount();
        BigDecimal occupyAmount = wmsProductStock.getOccupyAmount() == null ? BigDecimal.ZERO : wmsProductStock.getOccupyAmount();
        BigDecimal avaialableAmount = totalAmount.subtract(frozenAmount).subtract(occupyAmount);
        if (avaialableAmount.compareTo(applyQty) < 0) {
            throw new ServiceException("库位["+oriLocationCode+"],批次["+productBatch+"]的申请数量不能大于" + avaialableAmount);
        }

        wmsProductStock.setOccupyAmount(occupyAmount.add(applyQty));

        wmsProductStockMapper.updateWmsProductStock(wmsProductStock);

        wmsTransfer.setApplyBy(userName);
        wmsTransfer.setApplyDate(currentDate);
        wmsTransfer.setOperationType(WmsConstants.WMS_OPERATION_TYPE_MANUAL);
        wmsTransfer.setTransferType(WmsConstants.WMS_TRANSFER_TYPE_OUT_TO_PRODUCT_STOCK);
        wmsTransfer.setAuditStatus(WmsConstants.WMS_AUDIT_STATUS_PASS);
        wmsTransfer.setExecuteStatus(WmsConstants.WMS_EXECUTE_STATUS_TOEXECUTE);
        wmsTransferMapper.insertWmsTransfer(wmsTransfer);
    }
}
