package com.wms_main.service.business.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wms_main.app.AppCommon;
import com.wms_main.constant.AppConstant;
import com.wms_main.constant.enums.wcs.WcsApiResponseCodeEnums;
import com.wms_main.constant.enums.wcs.WcsStackerTaskStatusEnums;
import com.wms_main.constant.enums.wcs.WcsStackerTaskTypeEnums;
import com.wms_main.constant.enums.wms.*;
import com.wms_main.dao.*;
import com.wms_main.model.bo.wcs.WcsPickTask;
import com.wms_main.model.bo.wcs.WcsStackerTask;
import com.wms_main.model.bo.wms.OrderConfirmEntity;
import com.wms_main.model.bo.wms.StockConfirmEntity;
import com.wms_main.model.bo.wms.TaskConfirmEntity;
import com.wms_main.model.bo.wms.WmsPickTask;
import com.wms_main.model.dto.request.wcs.WcsBoxArriveRequest;
import com.wms_main.model.dto.request.wcs.WcsPickTaskRequest;
import com.wms_main.model.dto.request.wcs.WcsReleaseBoxRequest;
import com.wms_main.model.dto.request.wcs.WcsStackerTaskRequest;
import com.wms_main.model.dto.response.wcs.BaseWcsApiResponse;
import com.wms_main.model.dto.response.wcs.WcsApiResponse;
import com.wms_main.model.po.*;
import com.wms_main.model.vo.wms.InventoryConfirmVo;
import com.wms_main.model.vo.wms.TaskConfirmVo;
import com.wms_main.model.vo.wms.WorkConfirmVo;
import com.wms_main.repository.utils.StringUtils;
import com.wms_main.repository.utils.UUIDUtils;
import com.wms_main.service.api.IWcsApiService;
import com.wms_main.service.business.IConveyTaskService;
import com.wms_main.service.business.IStockDataService;
import com.wms_main.service.controller.ITaskControllerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 输送线任务服务 实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ConveyTaskServiceImpl implements IConveyTaskService {
    private final IWcsApiService wcsApiService;// wcs api服务
    private final ITAppPickTaskService appPickTaskService;// 拣选任务服务
    private final ITAppPickTaskBakService appPickTaskBakService;// 拣选任务备份服务
    private final ITAppTaskService appTaskService;// 堆垛机任务服务
    private final ITAppWorkService appWorkService;// 工作服务
    private final ITAppOutsService appOutsService;// 出库单服务
    private final IStockDataService stockDataService;// 库存数据服务
    private final ITAppPickPlanService appPickPlanService;// 拣选计划服务
    private final ITAppStockService appStockService;// 库存服务
    private final AppCommon appCommon;
    private final ITAppVehicleService appVehicleService;// 载具服务
    private final ITAppInventoryService appInventoryService;// 盘点服务

    /**
     * 取消拣选任务实现
     *
     * @param vehicleStandMap 键为站台，值为WmsPickTask
     * @param successCount    成功数量
     * @param failCount       失败数量
     * @param exceptionCount  异常数量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelPickTasks(Map<String, WmsPickTask> vehicleStandMap, int successCount, int failCount, int exceptionCount) {
        // 循环取消
        for (String key : vehicleStandMap.keySet()) {
            WmsPickTask thisKeyPickTask = vehicleStandMap.get(key);
            try {
                WcsPickTaskRequest request = new WcsPickTaskRequest(
                        null,
                        thisKeyPickTask.getVehicleId(),
                        1,
                        thisKeyPickTask.getPickStand(),
                        ""
                );
                WcsApiResponse<WcsPickTask> wcsResponse = wcsApiService.cancelPickTask(request);
                if (wcsResponse != null && WcsApiResponseCodeEnums.SUCCESS.getCode() == wcsResponse.getCode()) {
                    // 将这些拣选任务添加进记录表
                    List<TAppPickTask> targetPickTasks = appPickTaskService.list(new LambdaQueryWrapper<TAppPickTask>()
                            .eq(TAppPickTask::getVehicleId, thisKeyPickTask.getVehicleId())
                            .eq(TAppPickTask::getPickStand, thisKeyPickTask.getPickStand())
                            .ne(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.FOR_IN.getCode()));
                    // 设置拣选任务记录
                    List<TAppPickTaskBak> pickRecords = new ArrayList<>();
                    for (TAppPickTask pickTask : targetPickTasks) {
                        TAppPickTaskBak pickRecord = new TAppPickTaskBak(
                                pickTask.getPickId(),
                                pickTask.getPickStand(),
                                pickTask.getVehicleId(),
                                WmsPickTaskStatusEnum.CANCEL.getCode(),
                                pickTask.getCreateTime(),
                                pickTask.getSendTime(),
                                LocalDateTime.now(),
                                LocalDateTime.now()
                        );
                        pickRecords.add(pickRecord);
                    }
                    // 添加记录
                    appPickTaskBakService.saveBatch(pickRecords);
                    // 删除拣选任务
                    appPickTaskService.removeByIds(targetPickTasks);
                    successCount++;
                    log.info("取消拣选任务成功。载具：{}，站台：{}。", thisKeyPickTask.getVehicleId(), thisKeyPickTask.getPickStand());
                } else {
                    failCount++;
                    log.error("取消拣选任务失败。载具：{}，站台：{}。", thisKeyPickTask.getVehicleId(), thisKeyPickTask.getPickStand());
                }
            } catch (Exception e) {
                // 回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                exceptionCount++;
                log.error("取消拣选任务异常。载具：{}，站台：{}。", thisKeyPickTask.getVehicleId(), thisKeyPickTask.getPickStand());
            }
        }
    }

    /**
     * 取消当前其他站台的任务
     *
     * @param vehicleId 载具号
     * @param standId   站台号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOtherStandPickTasks(String vehicleId, String standId) {
        // 取消这个箱子去其他站台的任务
        List<TAppPickTask> otherStandPickTaskList = appPickTaskService.list(new LambdaQueryWrapper<TAppPickTask>()
                .ne(StringUtils.isNotEmpty(standId), TAppPickTask::getPickStand, standId)
                .eq(TAppPickTask::getVehicleId, vehicleId)
                .ne(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.FOR_IN.getCode()));
        Map<String, WmsPickTask> vehicleStandMap = new HashMap<>();
        for (TAppPickTask otherStandPickTask : otherStandPickTaskList) {
            String key = otherStandPickTask.getVehicleId() + "_" + otherStandPickTask.getPickStand();
            if (vehicleStandMap.containsKey(key)) {
                continue;
            }
            vehicleStandMap.put(key, new WmsPickTask(otherStandPickTask.getPickStand(), otherStandPickTask.getVehicleId()));
        }
        cancelPickTasks(vehicleStandMap, 0, 0, 0);
    }

    /**
     * 释放站台载具
     *
     * @param targetPickTask 目标拣选任务
     * @return 处理结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean releaseStandVehicle(TAppPickTask targetPickTask) { //已到达的拣选任务
        // 判断是否是需要回库
        int router = 0;// 默认不需要回库
//        if (!appPickTaskService.exists(new LambdaQueryWrapper<TAppPickTask>()
//                .eq(TAppPickTask::getVehicleId, targetPickTask.getVehicleId())
//                .ne(TAppPickTask::getPickStand, targetPickTask.getPickStand())
//                .ne(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.FOR_IN.getCode()))) {
//            router = 1;// 需要回库
//        }
        // 只要存在状态大于等于-1，小于等于2的任务就说明不需要回库
        if (!appPickTaskService.exists(new LambdaQueryWrapper<TAppPickTask>()
                .eq(TAppPickTask::getVehicleId, targetPickTask.getVehicleId())
                .between(TAppPickTask::getPickStatus, -1, 2))) {
            router = 1; // 需要回库
        }
        // 需要回库时，需要生成回库任务
        List<TAppPickTaskBak> pickRecords = new ArrayList<>();
        if (router == 1) {
            // 设置这个载具为入库中
            appVehicleService.update(new LambdaUpdateWrapper<TAppVehicle>()
                    .set(TAppVehicle::getVehicleStatus, WmsVehicleStatusEnums.IN.getCode())
                    .eq(TAppVehicle::getVehicleId, targetPickTask.getVehicleId()));
            // 设置这个载具的库存为回库中
            appStockService.update(new LambdaUpdateWrapper<TAppStock>()
                    .set(TAppStock::getStockStatus, WmsStockStatusEnums.BACK.getCode())
                    .eq(TAppStock::getVehicleId, targetPickTask.getVehicleId()));
//            // 查询这个箱子入库用的拣选任务
//            List<TAppPickTask> forInPickTasks = appPickTaskService.list(new LambdaQueryWrapper<TAppPickTask>()
//                    .eq(TAppPickTask::getVehicleId, targetPickTask.getVehicleId())
//                    .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.FOR_IN.getCode()));
            boolean haveForIn = false;// 是否要为了入库不回库
//            for (TAppPickTask forInPickTask : forInPickTasks) {
//                if (!Objects.equals(forInPickTask.getPickStand(), targetPickTask.getPickStand())) {
//                    haveForIn = true;
//                }
//                // 生成记录并删除
//                pickRecords.add(new TAppPickTaskBak(
//                        forInPickTask.getPickId(),
//                        forInPickTask.getPickStand(),
//                        forInPickTask.getVehicleId(),
//                        WmsPickTaskStatusEnum.FOR_IN.getCode(),
//                        forInPickTask.getCreateTime(),
//                        null,
//                        null,
//                        LocalDateTime.now()
//                ));
//            }
            // 没有需要入库的拣选任务
            if (!haveForIn) {
//                // 判断空箱需不需要回库
//                String emptyBack = "0";
//                try {
//                    emptyBack = appCommon.getConfigByKey(AppConfigKeyEnums.EMPTY_BACK.getKey());
//                } catch (Exception e) {
//                    log.error("获取空箱回库配置失败，使用默认值不回库。");
//                }
                // 判断这个箱子是不是空箱需要回库
                if (!stockDataService.isEmptyVehicle(targetPickTask.getVehicleId())
                //        || (stockDataService.isEmptyVehicle(targetPickTask.getVehicleId()) && "1".equals(emptyBack))
                ) {
                    // 生成回库任务
                    TAppTask task = new TAppTask(
                            UUIDUtils.getNewUUID("BACK_"),
                            WmsTaskTypeEnums.IN.getCode(),
                            WmsStackerTaskStatusEnums.JOB.getCode(),
                            1,
                            targetPickTask.getVehicleId(),
                            targetPickTask.getPickStand(),
                            null,
                            null,
                            LocalDateTime.now(),
                            null,
                            AppConstant.EMPTY_GOODS_ID,
                            0,
                            0,
                            "wms_auto",
                            "",
                            targetPickTask.getPickStand(),
                            ""
                    );
                    try {
                        // 保存任务
                        appTaskService.save(task);
                    } catch (Exception e) {
                        log.error("释放站台载具生成回库任务时失败。");
                        return false;
                    }
                }
            }
        } else {
            // 将这个箱子的状态暂存的都设置掉
            appPickTaskService.update(new LambdaUpdateWrapper<TAppPickTask>()
                    .set(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.WAIT.getCode())
                    .eq(TAppPickTask::getVehicleId, targetPickTask.getVehicleId())
                    .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.TEMP.getCode())
            );
            // 将这个载具的库存状态都设置为已出库
            appStockService.update(new LambdaUpdateWrapper<TAppStock>()
                    .set(TAppStock::getStockStatus, WmsStockStatusEnums.OUTED.getCode())
                    .set(TAppStock::getLocationId, "")
                    .eq(TAppStock::getVehicleId, targetPickTask.getVehicleId())
                    .eq(TAppStock::getStockStatus, WmsStockStatusEnums.OUTING.getCode()));
        }
        // 更新拣选任务信息，添加拣选任务记录信息
        pickRecords.add(new TAppPickTaskBak(
                targetPickTask.getPickId(),
                targetPickTask.getPickStand(),
                targetPickTask.getVehicleId(),
                WmsPickTaskStatusEnum.LEAVE.getCode(),
                targetPickTask.getCreateTime(),
                targetPickTask.getSendTime(),
                targetPickTask.getArriveTime(),
                LocalDateTime.now()
        ));
        try {
            appPickTaskBakService.saveBatch(pickRecords);
            // 更新当前载具到达当前点位的拣选任务为已到达
            updateVehicleArriveStatus(targetPickTask);
            // 删除当前载具在当前站台的拣选任务
//            appPickTaskService.remove(new LambdaQueryWrapper<TAppPickTask>()
//                    .eq(TAppPickTask::getVehicleId, targetPickTask.getVehicleId())
//                    .eq(TAppPickTask::getPickStand, targetPickTask.getPickStand())
//                    .eq(TAppPickTask::getPickId, targetPickTask.getPickId())
//            );
            appPickTaskService.removeById(targetPickTask.getPickId());
        } catch (Exception e) {
            log.error("保存拣选任务记录时发生异常。载具号：{}，站台号：{}", targetPickTask.getVehicleId(), targetPickTask.getPickStand());
            return false;
        }
//        try {
//            // 给wcs放行信号
//            BaseWcsApiResponse releaseResult = wcsApiService.releaseBox(new WcsReleaseBoxRequest(targetPickTask.getVehicleId(), targetPickTask.getPickStand(), router));
//            if (releaseResult == null || WcsApiResponseCodeEnums.SUCCESS.getCode() != releaseResult.getCode()) {
//                return false;
//            }
//        } catch (Exception e) {
//            log.error("向wcs传递放行信息异常。");
//            return false;
//        }
        return true;
    }

    /**
     * 更新载具到达状态，防止死锁
     * @param targetPickTask 目标拣选任务
     */
    private void updateVehicleArriveStatus(TAppPickTask targetPickTask) {
        synchronized (targetPickTask.getVehicleId().intern()) {

            // 使用 last() 的方式虽然有效，但推荐使用 MyBatis Plus 内置方法保证兼容性
            LambdaQueryWrapper<TAppPickTask> queryWrapper = new LambdaQueryWrapper<TAppPickTask>()
                    .eq(TAppPickTask::getVehicleId, targetPickTask.getVehicleId())
                    .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.WAIT.getCode());

            // 设置最多查一条记录（替代 last("LIMIT 1")）
            queryWrapper.last("LIMIT 1");

            TAppPickTask waitPickTask = appPickTaskService.getOne(queryWrapper);

            if (waitPickTask == null) {
                log.warn("没有找到符合条件的 WAIT 状态任务。载具号: {}", targetPickTask.getVehicleId());
                return;
            }
            // 更新当前载具到达当前点位的拣选任务为已到达
            appPickTaskService.update(new LambdaUpdateWrapper<TAppPickTask>()
                    .set(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode())
                    .set(TAppPickTask::getArriveTime, LocalDateTime.now())
                    .set(TAppPickTask::getPickStand, targetPickTask.getPickStand())
                    .eq(TAppPickTask::getPickId, waitPickTask.getPickId())
            );
            appPickPlanService.update(new LambdaUpdateWrapper<TAppPickPlan>()
                    .set(TAppPickPlan::getStandId, targetPickTask.getPickStand())
                    .eq(TAppPickPlan::getVehicleId, targetPickTask.getVehicleId())
                    .last("LIMIT 1"));
        }
    }


    /**
     * 获得对应库存的第一条工作
     *
     * @param thisPickTask 站台号
     * @return 工作确认信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public WorkConfirmVo getCurrentStandWork(TAppPickTask thisPickTask) {
        // 站台号和载具号必须输入
        if (thisPickTask == null || StringUtils.isEmpty(thisPickTask.getPickStand()) || StringUtils.isEmpty(thisPickTask.getVehicleId())) {
            return null;
        }
        // 轮询当前站台的拣选计划
        List<TAppPickPlan> pickPlans = appPickPlanService.list(new LambdaQueryWrapper<TAppPickPlan>()
                .eq(TAppPickPlan::getStandId, thisPickTask.getPickStand())
                .eq(TAppPickPlan::getVehicleId, thisPickTask.getVehicleId())
                .eq(TAppPickPlan::getPickType, 1));
        if (pickPlans == null || pickPlans.isEmpty()) {
            return null;
        }
        WorkConfirmVo resultVo = null;
        List<TAppPickPlan> needRemovePlans = new ArrayList<>();
        for (TAppPickPlan pickPlan : pickPlans) {
            // 计划拣选数量
            int planPickQty = pickPlan.getPlanPickQty();
            // 先查询对应的工作存不存在
            TAppWork thisWork = appWorkService.getById(pickPlan.getWorkIndex());
            // 判断这条工作还存在否
            if (thisWork == null) {
                needRemovePlans.add(pickPlan);
                continue;
            }
            // 判断有没有需求
            if (thisWork.getFinishNum() >= thisWork.getNeedNum()) {
                needRemovePlans.add(pickPlan);
                continue;
            }
            // 剩余需求量
            int remainNeedNum = thisWork.getNeedNum() - thisWork.getFinishNum();
            if (remainNeedNum < planPickQty) {
                // 需求不足，将计划拣选数量更新成实际需求数量
                planPickQty = remainNeedNum;
            }
            // 查询这个箱子上库存是否足够
            List<TAppStock> stockList = appStockService.list(new LambdaQueryWrapper<TAppStock>()
                    .eq(TAppStock::getVehicleId, thisPickTask.getVehicleId())
                    .eq(TAppStock::getGoodsId, thisWork.getGoodsId())
                    .gt(TAppStock::getRealNum, 0).orderByAsc(TAppStock::getFirstInTime));
            if (stockList == null || stockList.isEmpty()) {
                needRemovePlans.add(pickPlan);
                continue;
            }
            // 算出库存总量
            int remainSumNum = stockList.stream().mapToInt(TAppStock::getRealNum).sum();
            if (remainSumNum < planPickQty) {
                // 剩余数量不足，计划拣选数量更新成实际剩余数量
                planPickQty = remainSumNum;
            }
            // 命中，开始设置返回数据
            OrderConfirmEntity orderConfirmVo = new OrderConfirmEntity(
                    pickPlan.getWorkIndex(),
                    thisWork.getWorkOrder(),
                    thisWork.getProductId(),
                    thisWork.getSingleProductId(),
                    thisWork.getGoodsId(),
                    thisWork.getBoxNo(),
                    planPickQty,
                    planPickQty,
                    thisWork.getKittingRemark()
            );
            StockConfirmEntity stockConfirmVo = new StockConfirmEntity(
                    pickPlan.getPlanId(),
                    pickPlan.getVehicleId(),
                    pickPlan.getGoodsId(),
                    remainSumNum - planPickQty,
                    remainSumNum - planPickQty,
                    0,
                    "ASRS",
                    stockDataService.getWarningQty(),
                    null,
                    null,
                    null,
                    null,null
            );
            resultVo = new WorkConfirmVo(orderConfirmVo, stockConfirmVo);
            break;
        }
        // 删除不可用拣货计划
        if (!needRemovePlans.isEmpty()) {
            appPickPlanService.removeBatchByIds(needRemovePlans.stream().map(TAppPickPlan::getPlanId).toList());
        }

        return resultVo;
    }

    /**
     * 获取当前站台拣选任务需求
     *
     * @param thisPickTask 拣选任务
     * @return 任务vo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskConfirmVo getCurrentStandTask(TAppPickTask thisPickTask) {
        // 站台号和载具号必须输入
        if (thisPickTask == null || StringUtils.isEmpty(thisPickTask.getPickStand()) || StringUtils.isEmpty(thisPickTask.getVehicleId())) {
            return null;
        }
        // 轮询当前站台的拣选计划
        List<TAppPickPlan> pickPlans = appPickPlanService.list(new LambdaQueryWrapper<TAppPickPlan>()
                .eq(TAppPickPlan::getStandId, thisPickTask.getPickStand())
                .eq(TAppPickPlan::getVehicleId, thisPickTask.getVehicleId())
                .eq(TAppPickPlan::getPickType, 2));
        if (pickPlans == null || pickPlans.isEmpty()) {
            return null;
        }
        TaskConfirmVo resultVo = null;
        List<TAppPickPlan> needRemovePlans = new ArrayList<>();
        for (TAppPickPlan pickPlan : pickPlans) {
            // 计划拣选数量
            int planPickQty = pickPlan.getPlanPickQty();
            // 先查询对应的工作存不存在
            TAppOuts thisOuts = appOutsService.getById(pickPlan.getWorkIndex());
            // 判断这条工作还存在否
            if (thisOuts == null) {
                needRemovePlans.add(pickPlan);
                continue;
            }
            // 判断有没有需求
            if (thisOuts.getPickNum() >= thisOuts.getNeedNum()) {
                needRemovePlans.add(pickPlan);
                continue;
            }
            // 剩余需求量
            int remainNeedNum = thisOuts.getNeedNum() - thisOuts.getPickNum();
            if (remainNeedNum < planPickQty) {
                // 需求不足，将计划拣选数量更新成实际需求数量
                planPickQty = remainNeedNum;
            }
            // 查询这个箱子上库存是否足够
            List<TAppStock> stockList = appStockService.list(new LambdaQueryWrapper<TAppStock>()
                    .eq(TAppStock::getVehicleId, thisPickTask.getVehicleId())
                    .eq(TAppStock::getGoodsId, thisOuts.getGoodsId())
                    .gt(TAppStock::getRealNum, 0).orderByAsc(TAppStock::getFirstInTime));
            if (stockList == null || stockList.isEmpty()) {
                needRemovePlans.add(pickPlan);
                continue;
            }
            // 算出库存总量
            int remainSumNum = stockList.stream().mapToInt(TAppStock::getRealNum).sum();
            if (remainSumNum < planPickQty) {
                // 剩余数量不足，计划拣选数量更新成实际剩余数量
                planPickQty = remainSumNum;
            }
            // 命中，开始设置返回数据
            TaskConfirmEntity taskConfirmVo = new TaskConfirmEntity(
                    thisOuts.getTaskId(),
                    thisOuts.getOutType(),
                    thisOuts.getGoodsId(),
                    thisOuts.getNeedNum(),
                    remainNeedNum,
                    planPickQty,
                    planPickQty,
                    null
            );
            StockConfirmEntity stockConfirmVo = new StockConfirmEntity(
                    pickPlan.getPlanId(),
                    pickPlan.getVehicleId(),
                    pickPlan.getGoodsId(),
                    remainSumNum - planPickQty,
                    remainSumNum - planPickQty,
                    0,
                    "ASRS",
                    stockDataService.getWarningQty(),
                    thisOuts.getWorkOrder(),
                    thisOuts.getSpecialStock() ,
                    thisOuts.getBatchNo(),
                    thisOuts.getSpecialStockNo(),
                    thisOuts.getSpecialStockItemNo()


            );
            resultVo = new TaskConfirmVo(thisPickTask.getPickStand(),false,taskConfirmVo, stockConfirmVo);
            break;
        }
        // 删除不可用拣货计划
        if (!needRemovePlans.isEmpty()) {
            appPickPlanService.removeBatchByIds(needRemovePlans.stream().map(TAppPickPlan::getPlanId).toList());
        }

        return resultVo;
    }

    /**
     * 获取这个载具的盘点确认信息
     * @param vehicleId 载具号
     * @return 盘点确认信息
     */
    @Override
    public InventoryConfirmVo getInventoryConfirm(String vehicleId) {
        // 获取这个箱子的盘点任务
        List<TAppInventory> inventoryList = appInventoryService.list(new LambdaQueryWrapper<TAppInventory>()
                .eq(TAppInventory::getVehicleId, vehicleId));
        if (inventoryList == null || inventoryList.isEmpty()) {
            return null;
        }
        List<String> goodsIds = inventoryList.stream().map(TAppInventory::getGoodsId).distinct().toList();
        // 查询这个箱子的库存信息
        List<TAppStock> stockList = appStockService.list(new LambdaQueryWrapper<TAppStock>()
                .eq(TAppStock::getVehicleId, vehicleId)
                .in(TAppStock::getGoodsId, goodsIds));
        if (stockList == null || stockList.isEmpty()) {
            return null;
        }
        // 将这些库存根据料号Map一下， 并汇总库存数量
        Map<String, Integer> sumNumByGoodsMap = new HashMap<>();
        for (TAppStock stock : stockList) {
            if (sumNumByGoodsMap.containsKey(stock.getGoodsId())) {
                sumNumByGoodsMap.replace(stock.getGoodsId(), sumNumByGoodsMap.get(stock.getGoodsId()) + stock.getRealNum());
            } else {
                sumNumByGoodsMap.put(stock.getGoodsId(), stock.getRealNum());
            }
        }
        List<TAppPickTask> pickTasks = appPickTaskService.list(new LambdaQueryWrapper<TAppPickTask>()
                .eq(TAppPickTask::getVehicleId, vehicleId)
                .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode())
        );
        for (TAppInventory inventory : inventoryList) {
            if (sumNumByGoodsMap.containsKey(inventory.getGoodsId())) {
                // 返回盘点确认信息
                InventoryConfirmVo inventoryConfirmVo = new InventoryConfirmVo();
                inventoryConfirmVo.setInventoryId(inventory.getInventoryId());
                inventoryConfirmVo.setGoodsId(inventory.getGoodsId());
                inventoryConfirmVo.setVehicleId(inventory.getVehicleId());
                inventoryConfirmVo.setStockNum(sumNumByGoodsMap.get(inventory.getGoodsId()));
                inventoryConfirmVo.setConfirmNum(sumNumByGoodsMap.get(inventory.getGoodsId()));
                inventoryConfirmVo.setChildStandId(pickTasks.getFirst().getPickStand());
                inventoryConfirmVo.setSpecialStock(inventory.getSpecialStock());
                inventoryConfirmVo.setSpecialStockNo(inventory.getSpecialStockNo());
                inventoryConfirmVo.setSpecialStockItemNo(inventory.getSpecialStockItemNo());
                inventoryConfirmVo.setBatchNo(inventory.getBatchNo());
                // 返回结果
                return inventoryConfirmVo;
            }
        }
        return null;
    }
}
