package com.hw.wms.service.impl;

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

import com.hw.common.core.constant.WmsConstants;
import com.hw.common.core.exception.ServiceException;
import com.hw.common.core.utils.uuid.Seq;
import com.hw.common.security.utils.SecurityUtils;
import com.hw.wms.domain.WmsBaseWarehouse;
import com.hw.wms.domain.WmsProductStock;
import com.hw.wms.domain.vo.WmsProductOutstockConfirmVo;
import com.hw.wms.mapper.WmsBaseWarehouseMapper;
import com.hw.wms.mapper.WmsProductOutstockDetailMapper;
import com.hw.wms.mapper.WmsProductStockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

import com.hw.common.core.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.hw.wms.domain.WmsProductOutstockDetail;
import com.hw.wms.mapper.WmsProductOutstockMapper;
import com.hw.wms.domain.WmsProductOutstock;
import com.hw.wms.service.IWmsProductOutstockService;

/**
 * 成品出库记录Service业务层处理
 *
 * @author xs
 * @date 2023-12-20
 */
@Service
public class WmsProductOutstockServiceImpl implements IWmsProductOutstockService {
    @Autowired
    private WmsProductOutstockMapper wmsProductOutstockMapper;

    @Autowired
    private WmsProductOutstockDetailMapper wmsProductOutstockDetailMapper;

    @Autowired
    private WmsProductStockMapper wmsProductStockMapper;

    @Autowired
    private WmsBaseWarehouseMapper wmsBaseWarehouseMapper;

    /**
     * 查询成品出库记录
     *
     * @param productOutstockId 成品出库记录主键
     * @return 成品出库记录
     */
    @Override
    public WmsProductOutstock selectWmsProductOutstockByProductOutstockId(Long productOutstockId) {
        return wmsProductOutstockMapper.selectWmsProductOutstockByProductOutstockId(productOutstockId);
    }

    /**
     * 查询成品出库记录列表
     *
     * @param wmsProductOutstock 成品出库记录
     * @return 成品出库记录
     */
    @Override
    public List<WmsProductOutstock> selectWmsProductOutstockList(WmsProductOutstock wmsProductOutstock) {
        return wmsProductOutstockMapper.selectWmsProductOutstockList(wmsProductOutstock);
    }

    /**
     * 新增成品出库记录
     *
     * @param wmsProductOutstock 成品出库记录
     * @return 结果
     */
    @Override
    public int insertWmsProductOutstock(WmsProductOutstock wmsProductOutstock) {
        Long warehouseId = wmsProductOutstock.getWarehouseId();
        String saleorderCode = wmsProductOutstock.getSaleorderCode();
        Long productId = wmsProductOutstock.getProductId();
        BigDecimal applyQty = wmsProductOutstock.getApplyQty();

        WmsProductStock queryProductStock = new WmsProductStock();
        queryProductStock.setWarehouseId(warehouseId);
        queryProductStock.setSaleorderCode(saleorderCode);
        queryProductStock.setProductId(productId);
        queryProductStock.setSaleOrderId(wmsProductOutstock.getSaleOrderId());
        List<WmsProductStock> productStocks = wmsProductStockMapper.selectWmsProductStocksBySaleorder(queryProductStock);
        if (productStocks == null || productStocks.isEmpty()) {
            throw new ServiceException("没有库存");
        }

        WmsProductStock productStock = productStocks.get(0);
        BigDecimal orderAmount = productStock.getOrderAmount();
        /*获取仓库可用库存数量*/
        BigDecimal totalAmount = productStock.getTotalAmount() == null ? BigDecimal.ZERO : 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);
        BigDecimal sumApplyQty = productStock.getApplyAmount() == null ? BigDecimal.ZERO : productStock.getApplyAmount();//获取已申请出库数量

//        WmsProductOutstock queryProductOutStock = new WmsProductOutstock();
//        queryProductOutStock.setSaleorderCode(saleorderCode);
//        queryProductOutStock.setSaleOrderId(wmsProductOutstock.getSaleOrderId());
//        queryProductOutStock.setWarehouseId(warehouseId);
//        queryProductOutStock.setProductId(productId);
//        List<WmsProductOutstock> wmsProductOutstocks = wmsProductOutstockMapper.selectWmsProductOutstockList(queryProductOutStock);
//        BigDecimal sumApplyQty = wmsProductOutstocks.stream().map(WmsProductOutstock::getApplyQty).reduce(BigDecimal.ZERO, BigDecimal::add);

        //可申请数量
        BigDecimal availableApplyQty = availableAmount.subtract(sumApplyQty);

        if (applyQty.compareTo(availableApplyQty) > 0) {
            throw new ServiceException("可申请数量为" + availableApplyQty);
        }

        WmsBaseWarehouse warehouse = wmsBaseWarehouseMapper.selectWmsBaseWarehouseByWarehouseId(warehouseId);
        String operationType = warehouse.getWarehouseType().equals(WmsConstants.WMS_WAREHOUSE_TYPE_NORMAL)
                ? WmsConstants.WMS_OPERATION_TYPE_MANUAL : WmsConstants.WMS_OPERATION_TYPE_AUTO;

        String userName = SecurityUtils.getUsername();
        Date currentDate = new Date();
        wmsProductOutstock.setProductType(WmsConstants.WMS_PRODUCT_OUTSTOCK_PRODUCT_TYPE_PRODUCT);
        wmsProductOutstock.setOperationType(operationType);
        wmsProductOutstock.setOutstockType(WmsConstants.WMS_PRODUCT_OUTSTOCK_TYPE_SALE);
        wmsProductOutstock.setAuditStatus(WmsConstants.WMS_AUDIT_STATUS_PASS);
        wmsProductOutstock.setExecuteStatus(WmsConstants.WMS_EXECUTE_STATUS_TOEXECUTE);
        wmsProductOutstock.setApplyBy(userName);
        wmsProductOutstock.setApplyDate(currentDate);
        wmsProductOutstock.setTaskCode(Seq.getId(Seq.productOutstockSeqType, Seq.productOutstockCode));

        int rows = wmsProductOutstockMapper.insertWmsProductOutstock(wmsProductOutstock);

        //如果是agv自动仓库，需要调用WCS轮询查询成品出库记录进行调度出库

        return rows;
    }

    /**
     * 修改成品出库记录
     *
     * @param wmsProductOutstock 成品出库记录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateWmsProductOutstock(WmsProductOutstock wmsProductOutstock) {
        wmsProductOutstockMapper.deleteWmsProductOutstockDetailByProductOutstockId(wmsProductOutstock.getProductOutstockId());
        insertWmsProductOutstockDetail(wmsProductOutstock);
        return wmsProductOutstockMapper.updateWmsProductOutstock(wmsProductOutstock);
    }

    /**
     * 批量删除成品出库记录
     *
     * @param productOutstockIds 需要删除的成品出库记录主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteWmsProductOutstockByProductOutstockIds(Long[] productOutstockIds) {
        wmsProductOutstockMapper.deleteWmsProductOutstockDetailByProductOutstockIds(productOutstockIds);
        return wmsProductOutstockMapper.deleteWmsProductOutstockByProductOutstockIds(productOutstockIds);
    }

    /**
     * 删除成品出库记录信息
     *
     * @param productOutstockId 成品出库记录主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteWmsProductOutstockByProductOutstockId(Long productOutstockId) {
        wmsProductOutstockMapper.deleteWmsProductOutstockDetailByProductOutstockId(productOutstockId);
        return wmsProductOutstockMapper.deleteWmsProductOutstockByProductOutstockId(productOutstockId);
    }

    /**
     * 新增成品出库记录明细信息
     *
     * @param wmsProductOutstock 成品出库记录对象
     */
    public void insertWmsProductOutstockDetail(WmsProductOutstock wmsProductOutstock) {
        List<WmsProductOutstockDetail> wmsProductOutstockDetailList = wmsProductOutstock.getWmsProductOutstockDetailList();
        Long productOutstockId = wmsProductOutstock.getProductOutstockId();
        if (StringUtils.isNotNull(wmsProductOutstockDetailList)) {
            List<WmsProductOutstockDetail> list = new ArrayList<WmsProductOutstockDetail>();
            for (WmsProductOutstockDetail wmsProductOutstockDetail : wmsProductOutstockDetailList) {
                wmsProductOutstockDetail.setProductOutstockId(productOutstockId);
                list.add(wmsProductOutstockDetail);
            }
            if (list.size() > 0) {
                wmsProductOutstockMapper.batchWmsProductOutstockDetail(list);
            }
        }
    }


    /**
     * 查询成品出库记录列表 Join material，warehouse
     *
     * @param wmsProductOutstock 成品出库记录
     * @return 成品出库记录
     */
    @Override
    public List<WmsProductOutstock> selectWmsProductOutstockJoinList(WmsProductOutstock wmsProductOutstock) {
        return wmsProductOutstockMapper.selectWmsProductOutstockJoinList(wmsProductOutstock);
    }


    /**
     * 查询成品出库记录,join warehouse,material,获取出库总数量
     *
     * @param productOutstockId 成品出库记录主键
     * @return 成品出库记录
     */
    @Override
    public WmsProductOutstock selectWmsProductOutstockJoinByOutstockId(Long productOutstockId) {
        return wmsProductOutstockMapper.selectWmsProductOutstockJoinByOutstockId(productOutstockId);
    }


    /**
     * 适用于成品出库后，运输到指定地点，根据销售订单最终确认
     *
     * @param wmsProductOutstockConfirmVo
     * @return
     */
    @Override
    public int finalConfirmProductOutstock(WmsProductOutstockConfirmVo wmsProductOutstockConfirmVo) {
        WmsProductOutstockDetail productOutstockDetail = wmsProductOutstockDetailMapper.
                selectWmsProductOutstockDetailByProductBarcode(wmsProductOutstockConfirmVo.getMaterialBarcode());
        if (productOutstockDetail == null) {
            throw new ServiceException("没有此成品出库信息");
        }

        String executeStatus = productOutstockDetail.getExecuteStatus();
        if (executeStatus.equals(WmsConstants.WMS_EXECUTE_STATUS_CONFIRM)) {
            throw new ServiceException("此成品出库已经确认，无需再次确认");
        }
        if (!executeStatus.equals(WmsConstants.WMS_EXECUTE_STATUS_FINISH)) {
            throw new ServiceException("此成品还未出库，不能进行确认");
        }

        WmsProductOutstock wmsProductOutstock = wmsProductOutstockMapper.
                selectOnlyWmsProductOutstockByOutstockId(productOutstockDetail.getProductOutstockId());
        if (wmsProductOutstock.getSaleorderCode() == null ||
                !wmsProductOutstock.getSaleorderCode().equals(wmsProductOutstockConfirmVo.getSaleorderCode())) {
            throw new ServiceException("销售订单成品出库记录不匹配");
        }

        productOutstockDetail.setExecuteStatus(WmsConstants.WMS_EXECUTE_STATUS_CONFIRM);
        productOutstockDetail.setConfirmAmount(BigDecimal.ONE);
        productOutstockDetail.setUpdateDate(new Date());
        productOutstockDetail.setUpdateBy(SecurityUtils.getUsername());

        return wmsProductOutstockDetailMapper.updateWmsProductOutstockDetail(productOutstockDetail);
    }

}
