package com.hw.wms.service.impl;

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

import com.alibaba.cloud.commons.lang.StringUtils;
import com.hw.common.core.constant.SecurityConstants;
import com.hw.common.core.constant.WmsConstants;
import com.hw.common.core.domain.R;
import com.hw.common.core.exception.ServiceException;
import com.hw.common.security.utils.SecurityUtils;
import com.hw.mes.api.RemoteMesService;
import com.hw.mes.api.domain.MesBaseBarcodeInfo;
import com.hw.wms.config.WmsConfig;
import com.hw.wms.domain.WmsBaseLocation;
import com.hw.wms.domain.WmsProductOutstock;
import com.hw.wms.domain.WmsProductStock;
import com.hw.wms.mapper.WmsBaseLocationMapper;
import com.hw.wms.mapper.WmsProductOutstockMapper;
import com.hw.wms.mapper.WmsProductStockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hw.wms.mapper.WmsProductOutstockDetailMapper;
import com.hw.wms.domain.WmsProductOutstockDetail;
import com.hw.wms.service.IWmsProductOutstockDetailService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 成品出库记录明细Service业务层处理
 *
 * @author xins
 * @date 2024-01-16
 */
@Service
public class WmsProductOutstockDetailServiceImpl implements IWmsProductOutstockDetailService {
    @Autowired
    private WmsProductOutstockDetailMapper wmsProductOutstockDetailMapper;

    @Autowired
    private WmsProductOutstockMapper wmsProductOutstockMapper;

    @Autowired
    private WmsProductStockMapper wmsProductStockMapper;

    @Autowired
    private WmsBaseLocationMapper wmsBaseLocationMapper;

    @Autowired
    private WmsConfig wmsConfig;

    @Resource
    private RemoteMesService remoteMesService;


    /**
     * 查询成品出库记录明细
     *
     * @param productOutstockDetailId 成品出库记录明细主键
     * @return 成品出库记录明细
     */
    @Override
    public WmsProductOutstockDetail selectWmsProductOutstockDetailByProductOutstockDetailId(Long productOutstockDetailId) {
        return wmsProductOutstockDetailMapper.selectWmsProductOutstockDetailByProductOutstockDetailId(productOutstockDetailId);
    }

    /**
     * 查询成品出库记录明细列表
     *
     * @param wmsProductOutstockDetail 成品出库记录明细
     * @return 成品出库记录明细
     */
    @Override
    public List<WmsProductOutstockDetail> selectWmsProductOutstockDetailList(WmsProductOutstockDetail wmsProductOutstockDetail) {
        return wmsProductOutstockDetailMapper.selectWmsProductOutstockDetailList(wmsProductOutstockDetail);
    }

    /**
     * 新增成品出库记录明细
     * 人工成品出库确认（适用于成品仓库库管的成品出库确认）
     *
     * @param wmsProductOutstockDetail 成品出库记录明细
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertWmsProductOutstockDetail(WmsProductOutstockDetail wmsProductOutstockDetail) {
        String locationCode = wmsProductOutstockDetail.getLocationCode();
        String productBarcode = wmsProductOutstockDetail.getProductBarcode();//成品条码和批次码相同
        Long productOutstockId = wmsProductOutstockDetail.getProductOutstockId();

        R<MesBaseBarcodeInfo> baseBarcodeInfoR = remoteMesService.getBarcode(productBarcode, SecurityConstants.INNER);
        if (baseBarcodeInfoR == null) {
            throw new ServiceException("物料编码有误");
        }
        MesBaseBarcodeInfo baseBarcodeInfo = baseBarcodeInfoR.getData();
        if (baseBarcodeInfo == null) {
            throw new ServiceException("物料编码有误");
        }

        WmsProductOutstock productOutstock = wmsProductOutstockMapper.selectOnlyWmsProductOutstockByOutstockId(productOutstockId);
        if (productOutstock == null) {
            throw new ServiceException("没有此成品出库任务信息");
        }

        if(!productOutstock.getProductId().equals(baseBarcodeInfo.getMaterialId())) {
            throw new ServiceException("物料编码有误");
        }

        if(StringUtils.isEmpty(locationCode) &&
                (wmsConfig.getFirstFloorProductWarehouseId().equals(productOutstock.getWarehouseId()) ||
                        wmsConfig.getFourthFloorProductWarehouseId().equals(productOutstock.getWarehouseId()))){
            locationCode = "0";
            wmsProductOutstockDetail.setLocationCode("0");
        }else{
            WmsBaseLocation location = wmsBaseLocationMapper.selectWmsBaseLocationByLocationCode(locationCode);
            if (location == null) {
                throw new ServiceException(String.format("库位编码%1$s错误", locationCode));
            }
            if (!productOutstock.getWarehouseId().equals(location.getWarehouseId())) {
                throw new ServiceException("没有此仓库出库任务");
            }
        }

        if (productOutstock.getExecuteStatus().equals(WmsConstants.WMS_EXECUTE_STATUS_FINISH)) {
            throw new ServiceException("此出库申请已完成，不能再出库");
        }

        WmsProductStock productStock = wmsProductStockMapper.selectProductStockByBatch(productBarcode);
        if (productStock == null || !productStock.getSaleOrderId().equals(productOutstock.getSaleOrderId())) {
            throw new ServiceException("此库位没有对应订单库存");
        }

        BigDecimal totalAmount = productStock.getTotalAmount();
        BigDecimal frozenAmount = productStock.getFrozenAmount() == null ? BigDecimal.ZERO : productStock.getFrozenAmount();
        BigDecimal occupyAmount = productStock.getOccupyAmount() == null ? BigDecimal.ZERO : productStock.getOccupyAmount();

        BigDecimal availableAmount = totalAmount.subtract(frozenAmount).subtract(occupyAmount);
        if (availableAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("此库位没有可出库存");
        }


        /**判断已出库数量和申请的数量*/
        BigDecimal applyQty = productOutstock.getApplyQty() == null ? BigDecimal.ZERO : productOutstock.getApplyQty();
        BigDecimal outstockQty = productOutstock.getOutstockQty() == null ? BigDecimal.ZERO : productOutstock.getOutstockQty();

        BigDecimal currentOutstockQty = outstockQty.add(BigDecimal.ONE);
        if (applyQty.compareTo(currentOutstockQty) < 0) {
            throw new ServiceException(String.format("出库申请数量为%1$s，不能再出库", applyQty));
        }

        String userName = SecurityUtils.getUsername();
        Date currentDate = new Date();
        //更新出库记录
        if (applyQty.compareTo(currentOutstockQty) == 0) {
            productOutstock.setExecuteStatus(WmsConstants.WMS_EXECUTE_STATUS_FINISH);
            productOutstock.setEndTime(currentDate);
        } else if (applyQty.compareTo(currentOutstockQty) > 0) {
            productOutstock.setExecuteStatus(WmsConstants.WMS_EXECUTE_STATUS_EXECUTING);
        }

        productOutstock.setOutstockQty(currentOutstockQty);
        if (productOutstock.getBeginTime() == null) {
            productOutstock.setBeginTime(currentDate);
        }
        productOutstock.setUpdateDate(currentDate);
        productOutstock.setUpdateBy(userName);
        wmsProductOutstockMapper.updateWmsProductOutstock(productOutstock);

        //删除库存(由于一个成品对应一个库存信息，删除即可)
//        productStock.setTotalAmount(totalAmount.subtract(BigDecimal.ONE));
//        productStock.setUpdateBy(userName);
//        productStock.setUpdateDate(currentDate);
//        wmsProductStockMapper.updateWmsProductStock(productStock);
        wmsProductStockMapper.deleteWmsProductStockByProductStockId(productStock.getProductStockId());

        //插入出库记录明细
        wmsProductOutstockDetail.setExecuteStatus(WmsConstants.WMS_EXECUTE_STATUS_FINISH);
        wmsProductOutstockDetail.setBeginTime(currentDate);
        wmsProductOutstockDetail.setEndTime(currentDate);
        wmsProductOutstockDetail.setWarehouseId(productStock.getWarehouseId());
        wmsProductOutstockDetail.setPlanAmount(BigDecimal.ONE);
        wmsProductOutstockDetail.setOutstockAmount(BigDecimal.ONE);

        wmsProductOutstockDetailMapper.insertWmsProductOutstockDetail(wmsProductOutstockDetail);

        return 1;
    }

    /**
     * 修改成品出库记录明细
     *
     * @param wmsProductOutstockDetail 成品出库记录明细
     * @return 结果
     */
    @Override
    public int updateWmsProductOutstockDetail(WmsProductOutstockDetail wmsProductOutstockDetail) {
        return wmsProductOutstockDetailMapper.updateWmsProductOutstockDetail(wmsProductOutstockDetail);
    }

    /**
     * 批量删除成品出库记录明细
     *
     * @param productOutstockDetailIds 需要删除的成品出库记录明细主键
     * @return 结果
     */
    @Override
    public int deleteWmsProductOutstockDetailByProductOutstockDetailIds(Long[] productOutstockDetailIds) {
        return wmsProductOutstockDetailMapper.deleteWmsProductOutstockDetailByProductOutstockDetailIds(productOutstockDetailIds);
    }

    /**
     * 删除成品出库记录明细信息
     *
     * @param productOutstockDetailId 成品出库记录明细主键
     * @return 结果
     */
    @Override
    public int deleteWmsProductOutstockDetailByProductOutstockDetailId(Long productOutstockDetailId) {
        return wmsProductOutstockDetailMapper.deleteWmsProductOutstockDetailByProductOutstockDetailId(productOutstockDetailId);
    }
}
