package com.wms_main.service.controller.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
//import com.google.common.collect.CompactHashMap;
import com.wms_main.app.AppCommon;
import com.wms_main.constant.AppConstant;
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.WcsStackerTask;
import com.wms_main.model.bo.wms.GoodsInfoForTask;
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.ewm.*;
import com.wms_main.model.dto.request.wcs.WcsBoxArriveRequest;
import com.wms_main.model.dto.request.wcs.WcsTaskResultRequest;
import com.wms_main.model.dto.request.wcs.WcsVehicleInRequest;
import com.wms_main.model.dto.request.wms.*;
import com.wms_main.model.dto.response.ewm.EwmApiBackResponse;
import com.wms_main.model.dto.response.ewm.EwmApiLocalResponse;
import com.wms_main.model.dto.response.ewm.EwmApiStockResponse;
import com.wms_main.model.dto.response.ewm.TaskDetailInfo;
import com.wms_main.model.dto.response.wcs.BaseWcsApiResponse;
import com.wms_main.model.dto.response.wcs.WcsApiResponse;
import com.wms_main.model.dto.response.wms.BaseWmsApiResponse;
import com.wms_main.model.dto.response.wms.WmsApiResponse;
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.ConvertUtils;
import com.wms_main.repository.utils.StringUtils;
import com.wms_main.repository.utils.UUIDUtils;
import com.wms_main.service.api.IEwmApiService;
import com.wms_main.service.business.IConveyTaskService;
import com.wms_main.service.business.IStackerTaskService;
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.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

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

/**
 * 任务控制类 服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class TaskControllerServiceImpl implements ITaskControllerService {
    private final ITAppWcsTaskService appWcsTaskService;// wcs任务服务
    private final ITAppWcsTaskBakService appWcsTaskBakService;// wcs任务备份服务
    private final ITAppTaskService appWmsTaskService;// wms任务服务
    private final IStackerTaskService stackerTaskService;// 堆垛机任务服务
    private final ITAppLocationService appLocationService;// 库位服务
    private final ITAppPickTaskService appPickTaskService;// 拣选任务服务
    private final ITAppVehicleService appVehicleService;// 载具服务
    private final ITAppStockService appStockService;// 库存服务
    private final IConveyTaskService conveyTaskService;// 输送线任务服务
    private final ITAppStandService appStandService;// 站台服务
    private final ITAppOutsService appOutsService;// 出库单服务
    private final ITAppOutsCheckService appOutsCheckService; // 出库单Check服务
    private final IStockDataService stockDataService;// 库存数据服务
    private final ITAppOutsRecordService appOutsRecordService;// 出库单记录服务
    private final ITAppPickPlanService appPickPlanService;// 拣选计划服务
    private final ITAppInventoryService appInventoryService;// 盘点任务服务
    private final ITAppInventoryRecordService appInventoryRecordService;// 盘点记录服务
    private final ITAppWorkService appWorkService;// 工作详情服务
    private final AppCommon appCommon;
    private final IEwmApiService ewmApiService;
    // 在其他依赖注入后面添加
    private final ITempEwmInboundDataService tempEwmInboundDataService;
    private final ITAppStockCompareService appStockCompareService;



    /**
     * 实现
     *
     * @param stockInRequest 请求信息
     * @return 响应结果
     */
    @Override
    //@Transactional(rollbackFor = Exception.class)
    public BaseWmsApiResponse requireStockIn(StockInRequest stockInRequest) {
        // 判断请求信息的正确性。
        if (stockInRequest == null || StringUtils.isEmpty(stockInRequest.getVehicleId())) {
            return BaseWmsApiResponse.error("请求参数不完整，缺少载具号。");
        }
        // 校验当前是否在库
        if (appVehicleService.exists(new LambdaQueryWrapper<TAppVehicle>()
                .eq(TAppVehicle::getVehicleId, stockInRequest.getVehicleId())
                .eq(TAppVehicle::getVehicleStatus, WmsVehicleStatusEnums.ON.getCode()))) {
            return BaseWmsApiResponse.error("当前载具显示已在库中，无法再次入库。");
        }
        // 判断这个箱子是否有其他的wcs任务
        if (appWcsTaskService.exists(new LambdaQueryWrapper<TAppWcsTask>()
                .eq(TAppWcsTask::getVehicleId, stockInRequest.getVehicleId()))) {
            return BaseWmsApiResponse.error("当前载具仍有未完成的WCS任务，无法创建新的入库任务。");
        }
        // 判断这个箱子是否有其他的wms任务
        if (appWmsTaskService.exists(new LambdaQueryWrapper<TAppTask>()
                .eq(TAppTask::getVehicleId, stockInRequest.getVehicleId()))) {
            return BaseWmsApiResponse.error("当前载具仍有未完成的WMS任务，无法创建新的入库任务。");
        }
        // 非空载具入库，但是未包含物料信息，设置为空
        if (!stockInRequest.isEmptyTask() && (stockInRequest.getGoodsInfo() == null || stockInRequest.getGoodsInfo().isEmpty())) {
            stockInRequest.setEmptyTask(true);
        }
        // 空载具入库但是请求包含物料信息，设置为非空
        if (stockInRequest.isEmptyTask() && stockInRequest.getGoodsInfo() != null && !stockInRequest.getGoodsInfo().isEmpty()) {
            stockInRequest.setEmptyTask(false);
        }
        // 判断是否同种类料入库
        String thisTimeInGoodsId = "";// 本次入库物料
        if (stockInRequest.getGoodsInfo() != null && !stockInRequest.getGoodsInfo().isEmpty()) {
            for (GoodsInfoForTask goodsInfoForTask : stockInRequest.getGoodsInfo()) {
                if (StringUtils.isEmpty(thisTimeInGoodsId)) {
                    thisTimeInGoodsId = goodsInfoForTask.getGoodsId();
                } else {
                    if (!thisTimeInGoodsId.equals(goodsInfoForTask.getGoodsId())) {
                        return BaseWmsApiResponse.error("一个载具中只能入一种料。");
                    }
                }
            }
        }
        if (stockInRequest.isEmptyTask()) {
            // 创建空载具入库任务
            TAppTask task = new TAppTask(
                    UUIDUtils.getNewUUID(),
                    WmsTaskTypeEnums.IN.getCode(),
                    WmsStackerTaskStatusEnums.TEMP.getCode(),
                    1,
                    stockInRequest.getVehicleId(),
                    stockInRequest.getOrigin(),
                    null,
                    null,
                    LocalDateTime.now(),
                    null,
                    AppConstant.EMPTY_GOODS_ID,
                    0,
                    0,
                    stockInRequest.getUserName(),
                    "",
                    stockInRequest.getStandId(),
                    ""
            );
            try {
                // 保存任务
                appWmsTaskService.save(task);
            } catch (Exception e) {
                return BaseWmsApiResponse.error("创建空载具入库任务失败。");
            }
        } else {
            // 查询当前载具的库存信息
            List<TAppStock> thisVehicleStocks = appStockService.list(
                    new LambdaQueryWrapper<TAppStock>()
                            .eq(TAppStock::getVehicleId, stockInRequest.getVehicleId()));
            // 判断入库物料是否在库存中
            if (StringUtils.isNotEmpty(thisTimeInGoodsId) && thisVehicleStocks != null && !thisVehicleStocks.isEmpty()) {
                for (TAppStock stock : thisVehicleStocks) {
                    if (!Objects.equals(stock.getGoodsId(), thisTimeInGoodsId)) {
                        return BaseWmsApiResponse.error("当前载具已经绑定其他种类物料。");
                    }
                }
            }
            Map<String, TAppTask> goodsIdTaskMap = new HashMap<>();
            Map<String, TAppGoods> goodsMap = new HashMap<>();
            // 循环物料生成入库任务
            for (GoodsInfoForTask goodsInfoForTask : stockInRequest.getGoodsInfo()) {
                if (goodsIdTaskMap.containsKey(goodsInfoForTask.getGoodsId())) {
                    // 如果同一物料，则数量叠加。
                    TAppTask task = goodsIdTaskMap.get(goodsInfoForTask.getGoodsId());
                    task.setOpNum(task.getOpNum() + goodsInfoForTask.getOpNum());
                    goodsIdTaskMap.replace(goodsInfoForTask.getGoodsId(), task);
                } else {
                    // 判断当前料号是否存在于立库信息中
                    TAppGoods goods = appCommon.getInstantGoodsByGoodsId(goodsInfoForTask.getGoodsId());
                    if (goods == null) {
                        return BaseWmsApiResponse.error("入库物料列表中有物料不在立库维护信息中。物料号：" + goodsInfoForTask.getGoodsId() + "。");
                    }
                    if (!Objects.equals(goods.getPutArea(), "ASRS")) {
                        return BaseWmsApiResponse.error("非库内料不允许入库。物料号：" + goodsInfoForTask.getGoodsId() + "。");
                    }
                    // 创建入库任务
                    TAppTask task = new TAppTask(
                            UUIDUtils.getNewUUID(),
                            WmsTaskTypeEnums.IN.getCode(),
                            WmsStackerTaskStatusEnums.TEMP.getCode(),
                            1,
                            stockInRequest.getVehicleId(),
                            stockInRequest.getOrigin(),
                            null,
                            null,
                            LocalDateTime.now(),
                            null,
                            goodsInfoForTask.getGoodsId(),
                            goodsInfoForTask.getOpNum(),
                            0,
                            stockInRequest.getUserName(),
                            goodsInfoForTask.getRemark(),
                            stockInRequest.getStandId(),
                            goods.getGoodsDescription()
                    );
                    goodsIdTaskMap.put(goodsInfoForTask.getGoodsId(), task);
                    goodsMap.put(goodsInfoForTask.getGoodsId(), goods);
                }
                if (goodsMap.containsKey(goodsInfoForTask.getGoodsId())) {
                    // 判断数量是否超载
                    TAppGoods thisGoods = goodsMap.get(goodsInfoForTask.getGoodsId());
                    int maxQty1Vehicle = thisGoods.getBoxQty() * thisGoods.getMaxBoxNum();
                    int oldStockNum = 0;
                    if (thisVehicleStocks != null && !thisVehicleStocks.isEmpty()) {
                        // 计算出该物料的库存数量
                        oldStockNum = thisVehicleStocks.stream()
                                .filter(stock -> stock.getGoodsId().equals(goodsInfoForTask.getGoodsId()))
                                .mapToInt(TAppStock::getRealNum)
                                .sum();
                    }
                    if (goodsIdTaskMap.get(goodsInfoForTask.getGoodsId()).getOpNum() + oldStockNum > maxQty1Vehicle) {
                        return BaseWmsApiResponse.error("物料号：" + goodsInfoForTask.getGoodsId() + "数量超过阈值" + maxQty1Vehicle + "，不允许入库。");
                    }
                }
            }
            try {
                appWmsTaskService.saveBatch(goodsIdTaskMap.values());
            } catch (Exception e) {
                // 回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return BaseWmsApiResponse.error("创建入库任务失败。");
            }
        }

        return BaseWmsApiResponse.success("生成入库任务成功。");
    }

    /**
     * 请求出库---实现
     *
     * @param stockOutRequest 请求信息
     * @return 处理结果
     */
    @Override
    //@Transactional(rollbackFor = Exception.class)
    public BaseWmsApiResponse requireStockOut(StockOutRequest stockOutRequest) {
        // 保存
        if (stockOutRequest == null  || stockOutRequest.getNeedNum() == null
                || stockOutRequest.getNeedNum() <= 0 || StringUtils.isEmpty(stockOutRequest.getDestination())) {
            return BaseWmsApiResponse.error("请求参数不完整。");
        }
        // 判断终点对不对
        if (!appStandService.exists(new LambdaQueryWrapper<TAppStand>().eq(TAppStand::getStandId, stockOutRequest.getDestination()))) {
            return BaseWmsApiResponse.error("请求的终点站台不存在。");
        }
        // 针对不同的出库类型验证请求
//        if (stockOutRequest.getOutType().equals(WmsOutTypeEnums.EMPTY.getCode())) {
//            // 如果指定了载具号，则验证该载具是否为空载具
//            if (StringUtils.isNotEmpty(stockOutRequest.getVehicleId())) {
//                // 查询这个载具号
//                boolean haveThisEmptyVehicleFlag = appVehicleService.exists(new LambdaQueryWrapper<TAppVehicle>()
//                        .eq(TAppVehicle::getVehicleId, stockOutRequest.getVehicleId())
//                        .eq(TAppVehicle::getVehicleStatus, WmsVehicleStatusEnums.ON.getCode())
//                        .eq(TAppVehicle::getIsEmpty, 1)
//                );
//                if (!haveThisEmptyVehicleFlag) {
//                    return BaseWmsApiResponse.error("请求错误：目标不存在。");
//                }
//            } else {
//                // 判断空载具数量够不够
//                List<TAppVehicle> emptyVehicles = appVehicleService.list(new LambdaQueryWrapper<TAppVehicle>()
//                        .eq(TAppVehicle::getVehicleStatus, WmsVehicleStatusEnums.ON.getCode())
//                        .eq(TAppVehicle::getIsEmpty, 1)
//                );
//                if (emptyVehicles == null || emptyVehicles.isEmpty()) {
//                    return BaseWmsApiResponse.error("请求错误：库内无空箱。");
//                }
//                if (emptyVehicles.size() < stockOutRequest.getNeedNum()) {
//                    return BaseWmsApiResponse.error("请求错误：库内空箱数量" + emptyVehicles.size() + "，小于请求数量" + stockOutRequest.getNeedNum() + "。");
//                }
//            }
        //} else if (stockOutRequest.getOutType().equals(WmsOutTypeEnums.EMERGE.getCode())) {
            if (!appStandService.exists(new LambdaQueryWrapper<TAppStand>().eq(TAppStand::getStandId, stockOutRequest.getDestination())
                    .eq(TAppStand::getStandType, 1))) {
                return BaseWmsApiResponse.error("非拣选站台不允许紧急出库。");
            }
            // 判断理由是否输入
//            if (StringUtils.isEmpty(stockOutRequest.getReason())) {
//                return BaseWmsApiResponse.error("请求错误：紧急出库必须输入原因。");
//            }
            // 判断料号数量是否输入
            if (StringUtils.isEmpty(stockOutRequest.getGoodsId())) {
                return BaseWmsApiResponse.error("请求错误：紧急出库必须输入料号。");
            }
            if (stockOutRequest.getNeedNum() == null || stockOutRequest.getNeedNum() <= 0) {
                return BaseWmsApiResponse.error("请求错误：紧急出库必须输入有效数量。");
            }
            // 判断原因是缺料的时候，需判断工单号是否输入
//            if (stockOutRequest.getReason().contains("缺料") && StringUtils.isEmpty(stockOutRequest.getWorkOrder())) {
//                return BaseWmsApiResponse.error("请求错误：缺料时必须输入工单号。");
//            }
            // 判断请求的料号是不是库外料
//            TAppGoods thisGoods = appCommon.getInstantGoodsByGoodsId(stockOutRequest.getGoodsId());
//            if (thisGoods == null || !thisGoods.getPutArea().contains("ASRS")) {
//                return BaseWmsApiResponse.error("请求错误：库外料或未在系统中维护的料不允许紧急出库。");
//            }
            // 判断库存是否足够
//            List<TAppStock> stockList = appStockService.list(new LambdaQueryWrapper<TAppStock>()
//                    .eq(TAppStock::getGoodsId, stockOutRequest.getGoodsId())
//                    .gt(TAppStock::getRemainNum, 0));

        LambdaQueryWrapper<TAppStock> stockQueryWrapper;
        if (stockOutRequest.getVehicleId() == null || stockOutRequest.getVehicleId().isEmpty()){
            // 判断库存是否足够
            stockQueryWrapper = new LambdaQueryWrapper<TAppStock>()
                    .eq(TAppStock::getGoodsId, stockOutRequest.getGoodsId())
                    .gt(TAppStock::getRemainNum, 0);
        }else {
            stockQueryWrapper = new LambdaQueryWrapper<TAppStock>()
                    .eq(TAppStock::getVehicleId, stockOutRequest.getVehicleId())
                    .eq(TAppStock::getGoodsId, stockOutRequest.getGoodsId())
                    .gt(TAppStock::getRemainNum, 0);
        }


        // 精确匹配特殊属性字段的空值处理
        if (StringUtils.isNotEmpty(stockOutRequest.getSpecialStock())) {
            stockQueryWrapper.eq(TAppStock::getSpecialStock, stockOutRequest.getSpecialStock());
        } else {
            // 当请求字段为空时，匹配数据库中的空值（NULL或空字符串）
            stockQueryWrapper.and(wrapper -> wrapper.isNull(TAppStock::getSpecialStock)
                    .or().eq(TAppStock::getSpecialStock, ""));
        }

        if (StringUtils.isNotEmpty(stockOutRequest.getSpecialStockNo())) {
            stockQueryWrapper.eq(TAppStock::getSpecialStockNo, stockOutRequest.getSpecialStockNo());
        } else {
            // 当请求字段为空时，匹配数据库中的空值（NULL或空字符串）
            stockQueryWrapper.and(wrapper -> wrapper.isNull(TAppStock::getSpecialStockNo)
                    .or().eq(TAppStock::getSpecialStockNo, ""));
        }

        if (StringUtils.isNotEmpty(stockOutRequest.getSpecialStockItemNo())) {
            stockQueryWrapper.eq(TAppStock::getSpecialStockItemNo, stockOutRequest.getSpecialStockItemNo());
        } else {
            // 当请求字段为空时，匹配数据库中的空值（NULL或空字符串）
            stockQueryWrapper.and(wrapper -> wrapper.isNull(TAppStock::getSpecialStockItemNo)
                    .or().eq(TAppStock::getSpecialStockItemNo, ""));
        }

        if (StringUtils.isNotEmpty(stockOutRequest.getBatchNo())) {
            stockQueryWrapper.eq(TAppStock::getBatchNo, stockOutRequest.getBatchNo());
        } else {
            // 当请求字段为空时，匹配数据库中的空值（NULL或空字符串）
            stockQueryWrapper.and(wrapper -> wrapper.isNull(TAppStock::getBatchNo)
                    .or().eq(TAppStock::getBatchNo, ""));
        }

        List<TAppStock> stockList = appStockService.list(stockQueryWrapper);




        // 生成物料数量map
            Map<String, Integer> stockByGoodsMap = new HashMap<>();
            for (TAppStock stock : stockList) {
                if (stockByGoodsMap.containsKey(stock.getGoodsId())) {
                    stockByGoodsMap.replace(stock.getGoodsId(), stockByGoodsMap.get(stock.getGoodsId()) + stock.getRemainNum());
                } else {
                    stockByGoodsMap.put(stock.getGoodsId(), stock.getRemainNum());
                }
            }
            if (!stockByGoodsMap.containsKey(stockOutRequest.getGoodsId())) {
                return BaseWmsApiResponse.error("请求错误：库内无该料库存。");
            }
            if (stockByGoodsMap.get(stockOutRequest.getGoodsId()) < stockOutRequest.getNeedNum()) {
                return BaseWmsApiResponse.error("请求错误：库内该料库存不足，库内数量：" + stockByGoodsMap.get(stockOutRequest.getGoodsId()) + "，需求数量: " + stockOutRequest.getNeedNum() + "。");
            }
//        } else {
//            return BaseWmsApiResponse.error("请求错误：未知的出库类型。");
//        }
        // 添加任务
        TAppOuts task = new TAppOuts(
                UUIDUtils.getNewUUID(),
                stockOutRequest.getGoodsId(),
                stockOutRequest.getVehicleId(),
                stockOutRequest.getNeedNum(),
                0,
                0,
                9,
                stockOutRequest.getDestination(),
                stockOutRequest.getUserName(),
                stockOutRequest.getReason(),
                LocalDateTime.now(),
                stockOutRequest.getWorkOrder(),
                null,
                stockOutRequest.getSpecialStock(),
                stockOutRequest.getSpecialStockNo(),
                stockOutRequest.getSpecialStockItemNo(),
                stockOutRequest.getBatchNo(),
                null,
                 null,null, null,new Date()
        );
        appOutsService.save(task);
        return BaseWmsApiResponse.success("添加出库请求成功。");
    }


    /**
     * 接收ewm系统下发的出库任务---实现
     * @param ewmOutTaskRequest 接收ewm系统下发的出库任务
     * @return 处理结果
     */
    @Override
    public EwmApiBackResponse ewmRequestOutTask(EwmOutTaskRequest ewmOutTaskRequest) {
        // 保存
        if (ewmOutTaskRequest == null  || ewmOutTaskRequest.getTaskDetailInfo() == null
                || ewmOutTaskRequest.getTaskDetailInfo().isEmpty()) {
            return EwmApiBackResponse.error("请求参数不完整。");
        }
        // 查询所有可用的拣选站台
        List<TAppStand> pickStands = appStandService.list(new LambdaQueryWrapper<TAppStand>()
                .eq(TAppStand::getStandType, 1)
                .eq(TAppStand::getStandStatus, WmsUsableStatusEnums.USABLE.getCode()));
        if (pickStands == null || pickStands.isEmpty()) {
            return EwmApiBackResponse.error("系统中没有可用的拣选站台。");
        }

//        List<TAppOuts> ret = appOutsService.list(new LambdaQueryWrapper<TAppOuts>()
//                .eq(TAppOuts::getWorkOrder, ewmOutTaskRequest.getWaveNo())
//        );

        //List<TAppOuts> appOuts = new ArrayList<>();

        for (EwmOutTaskRequest.TaskDetailInfo task : ewmOutTaskRequest.getTaskDetailInfo()){
//            // 判断有没有出库数据相同的，如果有直接在已有的outs上做累加
//            List<TAppOuts> appOuts = appOutsService.list(new LambdaQueryWrapper<TAppOuts>()
//                    .eq(TAppOuts::getWorkOrder, task.getOrderNo())
//                    .eq(TAppOuts::getGoodsId, task.getMatNo())
//                    .eq(TAppOuts::getSpecialStock, task.getSpecialStock())
//                    .eq(TAppOuts::getSpecialStockNo, task.getSpecialStockNo())
//                    .eq(TAppOuts::getSpecialStockItemNo, task.getSpecialStockItemNo())
//                    .eq(TAppOuts::getBatchNo, task.getBatchNo())
//            );
//            if (appOuts != null && !appOuts.isEmpty()){
//                // 更新需求数量
//                TAppOuts existingOuts = appOuts.getFirst();
//                existingOuts.setNeedNum(appOuts.getFirst().getNeedNum() + task.getPickingQty().intValue());
//                appOutsService.updateById(existingOuts);
//            }
            // 判断料号数量是否输入
            if (StringUtils.isEmpty(task.getMatNo())) {
                return EwmApiBackResponse.error("请求错误：拣选出库必须输入料号。");
            }
            if (task.getPickingQty() == null || task.getPickingQty().intValue() <= 0) {
                return EwmApiBackResponse.error("请求错误：紧急出库必须输入有效数量。");
            }
            String targetDestination;
            // 判断
            List<TAppOuts> ret = appOutsService.list(new LambdaQueryWrapper<TAppOuts>()
                    .eq(TAppOuts::getOrderNo, task.getOrderNo())
            );
            //查询是否有orderNo相同的数据
            if(!ret.isEmpty()){
                targetDestination = ret.getFirst().getDestination();
            }else {
                // 使用Stream API直接找出任务数最少的站台
                targetDestination = pickStands.stream()
                        .min(Comparator.comparingInt(stand ->
                                Math.toIntExact(appOutsService.count(new LambdaQueryWrapper<TAppOuts>()
                                        .eq(TAppOuts::getDestination, stand.getStandId())))))
                        .map(TAppStand::getStandId)
                        .orElse(null);
            }
            if (targetDestination == null) {
                return EwmApiBackResponse.error("无法找到合适的站台进行任务分配。");
            }
            // 验证站台是否存在
            if (!appStandService.exists(new LambdaQueryWrapper<TAppStand>().eq(TAppStand::getStandId, targetDestination))) {
                return EwmApiBackResponse.error("请求的终点站台不存在。");
            }
            // 判断库存是否足够
            List<TAppStock> stockList;
            LambdaQueryWrapper<TAppStock> stockQueryWrapper = new LambdaQueryWrapper<TAppStock>()
                    .eq(TAppStock::getGoodsId, task.getMatNo())
                    .gt(TAppStock::getRemainNum, 0);

//            // 判断是否需要精确匹配特殊属性
//            boolean needExactMatch = StringUtils.isNotEmpty(task.getSpecialStock()) ||
//                    StringUtils.isNotEmpty(task.getSpecialStockNo()) ||
//                    StringUtils.isNotEmpty(task.getSpecialStockItemNo()) ||
//                    StringUtils.isNotEmpty(task.getBatchNo());

            // 精确匹配特殊属性 - 必须匹配所有四个字段完全一样，包括空值
            if (StringUtils.isNotEmpty(task.getSpecialStock())) {
                stockQueryWrapper.eq(TAppStock::getSpecialStock, task.getSpecialStock());
            } else {
                // 当请求字段为空时，匹配数据库中的空值（NULL或空字符串）
                stockQueryWrapper.and(wrapper -> wrapper.isNull(TAppStock::getSpecialStock)
                        .or().eq(TAppStock::getSpecialStock, ""));
            }

            if (StringUtils.isNotEmpty(task.getSpecialStockNo())) {
                stockQueryWrapper.eq(TAppStock::getSpecialStockNo, task.getSpecialStockNo());
            } else {
                // 当请求字段为空时，匹配数据库中的空值（NULL或空字符串）
                stockQueryWrapper.and(wrapper -> wrapper.isNull(TAppStock::getSpecialStockNo)
                        .or().eq(TAppStock::getSpecialStockNo, ""));
            }

            if (StringUtils.isNotEmpty(task.getSpecialStockItemNo())) {
                stockQueryWrapper.eq(TAppStock::getSpecialStockItemNo, task.getSpecialStockItemNo());
            } else {
                // 当请求字段为空时，匹配数据库中的空值（NULL或空字符串）
                stockQueryWrapper.and(wrapper -> wrapper.isNull(TAppStock::getSpecialStockItemNo)
                        .or().eq(TAppStock::getSpecialStockItemNo, ""));
            }

            if (StringUtils.isNotEmpty(task.getBatchNo())) {
                stockQueryWrapper.eq(TAppStock::getBatchNo, task.getBatchNo());
            } else {
                // 当请求字段为空时，匹配数据库中的空值（NULL或空字符串）
                stockQueryWrapper.and(wrapper -> wrapper.isNull(TAppStock::getBatchNo)
                        .or().eq(TAppStock::getBatchNo, ""));
            }

            stockList = appStockService.list(stockQueryWrapper);

            // 生成物料数量map
            Map<String, Integer> stockByGoodsMap = new HashMap<>();
            for (TAppStock stock : stockList) {
                if (stockByGoodsMap.containsKey(stock.getGoodsId())) {
                    stockByGoodsMap.replace(stock.getGoodsId(), stockByGoodsMap.get(stock.getGoodsId()) + stock.getRemainNum());
                } else {
                    stockByGoodsMap.put(stock.getGoodsId(), stock.getRemainNum());
                }
            }
            if (!stockByGoodsMap.containsKey(task.getMatNo())) {
                return EwmApiBackResponse.error("请求错误：库内无该料库存: " + task.getMatNo() + "。");
            }
            if (stockByGoodsMap.get(task.getMatNo()) < task.getPickingQty().intValue()) {
                return EwmApiBackResponse.error("请求错误：库内该料库存不足，库内数量：" + stockByGoodsMap.get(task.getMatNo()) + "，需求数量: " + task.getPickingQty().intValue() + "。");
            }
            TAppOuts outs = new TAppOuts(
                    task.getTaskNo(),
                    task.getMatNo(),
                    null,
                    task.getPickingQty().intValue(),
                    0,
                    0,
                    9,
                    targetDestination,
                    "EWM",
                    "SYSTEM",
                    LocalDateTime.now(),
                    task.getRemark(),
                    task.getOrderNo(),
                    task.getSpecialStock(),
                    task.getSpecialStockNo(),
                    task.getSpecialStockItemNo(),
                    task.getBatchNo(),
                    ewmOutTaskRequest.getPickingType(),
                    ewmOutTaskRequest.getWaveNo(),
                    task.getSkuUnit(),
                    task.getSecondPickingKey(),
                    ewmOutTaskRequest.getPickingDate()
            );
            //appOuts.add(outs);
            appOutsService.save(outs);
        }
        return EwmApiBackResponse.success("添加出库请求成功。");
    }


    @Override
    public WmsApiResponse<List<TAppStockCompare>> getCompareData() {
        List<TAppStockCompare> compareData = appStockCompareService.list(new LambdaQueryWrapper<>());
        return WmsApiResponse.success(compareData);
    }

    @Override
    public EwmApiBackResponse cancelOrderInTasks(SendWarehouseInCompletedRequest request) {
        EwmApiBackResponse response = EwmApiBackResponse.success();
        //response.setSuccessful(false);
        response.setMessage("取消入库任务失败：任务已经开始执行，无法取消。");
        response.setState("400");
        return response;
    }



    @Override
    public BaseWmsApiResponse getEwmStock(SendEwmGetStockInformationRequest request) {
        request.setAsrsCode("LASRS");
        // 清除所有旧数据
        appStockCompareService.remove(new LambdaQueryWrapper<>());
        log.info("成功清空库存对比数据表");

        // 从EWM系统获取库存数据
        EwmApiStockResponse ewmStockResponse = ewmApiService.getEwmStock(request);

        // 检查是否成功获取数据
        if (!"successfully".equals(ewmStockResponse.getState())) {
            return WmsApiResponse.error("拉取EWM系统库存数据失败");
        }
        List<EwmApiStockResponse.BinStock> ewmBinStocks = ewmStockResponse.getContent();

        //拉取本地库存数据
        List<TAppStock> localStocks = appStockService.list(new LambdaQueryWrapper<>());

        // 创建一个Map来按照BinStock的关键字段进行分组和汇总
        Map<String, EwmApiStockResponse.BinStock> binStockMap = new HashMap<>();

        // 遍历本地库存数据并按关键字段分组汇总
        for (TAppStock localStock : localStocks) {
            // 构造唯一键，用于识别相同的BinStock记录
            // 关键字段包括: plant, storageBin, matNo, matDesc, specialStock, specialStockNo,
            // specialStockItemNo, batchNo, baseUnit
            //String storageBin = localStock.getLocation(); // 假设库位对应 storageBin
            String matNo = localStock.getGoodsId();
            String matDesc = localStock.getGoodsDesc();
            String specialStock = localStock.getSpecialStock();
            String specialStockNo = localStock.getSpecialStockNo();
            String specialStockItemNo = localStock.getSpecialStockItemNo();
            String batchNo = localStock.getBatchNo();
            String baseUnit = localStock.getSkuUnit();

            // 构造唯一键
            String key = String.join("|",
                    matNo != null ? matNo : "",
                    matDesc != null ? matDesc : "",
                    specialStock != null ? specialStock : "",
                    specialStockNo != null ? specialStockNo : "",
                    specialStockItemNo != null ? specialStockItemNo : "",
                    batchNo != null ? batchNo : "",
                    baseUnit != null ? baseUnit : ""
            );

            // 如果已经存在相同键的记录，则累加数量；否则创建新记录
            if (binStockMap.containsKey(key)) {
                // 累加数量
                EwmApiStockResponse.BinStock existingBinStock = binStockMap.get(key);
                existingBinStock.setTotalQuantity(existingBinStock.getTotalQuantity() + localStock.getRealNum());
            } else {
                // 创建新的BinStock记录
                EwmApiStockResponse.BinStock binStock = new EwmApiStockResponse.BinStock();
                binStock.setMatNo(matNo);
                binStock.setMatDesc(matDesc);
                binStock.setTotalQuantity((double) localStock.getRealNum());
                binStock.setSpecialStock(specialStock);
                binStock.setSpecialStockNo(specialStockNo);
                binStock.setSpecialStockItemNo(specialStockItemNo);
                binStock.setBatchNo(batchNo);
                binStock.setBaseUnit(baseUnit);

                binStockMap.put(key, binStock);
            }
        }

        // 将Map中的值转换为List
        List<EwmApiStockResponse.BinStock> binStocks = new ArrayList<>(binStockMap.values());

        // 开始对比ewmBinStocks 和 binStocks
        // 执行库存对比逻辑
        compareStocks(ewmBinStocks, binStocks);

        // 返回成功响应
        return WmsApiResponse.success("获取并对比库存数据成功");
    }



    /**
     * 对比EWM和本地库存数据
     * @param ewmBinStocks EWM系统库存数据
     * @param localBinStocks 本地WMS系统库存数据
     */
    private void compareStocks(List<EwmApiStockResponse.BinStock> ewmBinStocks, List<EwmApiStockResponse.BinStock> localBinStocks) {
        // 创建Map便于快速查找
        Map<String, EwmApiStockResponse.BinStock> ewmStockMap = new HashMap<>();
        Map<String, EwmApiStockResponse.BinStock> localStockMap = new HashMap<>();

        // 填充EWM库存Map
        for (EwmApiStockResponse.BinStock binStock : ewmBinStocks) {
            String key = generateStockKey(binStock);
            ewmStockMap.put(key, binStock);
        }

        // 填充本地库存Map
        for (EwmApiStockResponse.BinStock binStock : localBinStocks) {
            String key = generateStockKey(binStock);
            localStockMap.put(key, binStock);
        }

        // 存储需要插入数据库的对比结果
        List<TAppStockCompare> compareResults = new ArrayList<>();

        // 1. 查找EWM有但本地没有的记录
        for (String key : ewmStockMap.keySet()) {
            if (!localStockMap.containsKey(key)) {
                EwmApiStockResponse.BinStock ewmStock = ewmStockMap.get(key);
                // 如果EWM数量为0，跳过不记录
                if (ewmStock.getTotalQuantity() == null || ewmStock.getTotalQuantity() <= 0) {
                    continue;
                }
                log.warn("库存不一致 - EWM有但本地没有:  物料={}, 批次={}, 数量={}",
                        ewmStock.getMatNo(),
                        ewmStock.getBatchNo(), ewmStock.getTotalQuantity());
                // 创建对比记录
                TAppStockCompare compareResult = new TAppStockCompare();
                compareResult.setGoodsId(ewmStock.getMatNo());
                compareResult.setGoodsDesc(ewmStock.getMatDesc());
                compareResult.setWmsTotalNum(0);
                compareResult.setEwmTotalNum(ewmStock.getTotalQuantity().intValue());
                compareResult.setSpecialStock(ewmStock.getSpecialStock());
                compareResult.setSpecialStockNo(ewmStock.getSpecialStockNo());
                compareResult.setSpecialStockItemNo(ewmStock.getSpecialStockItemNo());
                compareResult.setBatchNo(ewmStock.getBatchNo());
                compareResult.setCreateTime(LocalDateTime.now());
                compareResult.setCompareStatus(-2); // EWM有WMS没有
                compareResults.add(compareResult);
            }
        }

        // 2. 查找本地有但EWM没有的记录
        for (String key : localStockMap.keySet()) {
            if (!ewmStockMap.containsKey(key)) {
                EwmApiStockResponse.BinStock localStock = localStockMap.get(key);
                log.warn("库存不一致 - 本地有但EWM没有:  物料={}, 批次={}, 数量={}",
                        localStock.getMatNo(),
                        localStock.getBatchNo(), localStock.getTotalQuantity());
                // 创建对比记录
                TAppStockCompare compareResult = new TAppStockCompare();
                compareResult.setGoodsId(localStock.getMatNo());
                compareResult.setGoodsDesc(localStock.getMatDesc());
                compareResult.setWmsTotalNum(localStock.getTotalQuantity().intValue());
                compareResult.setEwmTotalNum(0);
                compareResult.setSpecialStock(localStock.getSpecialStock());
                compareResult.setSpecialStockNo(localStock.getSpecialStockNo());
                compareResult.setSpecialStockItemNo(localStock.getSpecialStockItemNo());
                compareResult.setBatchNo(localStock.getBatchNo());
                compareResult.setCreateTime(LocalDateTime.now());
                compareResult.setCompareStatus(2); // WMS有EWM没有
                compareResults.add(compareResult);
            }
        }

        // 3. 比较都存在的记录的数量差异
        for (String key : ewmStockMap.keySet()) {
            if (localStockMap.containsKey(key)) {
                EwmApiStockResponse.BinStock ewmStock = ewmStockMap.get(key);
                EwmApiStockResponse.BinStock localStock = localStockMap.get(key);

                // 比较数量是否一致（考虑浮点数比较精度）
                if (Math.abs(ewmStock.getTotalQuantity() - localStock.getTotalQuantity()) > 0.001) {
                    log.warn("库存数量不一致:  物料={}, 批次={}, EWM数量={}, 本地数量={}",
                            ewmStock.getMatNo(),
                            ewmStock.getBatchNo(), ewmStock.getTotalQuantity(), localStock.getTotalQuantity());
                    // 创建对比记录
                    TAppStockCompare compareResult = new TAppStockCompare();
                    compareResult.setGoodsId(ewmStock.getMatNo());
                    compareResult.setGoodsDesc(ewmStock.getMatDesc());
                    compareResult.setWmsTotalNum(localStock.getTotalQuantity().intValue());
                    compareResult.setEwmTotalNum(ewmStock.getTotalQuantity().intValue());
                    compareResult.setSpecialStock(ewmStock.getSpecialStock());
                    compareResult.setSpecialStockNo(ewmStock.getSpecialStockNo());
                    compareResult.setSpecialStockItemNo(ewmStock.getSpecialStockItemNo());
                    compareResult.setBatchNo(ewmStock.getBatchNo());
                    compareResult.setCreateTime(LocalDateTime.now());

                    // 设置差异状态
                    int diff = localStock.getTotalQuantity().intValue() - ewmStock.getTotalQuantity().intValue();
                    compareResult.setCompareStatus(diff > 0 ? 1 : -1); // WMS多于EWM 或 EWM多于WMS

                    compareResults.add(compareResult);
                }
            }
        }

        // 将对比结果批量插入数据库
        if (!compareResults.isEmpty()) {
            try {
                appStockCompareService.saveBatch(compareResults);
                log.info("成功插入 {} 条库存对比记录到数据库", compareResults.size());
            } catch (Exception e) {
                log.error("保存库存对比结果到数据库时发生异常", e);
            }
        }
    }

    /**
     * 生成库存记录的唯一键
     * @param binStock 库存记录
     * @return 唯一键
     */
    private String generateStockKey(EwmApiStockResponse.BinStock binStock) {
        return String.join("|",
                binStock.getMatNo() != null ? binStock.getMatNo() : "",
                //binStock.getMatDesc() != null ? binStock.getMatDesc() : "",
                binStock.getSpecialStock() != null ? binStock.getSpecialStock() : "",
                binStock.getSpecialStockNo() != null ? binStock.getSpecialStockNo() : "",
                binStock.getSpecialStockItemNo() != null ? binStock.getSpecialStockItemNo() : "",
                binStock.getBatchNo() != null ? binStock.getBatchNo() : ""
                //binStock.getBaseUnit() != null ? binStock.getBaseUnit() : ""
        );
    }


    /**
     * 入库用出库---实现
     *
     * @param voiRequest 请求信息
     * @return 处理结果
     */
    @Override
    //@Transactional(rollbackFor = Exception.class)
    public BaseWmsApiResponse requireVehiclesForIn(VehicleOutForInRequest voiRequest) {
        // 验证请求正确性
        if (voiRequest == null || voiRequest.getGoodsIds() == null || voiRequest.getGoodsIds().isEmpty()) {
            return WmsApiResponse.error("请求错误：请求信息为空。", null);
        }
        // 结果
        List<TAppOuts> outsList = new ArrayList<>();
        // 筛选出料号
        List<String> distinctGoodsIdList = voiRequest.getGoodsIds().stream().distinct().toList();
        // 获取数据map
        Map<String, Map<String, Integer>> goodsQtyMap = stockDataService.getCanPutGoodsMap(distinctGoodsIdList);
        // 迭代处理需求
        List<String> nonVehicleGoodsIds = new ArrayList<>();
        for (String goodsId : voiRequest.getGoodsIds()) {
            TAppGoods thisGoods = appCommon.getInstantGoodsByGoodsId(goodsId);
            if (thisGoods == null || !thisGoods.getPutArea().contains("ASRS")) {
                nonVehicleGoodsIds.add(goodsId);
                continue;
            }
            // 判断需求是否能满足
            if (!goodsQtyMap.containsKey(goodsId)) {
                nonVehicleGoodsIds.add(goodsId);
                continue;
            }
            Map<String, Integer> qtyByVehicleMap = goodsQtyMap.get(goodsId);
            if (qtyByVehicleMap.isEmpty()) {
                nonVehicleGoodsIds.add(goodsId);
                goodsQtyMap.remove(goodsId);
                continue;
            }
            // 当前料的载具号列表
            List<String> vehicleIdsOfThisGoods = new ArrayList<>(qtyByVehicleMap.keySet());
            for (String vehicleId : vehicleIdsOfThisGoods) {
                qtyByVehicleMap.remove(vehicleId);
                if (qtyByVehicleMap.isEmpty()) {
                    goodsQtyMap.remove(goodsId);
                } else {
                    goodsQtyMap.replace(goodsId, qtyByVehicleMap);
                }
                break;
            }
            // 添加任务
            outsList.add(new TAppOuts(
                    UUIDUtils.getNewUUID(),
                    goodsId,
                    "",
                    1,
                    0,
                    0,
                    WmsOutTypeEnums.FOR_IN.getCode(),
                    "R1",
                    voiRequest.getUserName(),
                    "",
                    LocalDateTime.now(),
                    "",
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,null,
                    null,
                    null
            ));
        }

        if (!outsList.isEmpty()) {
            StringBuilder message = new StringBuilder("以下料号无料箱：\n");
            for (String nonVehicleGoodsId : nonVehicleGoodsIds) {
                message.append(nonVehicleGoodsId).append("；\n");
            }
            appOutsService.saveBatch(outsList);
            return BaseWmsApiResponse.success("添加请求成功。" + message);
        } else {
            return BaseWmsApiResponse.error("符合条件的料号数量为0。");
        }
    }

    /**
     * 实现
     *
     * @param wcsTaskResultRequest 请求信息
     * @return 响应信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseWcsApiResponse sendTaskResult(WcsTaskResultRequest wcsTaskResultRequest) {
        if (StringUtils.isEmpty(wcsTaskResultRequest.getTaskId()) || wcsTaskResultRequest.getTaskStatus() == null) {
            return BaseWcsApiResponse.error("请求缺少关键信息：任务号、任务状态。");
        }
        // 查询对应的wcs任务
        TAppWcsTask wcsTask = appWcsTaskService.getOne(
                new LambdaQueryWrapper<TAppWcsTask>()
                        .eq(TAppWcsTask::getWcsTaskId, wcsTaskResultRequest.getTaskId())
        );
        if (wcsTask == null) {
            return BaseWcsApiResponse.error("未找到对应的wcs任务。");
        }
        // 转换堆垛机任务状态
        int wmsTaskStatus = ConvertUtils.convertWcsStackerTaskStatusToWmsTaskStatus(wcsTaskResultRequest.getTaskStatus());
        if (wmsTaskStatus == -1) {
            return BaseWcsApiResponse.error("反馈的任务状态值无效。");
        }
        // 判断反馈的任务状态是否是「已完成」
        if (Objects.equals(wcsTaskResultRequest.getTaskStatus(), WcsStackerTaskStatusEnums.FINISH.getCode())) {
            // 更新wms任务状态
            appWmsTaskService.update(
                    new LambdaUpdateWrapper<TAppTask>()
                            .set(TAppTask::getTaskStatus, WmsStackerTaskStatusEnums.FINISH.getCode())
                            .set(TAppTask::getFinishTime, LocalDateTime.now())
                            .eq(TAppTask::getWcsTaskId, wcsTaskResultRequest.getTaskId())
            );
            // 移除wcs任务，并向wcs备份表添加记录
            TAppWcsTaskBak wcsTaskBak = new TAppWcsTaskBak(
                    wcsTask.getWcsTaskId(),
                    wcsTask.getWcsTaskStatus(),
                    wcsTask.getWcsTaskType(),
                    wcsTask.getTaskPriority(),
                    wcsTask.getVehicleId(),
                    wcsTask.getOrigin(),
                    wcsTask.getDestination(),
                    wcsTask.getCreateTime(),
                    wcsTask.getSendTime(),
                    wcsTask.getFinishTime(),
                    wcsTask.getRemark()
            );
            appWcsTaskService.removeById(wcsTask.getWcsTaskId());
            appWcsTaskBakService.save(wcsTaskBak);
        } else {
            // 更新wms任务状态
            appWmsTaskService.update(
                    new LambdaUpdateWrapper<TAppTask>()
                            .set(TAppTask::getTaskStatus, wmsTaskStatus)
                            .eq(TAppTask::getWcsTaskId, wcsTaskResultRequest.getTaskId())
            );
            // 更新wcs任务状态
            appWcsTaskService.update(
                    new LambdaUpdateWrapper<TAppWcsTask>()
                            .set(TAppWcsTask::getWcsTaskStatus, wcsTaskResultRequest.getTaskStatus())
                            .eq(TAppWcsTask::getWcsTaskId, wcsTaskResultRequest.getTaskId())
            );
        }
        return BaseWcsApiResponse.success("处理任务状态反馈成功。");
    }

    /**
     * 实现
     * 调用EWM系统获取入库具体信息
     * @param wcsVehicleInRequest 载具请求
     * @return 响应信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public EwmApiLocalResponse ewmInformationBack(WcsVehicleInRequest wcsVehicleInRequest) {
        // 验证请求参数
        if (wcsVehicleInRequest == null || StringUtils.isEmpty(wcsVehicleInRequest.getVehicleNo())) {
            log.warn("请求缺少关键信息：载具号。");
            return EwmApiLocalResponse.error("请求缺少关键信息：载具号。");
        }

        try {
            // 1. 准备请求数据
            SendEwmVehicleForInRequest request = new SendEwmVehicleForInRequest();
            request.setContainerNo(wcsVehicleInRequest.getVehicleNo());

            // 2. 调用EWM系统接口
            EwmApiLocalResponse response = ewmApiService.sendVehicleForIn(request);

            // 3. 记录调用日志
            if (response != null && response.isSuccess()) {
                log.info("成功从EWM系统获取入库信息，载具号: {}, EWM响应: {}",
                        wcsVehicleInRequest.getVehicleNo(), response.getMessage());
            } else {
                log.warn("EWM系统返回失败响应，载具号: {}, 错误信息: {}",
                        wcsVehicleInRequest.getVehicleNo(),
                        response != null ? response.getMessage() : "响应为空");
            }
            saveEwmDataToTempTable(response, wcsVehicleInRequest.getVehicleNo());
            return response;
        } catch (Exception e) {
            // 记录错误日志
            log.error("调用EWM接口异常，载具号: {}", wcsVehicleInRequest.getVehicleNo(), e);
            return EwmApiLocalResponse.error("调用EWM接口失败: " + e.getMessage());
        }
    }

    /**
     * 将EWM返回的数据保存到临时表中
     * @param response EWM接口返回的数据
     * @param vehicleNo 载具号
     */
    private void saveEwmDataToTempTable(EwmApiLocalResponse response, String vehicleNo) {
        if (response == null || response.getContent() == null || response.getContent().toString().isEmpty()) {
            log.warn("EWM返回数据为空或无任务明细，载具号: {}", vehicleNo);
            return;
        }
        try {
            // 先查询要删除的数据
            List<TAppTempEwmInboundData> existingData = tempEwmInboundDataService.list(
                    new LambdaQueryWrapper<TAppTempEwmInboundData>()
                            .eq(TAppTempEwmInboundData::getContainerNo, vehicleNo)
                            .eq(TAppTempEwmInboundData::getProcessStatus, 0)
            );
            log.debug("删除前查询到 {} 条待处理数据，载具号: {}", existingData.size(), vehicleNo);

            // 先删除该载具号之前可能存在的未处理数据
            boolean removeResult = tempEwmInboundDataService.remove(new LambdaQueryWrapper<TAppTempEwmInboundData>()
                    .eq(TAppTempEwmInboundData::getContainerNo, vehicleNo));

            log.info("删除操作结果: {}，载具号: {}，删除条件: containerNo={}, processStatus=0",
                    removeResult, vehicleNo, vehicleNo);

            // 再次查询确认是否删除成功
            List<TAppTempEwmInboundData> afterDeleteData = tempEwmInboundDataService.list(
                    new LambdaQueryWrapper<TAppTempEwmInboundData>()
                            .eq(TAppTempEwmInboundData::getContainerNo, vehicleNo)
                            .eq(TAppTempEwmInboundData::getProcessStatus, 0)
            );
            log.debug("删除后剩余 {} 条待处理数据，载具号: {}", afterDeleteData.size(), vehicleNo);

            // 转换并保存数据
            List<TAppTempEwmInboundData> dataList = new ArrayList<>();
            for (TaskDetailInfo taskDetail : response.getContent().getTaskDetailInfo()) {
                TAppTempEwmInboundData data = new TAppTempEwmInboundData();
                data.setId(UUIDUtils.getNewUUID()); // 不要使用固定值"123"
                data.setBillNo(response.getContent().getBillNo());
                data.setBillType(response.getContent().getBillType());
                data.setContainerNo(response.getContent().getContainerNo() != null ? response.getContent().getContainerNo() : vehicleNo);
                data.setTaskNo(taskDetail.getTaskNo());
                data.setOrderNo(taskDetail.getOrderNo());
                data.setOrderType(taskDetail.getOrderType());
                data.setMatNo(taskDetail.getMatNo());
                data.setMatDesc(taskDetail.getMatDesc());
                data.setSkuQty(taskDetail.getSkuQty());
                data.setSkuUnit(taskDetail.getSkuUnit());
                data.setRemark(taskDetail.getRemark());
                data.setSpecialStock(taskDetail.getSpecialStock());
                data.setSpecialStockNo(taskDetail.getSpecialStockNo());
                data.setSpecialStockItemNo(taskDetail.getSpecialStockItemNo());
                data.setBatchNo(taskDetail.getBatchNo());
                data.setProcessStatus(0); // 待处理状态
                data.setCreateTime(LocalDateTime.now());
                data.setUpdateTime(LocalDateTime.now());
                dataList.add(data);
            }

            if (!dataList.isEmpty()) {
                // 批量插入时指定合理的批次大小
                boolean saveResult = tempEwmInboundDataService.saveBatch(dataList);
                log.info("保存EWM数据结果: {}，载具号: {}，记录数: {}", saveResult, vehicleNo, dataList.size());
            }
        } catch (Exception e) {
            log.error("保存EWM数据到临时表失败，载具号: {}", vehicleNo, e);
            throw e; // 重新抛出异常以便上层处理
        }
    }

    /**
     * 根据临时表数据生成WMS任务
     */
    private void generateWmsTasksFromTempData(WcsVehicleInRequest wcsVehicleInRequest) {
        try {
            // 查询该载具号下所有未处理的临时数据
            List<TAppTempEwmInboundData> tempDataList = tempEwmInboundDataService.list(
                    new LambdaQueryWrapper<TAppTempEwmInboundData>()
                            .eq(TAppTempEwmInboundData::getContainerNo, wcsVehicleInRequest.getVehicleNo())
                            .eq(TAppTempEwmInboundData::getProcessStatus, 0)
            );
            if (tempDataList == null || tempDataList.isEmpty()) {
                log.info("未找到需要处理的临时数据，载具号: {}", wcsVehicleInRequest.getVehicleNo());
                return;
            }
            log.info("开始处理临时数据生成WMS任务，载具号: {}，记录数: {}", wcsVehicleInRequest.getVehicleNo(), tempDataList.size());

            // 生成WMS任务列表
            List<TAppTask> wmsTaskList = new ArrayList<>();

            // 创建入库任务
            TAppTask task = new TAppTask(
                    UUIDUtils.getNewUUID(),
                    WmsTaskTypeEnums.IN.getCode(),                    // 入库任务类型
                    WmsStackerTaskStatusEnums.TEMP.getCode(),         // 初始状态为临时
                    1,                                                // 任务优先级
                    wcsVehicleInRequest.getVehicleNo(),               // 载具号
                    wcsVehicleInRequest.getPoint(),                   // 任务来源
                    null,                                             // 目标库位（后续分配）
                    null,                                             // WCS任务ID（后续生成）
                    LocalDateTime.now(),                              // 创建时间
                    null,                                             // 完成时间
                    tempDataList.getFirst().getMatNo(),               // 物料号
                    null,                                             // 操作数量
                    0,                                                // 已完成数量
                    null,                                             // 用户名/特殊库存标识
                    "EWM入库任务",                                      // 备注
                    "R1",                                             // 默认站台
                    null                                              // 物料描述
            );

            wmsTaskList.add(task);

            // 保存WMS任务
            boolean saveResult = appWmsTaskService.saveBatch(wmsTaskList);
            if (saveResult) {
                log.info("成功生成WMS任务，载具号: {}，任务数: {}", wcsVehicleInRequest.getVehicleNo(), wmsTaskList.size());
            } else {
                log.error("保存WMS任务失败，载具号: {}", wcsVehicleInRequest.getVehicleNo());
                return;
            }

            // 更新临时表中对应记录的状态为已处理

            boolean updateResult = tempEwmInboundDataService.update(
                    new LambdaUpdateWrapper<TAppTempEwmInboundData>()
                            .set(TAppTempEwmInboundData::getProcessStatus, 1)  // 已处理状态
                            .set(TAppTempEwmInboundData::getUpdateTime, LocalDateTime.now())
                            .in(TAppTempEwmInboundData::getContainerNo, wcsVehicleInRequest.getVehicleNo())
            );

            if (updateResult) {
                log.info("成功更新临时数据状态为已处理，载具号: {}", wcsVehicleInRequest.getVehicleNo());
            } else {
                log.error("更新临时数据状态失败，载具号: {}", wcsVehicleInRequest.getVehicleNo());
            }


        } catch (Exception e) {
            log.error("根据临时表数据生成WMS任务时发生异常，载具号: {}", wcsVehicleInRequest.getVehicleNo(), e);
            throw new RuntimeException("生成WMS任务失败: " + e.getMessage(), e);
        }
    }


    /**
     * 实现
     *
     * @param wcsVehicleInRequest 载具请求
     * @return 响应信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public WcsApiResponse<WcsStackerTask> wcsRequestVehicleIn(WcsVehicleInRequest wcsVehicleInRequest) {
        if (StringUtils.isEmpty(wcsVehicleInRequest.getVehicleNo())) {
            return WcsApiResponse.error("请求缺少关键信息：载具号。", null);
        }

        // 0. 验证任务是否已经存在
        List<TAppTask> wmsTaskIsExist = appWmsTaskService.list(
                new LambdaQueryWrapper<TAppTask>()
                        .eq(TAppTask::getVehicleId, wcsVehicleInRequest.getVehicleNo())
                        .eq(TAppTask::getTaskType, WmsTaskTypeEnums.IN.getCode())
        );
        // 1. 验证WCS任务是否已经存在
        List<TAppWcsTask> wcsTaskIsExist = appWcsTaskService.list(
                new LambdaQueryWrapper<TAppWcsTask>()
                        .eq(TAppWcsTask::getVehicleId, wcsVehicleInRequest.getVehicleNo())
                        .eq(TAppWcsTask::getWcsTaskType, WmsTaskTypeEnums.IN.getCode())
        );
        if (!wmsTaskIsExist.isEmpty() && !wcsTaskIsExist.isEmpty()){
            appWcsTaskService.update(new LambdaUpdateWrapper<TAppWcsTask>()
                    .set(TAppWcsTask::getWcsTaskStatus, 0)
                    .eq(TAppWcsTask::getVehicleId, wcsVehicleInRequest.getVehicleNo())
                    .eq(TAppWcsTask::getWcsTaskType, WcsStackerTaskTypeEnums.IN.getCode()));
            return WcsApiResponse.error("该载具号已经存在入库任务，修改wcs状态重新下发。", null);
        }
        if (!wmsTaskIsExist.isEmpty() || !wcsTaskIsExist.isEmpty()){
            return WcsApiResponse.error("该载具号已经存在入库任务，请检查。", null);
        }

        // 1. 获取EWM数据
        EwmApiLocalResponse response = ewmInformationBack(wcsVehicleInRequest);
        if (!response.isSuccess()) {
            return WcsApiResponse.error(response.getMessage(), null);
        }
        try {
            // 2. 将EWM数据保存到临时表
            saveEwmDataToTempTable(response, wcsVehicleInRequest.getVehicleNo());

            // 3. 根据临时表数据生成WMS任务
            generateWmsTasksFromTempData(wcsVehicleInRequest);

        } catch (Exception e) {
            log.error("处理EWM数据异常，载具号: {}", wcsVehicleInRequest.getVehicleNo(), e);
            return WcsApiResponse.error("处理EWM数据失败: " + e.getMessage(), null);
        }


        // 查询该载具对应的wms任务
        List<TAppTask> wmsTasks = appWmsTaskService.list(
                new LambdaQueryWrapper<TAppTask>()
                        .eq(TAppTask::getVehicleId, wcsVehicleInRequest.getVehicleNo())
                        .eq(TAppTask::getTaskType, WmsTaskTypeEnums.IN.getCode())
                        .eq(TAppTask::getTaskStatus, WmsStackerTaskStatusEnums.TEMP.getCode())
        );
        if (wmsTasks == null || wmsTasks.isEmpty()) {
            return WcsApiResponse.error("当前载具不存在任务或者任务已经下发。", null);
        }

        // 查询是否已经有对应wcs任务
        List<TAppWcsTask> wcsTasks = appWcsTaskService.list(
                new LambdaQueryWrapper<TAppWcsTask>()
                        .eq(TAppWcsTask::getVehicleId, wcsVehicleInRequest.getVehicleNo())
                        .eq(TAppWcsTask::getWcsTaskType, WcsStackerTaskTypeEnums.IN.getCode())
                        .ne(TAppWcsTask::getWcsTaskStatus, WcsStackerTaskStatusEnums.FINISH.getCode()));
        if (wcsTasks != null && !wcsTasks.isEmpty()) {
            WcsStackerTask wcsStackerTask = new WcsStackerTask(
                    wcsTasks.getFirst().getWcsTaskId(),
                    wcsTasks.getFirst().getWcsTaskType(),
                    wcsTasks.getFirst().getVehicleId(),
                    wcsTasks.getFirst().getOrigin(),
                    wcsTasks.getFirst().getDestination(),
                    "WMS"
            );
            return WcsApiResponse.success("载具请求入库成功。", wcsStackerTask);
        }
        // 判断是否已经分配库位
        String locationId = "";
        List<String> goodsIds = new ArrayList<>();
        for (TAppTask wmsTask : wmsTasks) {
            if (StringUtils.isNotEmpty(wmsTask.getDestination())) {
                locationId = wmsTask.getDestination();
                break;
            }
            if (!goodsIds.contains(wmsTask.getGoodsId())) {
                goodsIds.add(wmsTask.getGoodsId());
            }
        }
        if (StringUtils.isEmpty(locationId)) {
            // 如果只有一个料号，那么分配优先存放区域
            TAppLocation locationFilter = new TAppLocation();
            if (goodsIds.size() == 1) {
                TAppGoods thisGoods = appCommon.getInstantGoodsByGoodsId(goodsIds.getFirst());
                if (thisGoods != null && StringUtils.isNotEmpty(thisGoods.getPutArea())) {
                    locationFilter.setSubArea(thisGoods.getPutArea());
                }
            }
            // 需要申请库位
            TAppLocation targetLocation = stackerTaskService.requestOneLocation(null, wcsVehicleInRequest.getVehicleNo());
            locationId = targetLocation.getLocationId();
        }
        // 解析wms任务以获得wcs任务
        TAppWcsTask wcsInTask = new TAppWcsTask();
        wcsInTask.setWcsTaskId(UUIDUtils.getNewUUID());
        wcsInTask.setWcsTaskType(WcsStackerTaskTypeEnums.IN.getCode());
        wcsInTask.setWcsTaskStatus(WcsStackerTaskStatusEnums.WAIT.getCode());
        wcsInTask.setTaskPriority(wmsTasks.getFirst().getTaskPriority());
        wcsInTask.setOrigin(wmsTasks.getFirst().getOrigin());
        wcsInTask.setDestination(locationId);
        wcsInTask.setVehicleId(wmsTasks.getFirst().getVehicleId());
        wcsInTask.setCreateTime(LocalDateTime.now());
        wcsInTask.setSendTime(LocalDateTime.now());
        // 实时返回的任务
        WcsStackerTask wcsStackerTask = new WcsStackerTask(
                wcsInTask.getWcsTaskId(),
                wcsInTask.getWcsTaskType(),
                wcsInTask.getVehicleId(),
                wcsInTask.getOrigin(),
                wcsInTask.getDestination(),
                "WMS"
        );
        try {
            // 载具设置状态入库中
            appVehicleService.update(new LambdaUpdateWrapper<TAppVehicle>()
                    .set(TAppVehicle::getVehicleStatus, WmsVehicleStatusEnums.IN.getCode())
                    .eq(TAppVehicle::getVehicleId, wcsVehicleInRequest.getVehicleNo()));
            // 如果有库存的话，更新库存状态为回库中
            appStockService.update(new LambdaUpdateWrapper<TAppStock>()
                    .set(TAppStock::getStockStatus, WmsStockStatusEnums.BACK.getCode())
                    .eq(TAppStock::getVehicleId, wcsVehicleInRequest.getVehicleNo()));
            // 更新wmsTask
            appWmsTaskService.update(
                    new LambdaUpdateWrapper<TAppTask>()
                            .set(TAppTask::getTaskStatus, WmsStackerTaskStatusEnums.SEND.getCode())
                            .set(TAppTask::getWcsTaskId, wcsInTask.getWcsTaskId())
                            .set(TAppTask::getDestination, locationId)
                            .eq(TAppTask::getVehicleId, wcsVehicleInRequest.getVehicleNo())
                            .eq(TAppTask::getTaskType, WmsTaskTypeEnums.IN.getCode())
                            .eq(TAppTask::getTaskStatus, WmsStackerTaskStatusEnums.TEMP.getCode())
            );
            // 存储wcsTask
            appWcsTaskService.save(wcsInTask);
            return WcsApiResponse.success("载具请求入库成功。", wcsStackerTask);
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            // 恢复库位空闲
            appLocationService.update(new LambdaUpdateWrapper<TAppLocation>()
                    .set(TAppLocation::getIsOccupy, 0)
                    .set(TAppLocation::getVehicleId, "")
                    .eq(TAppLocation::getLocationId, locationId));
            return WcsApiResponse.error("载具请求入库发生异常。", null);
        }
    }

    // 无事务的查询方法
    public TAppPickTask findPickTask(String vehicleNo) {
        return appPickTaskService.getOne(new LambdaQueryWrapper<TAppPickTask>()
                .eq(TAppPickTask::getVehicleId, vehicleNo)
                .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.SEND.getCode())
                .orderByDesc(TAppPickTask::getCreateTime)
                .last("LIMIT 1"));
    }


    /**
     * 实现
     *
     * @param boxArriveRequest 请求信息
     * @return 响应信息
     */
    @Override
    //@Transactional(rollbackFor = Exception.class)
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public BaseWcsApiResponse boxArrive(WcsBoxArriveRequest boxArriveRequest) {
        if (boxArriveRequest == null
                || StringUtils.isEmpty(boxArriveRequest.getVehicleNo())
                || StringUtils.isEmpty(boxArriveRequest.getLocation())) {
            return BaseWcsApiResponse.error("请求信息不完整，缺少载具号或者点位。");
        }
        TAppPickTask pickTask = findPickTask(boxArriveRequest.getVehicleNo());

        if (pickTask == null) {
            return BaseWcsApiResponse.error("没有找到当前载具的拣选任务。");
        }

        String pickStand = pickTask.getPickStand();

        // 判断当前站台有没有别的已到达的拣选任务
        List<TAppPickTask> pickTaskList = appPickTaskService.list(new LambdaQueryWrapper<TAppPickTask>()
                .eq(TAppPickTask::getPickStand, boxArriveRequest.getLocation())
                .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode()));

        // 如果有其他已到达的拣选任务，将它们的状态设置为0（等待状态）
        if (pickTaskList != null && !pickTaskList.isEmpty()) {
            for (TAppPickTask otherTask : pickTaskList) {
                appPickTaskService.update(new LambdaUpdateWrapper<TAppPickTask>()
                        .set(TAppPickTask::getPickStatus, 0)  // 设置为等待状态
                        .set(TAppPickTask::getPickId, UUIDUtils.getNewUUID())  // 重新设置ID
                        .eq(TAppPickTask::getPickId, otherTask.getPickId()));
            }
        }
        // 更新当前载具到达当前点位的拣选任务为已到达
        boolean isUpdateSuccess = appPickTaskService.update(new LambdaUpdateWrapper<TAppPickTask>()
                .set(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode())
                .set(TAppPickTask::getArriveTime, LocalDateTime.now())
                .set(TAppPickTask::getPickStand, boxArriveRequest.getLocation())
                .eq(TAppPickTask::getVehicleId, boxArriveRequest.getVehicleNo())
                .gt(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.WAIT.getCode())
                .ne(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.FOR_IN.getCode()));

        // 更新拣选PLAN
        boolean isUpdatePlanSuccess = appPickPlanService.update(new LambdaUpdateWrapper<TAppPickPlan>()
                .set(TAppPickPlan::getStandId, boxArriveRequest.getLocation())
                .eq(TAppPickPlan::getVehicleId, boxArriveRequest.getVehicleNo())
                .eq(TAppPickPlan::getStandId, pickStand)
                .last("LIMIT 1"));

        //boolean isUpdatePlanSuccess = updatePickPlanInNewTransaction(boxArriveRequest, pickStand);

        if (isUpdateSuccess && isUpdatePlanSuccess) {
            // 更新成功，返回成功
            return BaseWcsApiResponse.success("处理成功。");
        } else {
            // 更新失败，返回失败
            return BaseWcsApiResponse.error("处理失败。");
        }
    }


    /**
     * 取消拣选任务实现
     *
     * @param pickTaskRequest 请求信息
     * @return 处理结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseWmsApiResponse cancelPickTasks(PickTaskRequest pickTaskRequest) {
        if (pickTaskRequest == null || pickTaskRequest.getPickTasks() == null || pickTaskRequest.getPickTasks().isEmpty()) {
            // 更新失败，返回失败
            return BaseWmsApiResponse.error("空请求。");
        }
        // 获得需要取消的拣选任务列表
        Map<String, WmsPickTask> vehicleStandMap = new HashMap<>();
        for (WmsPickTask pickTask : pickTaskRequest.getPickTasks()) {
            String key = pickTask.getVehicleId() + "_" + pickTask.getPickStand();
            if (vehicleStandMap.containsKey(key)) {
                continue;
            }
            vehicleStandMap.put(key, pickTask);
        }
        int successCount = 0;
        int failCount = 0;
        int exceptionCount = 0;
        conveyTaskService.cancelPickTasks(vehicleStandMap, successCount, failCount, exceptionCount);
        return BaseWmsApiResponse.success("取消拣选任务成功" + successCount + "条，失败" + failCount + "条，异常" + exceptionCount + "条。");
    }


    /**
     * 获取当前站台任务---实现
     *
     * @param wmsRequest 请求信息
     * @return 获取结果
     */
    @Override
    //@Transactional(rollbackFor = Exception.class)
    public WmsApiResponse<List<TaskConfirmVo>> getCurrentTask(BaseWmsRequest wmsRequest) {
        if (wmsRequest == null || StringUtils.isEmpty(wmsRequest.getStandId())) {
            // 缺少站台号
            return WmsApiResponse.error("请求缺少信息，请输入站台号。", null);
        }
        List<TAppPickTask> pickTasks = new ArrayList<>();
        Map<String, List<String>> standMapping = new HashMap<>();
        standMapping.put("P1", Arrays.asList("P11", "P12", "P13"));
        standMapping.put("P2", Arrays.asList("P14", "P15", "P16"));
        standMapping.put("P3", Arrays.asList("P17", "P18", "P19"));
        standMapping.put("P4", Arrays.asList("P21", "P22", "P23"));

//        if (wmsRequest.getStandId().equals("P1")){
//            // 查询当前站台的拣选任务
//            pickTasks = appPickTaskService.list(new LambdaQueryWrapper<TAppPickTask>()
//                    .in(TAppPickTask::getPickStand, "CK41", "CK42", "CK43")
//                    .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode()));
//        }else if(wmsRequest.getStandId().equals("P2")){
//            pickTasks = appPickTaskService.list(new LambdaQueryWrapper<TAppPickTask>()
//                    .in(TAppPickTask::getPickStand, "CK44", "CK45", "CK46")
//                    .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode()));
//        }else if (wmsRequest.getStandId().equals("P3")){
//            pickTasks = appPickTaskService.list(new LambdaQueryWrapper<TAppPickTask>()
//                    .in(TAppPickTask::getPickStand, "CK47", "CK48", "CK49")
//                    .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode()));
//        }else{
//            return WmsApiResponse.error("当前站台未开放拣选功能。", null);
//        }
        if (standMapping.containsKey(wmsRequest.getStandId())) {
            // 处理母站台情况
            List<String> subStands = standMapping.get(wmsRequest.getStandId());
            for (String subStand : subStands) {
                TAppPickTask task = appPickTaskService.getOne(new LambdaQueryWrapper<TAppPickTask>()
                        .eq(TAppPickTask::getPickStand, subStand)
                        .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode())
                        .last("LIMIT 1"));

                if (task != null) {
                    pickTasks.add(task);
                }
            }
        } else {
            // 处理普通站台情况
            TAppPickTask task = appPickTaskService.getOne(new LambdaQueryWrapper<TAppPickTask>()
                    .eq(TAppPickTask::getPickStand, wmsRequest.getStandId())
                    .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode())
                    .last("LIMIT 1"));

            if (task != null) {
                pickTasks.add(task);
            }
        }
        if (pickTasks.isEmpty()) {
            // 当前站台没有任务
            return WmsApiResponse.error("当前站台没有任务。", null);
        }
        List<TaskConfirmVo> confirmVos = new ArrayList<>();
        for (TAppPickTask pickTask : pickTasks){
            // 查找这个载具对应的库存信息：数量>0
            List<TAppStock> thisVehicleStocks = appStockService.list(new LambdaQueryWrapper<TAppStock>()
                    .eq(TAppStock::getVehicleId, pickTask.getVehicleId())
                    .gt(TAppStock::getRealNum, 0));
            if (thisVehicleStocks == null || thisVehicleStocks.isEmpty()) {
                TaskConfirmVo confirmVo = new TaskConfirmVo(pickTask.getPickStand(), true, null, null);
                confirmVos.add(confirmVo);
            }
            // 判断是否有任务需求
            TaskConfirmVo confirmVo = conveyTaskService.getCurrentStandTask(pickTask);
            if (confirmVo != null) {
                confirmVos.add(confirmVo);
            }else{
                TaskConfirmVo confirmVoTwo = new TaskConfirmVo(pickTask.getPickStand(), true, null, null);
                confirmVos.add(confirmVoTwo);
            }
        }
        return WmsApiResponse.success("获取当前站台任务成功。", confirmVos);
//        TAppPickTask thisStandPickTask = pickTasks.getFirst();
//        // 查找这个载具对应的库存信息：数量>0
//        List<TAppStock> thisVehicleStocks = appStockService.list(new LambdaQueryWrapper<TAppStock>()
//                .eq(TAppStock::getVehicleId, thisStandPickTask.getVehicleId())
//                .gt(TAppStock::getRealNum, 0));
//        if (thisVehicleStocks == null || thisVehicleStocks.isEmpty()) {
//            return WmsApiResponse.instanceOf(WmsApiResponseCodeEnums.WARNING.getCode(), "当前箱子已经是空箱，请直接放行。", null);
//        }
//        // 判断是否有任务需求
//        TaskConfirmVo confirmVo = conveyTaskService.getCurrentStandTask(thisStandPickTask);
//        if (confirmVo != null) {
//            return WmsApiResponse.success("请根据界面提示拣选。", confirmVo);
//        }
//        return WmsApiResponse.instanceOf(WmsApiResponseCodeEnums.WARNING.getCode(), "当前箱子没有拣选需求，请直接放行。", null);
    }

    /**
     * 确认当前站台任务---实现
     *
     * @param confirmTaskRequest 请求信息
     * @return 确认结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseWmsApiResponse confirmCurrentTask(ConfirmTaskRequest confirmTaskRequest) {
        if (confirmTaskRequest == null || StringUtils.isEmpty(confirmTaskRequest.getStandId())) {
            return BaseWmsApiResponse.error("请求缺少信息，请输入站台号。");
        }
        // 查询当前站台上的已到达的拣选任务
        List<TAppPickTask> pickTaskList = appPickTaskService.list(new LambdaQueryWrapper<TAppPickTask>()
                .eq(TAppPickTask::getPickStand, confirmTaskRequest.getStandId())
                .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode())
                .eq(TAppPickTask::getPickType,1)
        );
        if (pickTaskList == null || pickTaskList.isEmpty()) {
            return BaseWmsApiResponse.error("当前站台没有箱子到达, 请检查。");
        }
        if (pickTaskList.size() > 1) {
            return BaseWmsApiResponse.error("当前站台有多个箱子到达，请检查。");
        }

        TAppOuts thisOut = appOutsService.getOne(new LambdaQueryWrapper<TAppOuts>()
                .eq(TAppOuts::getTaskId, confirmTaskRequest.getTaskConfirm().getTaskId()));

        if (thisOut == null) {
            return BaseWmsApiResponse.error("当前任务不存在或已经拣选完毕，请刷新后重试。");
        }

        // 调用EWM系统检验箱子
        SendEwmCheckContainerNo request = new SendEwmCheckContainerNo();
        request.setContainerNo(confirmTaskRequest.getTaskConfirm().getContainerNo());
        request.setType(thisOut.getPickingType());
        request.setFirstOrSecond(false);
        request.setCheckKey(thisOut.getSecondPickingCode());
        EwmApiBackResponse ewmResponse = ewmApiService.sendEwmCheckContainerNo(request);
        // 检查 EWM 系统返回结果
        if (ewmResponse == null) {
            return BaseWmsApiResponse.error("EWM系统无响应，请检查网络连接。");
        }
        // 检查返回内容是否为空
        if (ewmResponse.getContent() == null) {
            // 根据 state 状态处理
            if ("successfully".equals(ewmResponse.getState())) {
                return BaseWmsApiResponse.success("操作成功，但无返回内容。");
            } else {
                return BaseWmsApiResponse.error("EWM系统返回异常：" + (ewmResponse.getMessage() != null ? ewmResponse.getMessage() : "未知错误"));
            }
        }

        // 检测目标箱号是否存在别的物料，以颗粒度为第一优先级，如果颗粒度为空，则使用工单号
        List<TAppOutsCheck> thisOutsChecks = appOutsCheckService.list(new LambdaQueryWrapper<TAppOutsCheck>()
                .eq(TAppOutsCheck::getContainerNo, confirmTaskRequest.getTaskConfirm().getContainerNo()));
        if (thisOutsChecks != null && !thisOutsChecks.isEmpty()) {
            TAppOutsCheck existingCheck = thisOutsChecks.getFirst();

            // 1. 检测是否是颗粒度相同（考虑 null 和 empty）
            String existingSecondPickingCode = existingCheck.getSecondPickingCode();
            String newSecondPickingCode = thisOut.getSecondPickingCode();

            boolean isSecondPickingCodeMatch = (StringUtils.isEmpty(existingSecondPickingCode) && StringUtils.isEmpty(newSecondPickingCode))
                    || Objects.equals(existingSecondPickingCode, newSecondPickingCode);

            if (!isSecondPickingCodeMatch) {
                return BaseWmsApiResponse.error("当前目标箱号已存在其他颗粒度物料，请检查。");
            }

            // 2. 如果颗粒度一致（包括都为空），再检测工单号是否相同
            String existingOrderNo = existingCheck.getOrderNo();
            String newOrderNo = thisOut.getOrderNo();

            boolean isOrderNoMatch = Objects.equals(existingOrderNo, newOrderNo);
            if (!isOrderNoMatch) {
                return BaseWmsApiResponse.error("当前目标箱号已存在其他工单号物料，请检查。");
            }
        }
        // 将出库完成需要反馈的信息插入outsCheck表中
        List<TAppOutsCheck> outsChecks = new ArrayList<>();
        outsChecks.add(new TAppOutsCheck(
                UUIDUtils.getNewUUID("CHECK_"),
                thisOut.getWaveNo(),
                confirmTaskRequest.getTaskConfirm().getTaskId(),
                confirmTaskRequest.getTaskConfirm().getGoodsId(),
                confirmTaskRequest.getTaskConfirm().getTotalNeed(),
                confirmTaskRequest.getTaskConfirm().getRealPickQty(),
                thisOut.getUnit(),
                confirmTaskRequest.getTaskConfirm().getContainerNo(),
                thisOut.getSecondPickingCode(),
                thisOut.getOrderNo()
        ));
        appOutsCheckService.saveBatch(outsChecks);
        // 当前站台到达的拣选任务
        TAppPickTask thisPickTask = pickTaskList.getFirst();
        if (confirmTaskRequest.getTaskConfirm() != null && StringUtils.isNotEmpty(confirmTaskRequest.getTaskConfirm().getTaskId())) {
            // 更新工作信息
            String updateTaskResult = updateTaskInfo(confirmTaskRequest);
            if (StringUtils.isNotEmpty(updateTaskResult)) {
                return BaseWmsApiResponse.error("更新任务信息失败：" + updateTaskResult + "，请重试。");
            }
        }
        // 更新库存信息
        stockDataService.updateStockInfo(confirmTaskRequest.getStockConfirm(), confirmTaskRequest.getStandId(), confirmTaskRequest.getUserName(), "出库拣选", null);
        // 查询库存获得当前载具中存储的库存列表
 //       LambdaQueryWrapper<TAppStock> stockQueryWrapper = new LambdaQueryWrapper<TAppStock>()
//                .eq(TAppStock::getVehicleId, thisPickTask.getVehicleId())
//                .gt(TAppStock::getRealNum, 0);
//        List<TAppStock> stockList = appStockService.list(stockQueryWrapper);
        // 界面直接点击确认/放行
//        if (stockList.isEmpty()) {
//            conveyTaskService.cancelOtherStandPickTasks(thisPickTask.getVehicleId(), thisPickTask.getPickStand());
            // 判断还有没有当前站台的其他拣选任务
//            TaskConfirmVo taskConfirmVo = conveyTaskService.getCurrentStandTask(thisPickTask);
//            if (taskConfirmVo != null) {
//                return BaseWmsApiResponse.warn("当前载具还有其他拣选任务，请根据界面信息进行拣配。");
//            }
//            WorkConfirmVo resultVo = conveyTaskService.getCurrentStandWork(thisPickTask);
//            if (resultVo != null) {
//                return BaseWmsApiResponse.warn("当前载具还有工作，请切换到拣配界面进行拣配。");
//            }
            // 判断当前载具是否还有盘点任务
//            List<String> goodsIds = stockList.stream().map(TAppStock::getGoodsId).distinct().toList();
//            List<TAppInventory> inventoryTasks = appInventoryService.list(new LambdaQueryWrapper<TAppInventory>()
//                    .eq(TAppInventory::getVehicleId, thisPickTask.getVehicleId())
//                    .in(TAppInventory::getGoodsId, goodsIds));
//            if (inventoryTasks != null && !inventoryTasks.isEmpty()) {
//                return BaseWmsApiResponse.warn("当前载具还有盘点任务，请切换到盘点界面进行拣配。");
//            }
//        }
//        else {
//            // 取消后续拣选任务
//            conveyTaskService.cancelOtherStandPickTasks(thisPickTask.getVehicleId(), thisPickTask.getPickStand());
//        }
        // 放行
        if (conveyTaskService.releaseStandVehicle(thisPickTask)) {
            if (appPickTaskService.exists(new LambdaQueryWrapper<TAppPickTask>()
                    .eq(TAppPickTask::getVehicleId, thisPickTask.getVehicleId())
                    .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode())
            )){
                return BaseWmsApiResponse.success("继续拣选");
            }
//            // 回告EWm系统出库完成
//            SendWarehouseOutCompletedRequest request = new SendWarehouseOutCompletedRequest();
//            List<SendWarehouseOutCompletedRequest.PickingDetail> pickingDetails = new ArrayList<>();
//            SendWarehouseOutCompletedRequest.PickingDetail pickingDetail = new SendWarehouseOutCompletedRequest.PickingDetail();
//            pickingDetail.setTaskNo(confirmTaskRequest.getTaskConfirm().getTaskId());
//            pickingDetail.setMatNo(confirmTaskRequest.getTaskConfirm().getGoodsId());
//            pickingDetail.setPickingQty(Double.valueOf(confirmTaskRequest.getTaskConfirm().getTotalNeed()));
//            pickingDetail.setActQty(Double.valueOf(confirmTaskRequest.getTaskConfirm().getRealPickQty()));
//            pickingDetail.setUnit(thisOut.getUnit());
//            pickingDetail.setContainerNo(confirmTaskRequest.getTaskConfirm().getContainerNo());
//            pickingDetails.add(pickingDetail);
//            request.setPickingDetail(pickingDetails);
//            request.setWaveNo(thisOut.getWaveNo());
//            request.setPickingType(thisOut.getPickingType());
//
//            EwmApiBackResponse ewmApiBackResponse = ewmApiService.sendWarehouseOutCompleted(request);
//            if (Objects.equals(ewmApiBackResponse.getState(), "successfully")) {
//                log.info("调用EWM系统接口成功，请求参数: {}", request);
//
//            }else {
//                log.error("调用EWM系统接口异常，请求参数: {}", request);
//                //return BaseWmsApiResponse.error("调用EWM系统接口异常: " + ewmApiBackResponse.getMessage());
//            }
            return BaseWmsApiResponse.success("确认成功。");
        } else {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return BaseWmsApiResponse.error("释放箱子失败。");
        }
    }

    /**
     * 请求盘点---实现
     *
     * @param inventoryRequest 盘点请求
     * @return 请求结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseWmsApiResponse requestInventory(InventoryRequest inventoryRequest) {
        if (inventoryRequest == null) {
            return BaseWmsApiResponse.error("请求为NULL。");
        }
        if (StringUtils.isEmpty(inventoryRequest.getStandId())) {
            return BaseWmsApiResponse.error("请求缺少信息，请输入站台号。");
        }
        if (!appStandService.exists(new LambdaQueryWrapper<TAppStand>().eq(TAppStand::getStandId, inventoryRequest.getStandId())
                .eq(TAppStand::getStandType, 1))) {
            return BaseWmsApiResponse.error("非拣选站台不允许盘点。");
        }
        if (StringUtils.isEmpty(inventoryRequest.getGoodsId())) {
            return BaseWmsApiResponse.error("请求缺少信息，请输入料号。");
        }
        // 判断这个料有没有还没盘点完的任务
        List<TAppInventory> inventoryList = appInventoryService.list(new LambdaQueryWrapper<TAppInventory>()
                .eq(TAppInventory::getGoodsId, inventoryRequest.getGoodsId())
                .and(wrapper -> {
                    // specialStock匹配逻辑
                    if (StringUtils.isEmpty(inventoryRequest.getSpecialStock())) {
                        // 传入空值，匹配数据库中的NULL或空字符串
                        wrapper.isNull(TAppInventory::getSpecialStock)
                                .or()
                                .eq(TAppInventory::getSpecialStock, "");
                    } else {
                        // 传入具体值，精确匹配
                        wrapper.eq(TAppInventory::getSpecialStock, inventoryRequest.getSpecialStock());
                    }
                })
                .and(wrapper -> {
                    // specialStockNo匹配逻辑
                    if (StringUtils.isEmpty(inventoryRequest.getSpecialStockNo())) {
                        // 传入空值，匹配数据库中的NULL或空字符串
                        wrapper.isNull(TAppInventory::getSpecialStockNo)
                                .or()
                                .eq(TAppInventory::getSpecialStockNo, "");
                    } else {
                        // 传入具体值，精确匹配
                        wrapper.eq(TAppInventory::getSpecialStockNo, inventoryRequest.getSpecialStockNo());
                    }
                })
                .and(wrapper -> {
                    // specialStockItemNo匹配逻辑
                    if (StringUtils.isEmpty(inventoryRequest.getSpecialStockItemNo())) {
                        // 传入空值，匹配数据库中的NULL或空字符串
                        wrapper.isNull(TAppInventory::getSpecialStockItemNo)
                                .or()
                                .eq(TAppInventory::getSpecialStockItemNo, "");
                    } else {
                        // 传入具体值，精确匹配
                        wrapper.eq(TAppInventory::getSpecialStockItemNo, inventoryRequest.getSpecialStockItemNo());
                    }
                })
                .and(wrapper -> {
                    // batchNo匹配逻辑
                    if (StringUtils.isEmpty(inventoryRequest.getBatchNo())) {
                        // 传入空值，匹配数据库中的NULL或空字符串
                        wrapper.isNull(TAppInventory::getBatchNo)
                                .or()
                                .eq(TAppInventory::getBatchNo, "");
                    } else {
                        // 传入具体值，精确匹配
                        wrapper.eq(TAppInventory::getBatchNo, inventoryRequest.getBatchNo());
                    }
                })
                .eq(StringUtils.isNotEmpty(inventoryRequest.getVehicleId()), TAppInventory::getVehicleId, inventoryRequest.getVehicleId()));
        if (inventoryList != null && !inventoryList.isEmpty()) {
            String errMsg = StringUtils.isNotEmpty(inventoryRequest.getVehicleId()) ? "载具：" + inventoryRequest.getVehicleId() : "";
            return BaseWmsApiResponse.error(errMsg + "该料号还有盘点任务未完成。");
        }
        // 查询库存，创建盘点任务
        List<TAppStock> stockList = appStockService.list(new LambdaQueryWrapper<TAppStock>()
                .eq(TAppStock::getGoodsId, inventoryRequest.getGoodsId())
                .and(wrapper -> {
                    // specialStock匹配逻辑
                    if (StringUtils.isEmpty(inventoryRequest.getSpecialStock())) {
                        // 传入空值，匹配数据库中的NULL或空字符串
                        wrapper.isNull(TAppStock::getSpecialStock)
                                .or()
                                .eq(TAppStock::getSpecialStock, "");
                    } else {
                        // 传入具体值，精确匹配
                        wrapper.eq(TAppStock::getSpecialStock, inventoryRequest.getSpecialStock());
                    }
                })
                .and(wrapper -> {
                    // specialStockNo匹配逻辑
                    if (StringUtils.isEmpty(inventoryRequest.getSpecialStockNo())) {
                        // 传入空值，匹配数据库中的NULL或空字符串
                        wrapper.isNull(TAppStock::getSpecialStockNo)
                                .or()
                                .eq(TAppStock::getSpecialStockNo, "");
                    } else {
                        // 传入具体值，精确匹配
                        wrapper.eq(TAppStock::getSpecialStockNo, inventoryRequest.getSpecialStockNo());
                    }
                })
                .and(wrapper -> {
                    // specialStockItemNo匹配逻辑
                    if (StringUtils.isEmpty(inventoryRequest.getSpecialStockItemNo())) {
                        // 传入空值，匹配数据库中的NULL或空字符串
                        wrapper.isNull(TAppStock::getSpecialStockItemNo)
                                .or()
                                .eq(TAppStock::getSpecialStockItemNo, "");
                    } else {
                        // 传入具体值，精确匹配
                        wrapper.eq(TAppStock::getSpecialStockItemNo, inventoryRequest.getSpecialStockItemNo());
                    }
                })
                .and(wrapper -> {
                    // batchNo匹配逻辑
                    if (StringUtils.isEmpty(inventoryRequest.getBatchNo())) {
                        // 传入空值，匹配数据库中的NULL或空字符串
                        wrapper.isNull(TAppStock::getBatchNo)
                                .or()
                                .eq(TAppStock::getBatchNo, "");
                    } else {
                        // 传入具体值，精确匹配
                        wrapper.eq(TAppStock::getBatchNo, inventoryRequest.getBatchNo());
                    }
                })
                .eq(StringUtils.isNotEmpty(inventoryRequest.getVehicleId()), TAppStock::getVehicleId, inventoryRequest.getVehicleId()));
        if (stockList == null || stockList.isEmpty()) {
            return BaseWmsApiResponse.error("物料" + inventoryRequest.getGoodsId() + "没有库存。");
        }
        // 根据载具号map一下
        Map<String, TAppInventory> inventoryByVehicleMap = new HashMap<>();
        // 盘点单号
        String orderId = UUIDUtils.getNewUUID();
        for (TAppStock stock : stockList) {
            if (!inventoryByVehicleMap.containsKey(stock.getVehicleId())) {
                // 添加盘点任务
                TAppInventory inventoryTask = new TAppInventory(
                        UUIDUtils.getNewUUID(),
                        inventoryRequest.getGoodsId(),
                        stock.getVehicleId(),
                        null,
                        null,
                        inventoryRequest.getStandId(),
                        inventoryRequest.getUserName(),
                        WmsInvTypeEnums.INV_TYPE_1.getCode(),
                        WmsInvStatusEnums.INIT.getCode(),
                        WmsInvResultEnums.NONE.getCode(),
                        LocalDateTime.now(),
                        null,
                        orderId,
                        inventoryRequest.getSpecialStock(),
                        inventoryRequest.getSpecialStockNo(),
                        inventoryRequest.getSpecialStockItemNo(),
                        inventoryRequest.getBatchNo()
                );
                inventoryByVehicleMap.put(stock.getVehicleId(), inventoryTask);
            }
        }
        if (!inventoryByVehicleMap.isEmpty()) {
            appInventoryService.saveBatch(inventoryByVehicleMap.values());
        }
        // 保存盘点任务
        return BaseWmsApiResponse.success("创建盘点任务成功。");
    }


    /**
     * 查询盘点确认信息
     *
     * @param inventoryConfirmRequest 请求
     * @return 查询结果
     */
    @Override
    public WmsApiResponse<InventoryConfirmVo> getInventoryConfirm(InventoryConfirmRequest inventoryConfirmRequest) {
        // 判断请求是否参数完备
        if (inventoryConfirmRequest == null) {
            return WmsApiResponse.error("请求参数为空。", null);
        }
        if (StringUtils.isEmpty(inventoryConfirmRequest.getStandId())) {
            return WmsApiResponse.error("请求参数缺少站台号。", null);
        }

        // 定义主站台与子站台的映射关系
        Map<String, List<String>> standMapping = new HashMap<>();
        standMapping.put("P1", Arrays.asList("P11", "P12", "P13"));
        standMapping.put("P2", Arrays.asList("P14", "P15", "P16"));
        standMapping.put("P3", Arrays.asList("P17", "P18", "P19"));
        standMapping.put("P4", Arrays.asList("P21", "P22", "P23"));

        List<TAppPickTask> pickTaskList = new ArrayList<>();

        if (standMapping.containsKey(inventoryConfirmRequest.getStandId())) {
            // 处理母站台情况
            List<String> subStands = standMapping.get(inventoryConfirmRequest.getStandId());
            for (String subStand : subStands) {
                TAppPickTask task = appPickTaskService.getOne(new LambdaQueryWrapper<TAppPickTask>()
                        .eq(TAppPickTask::getPickStand, subStand)
                        .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode())
                        .last("LIMIT 1"));

                if (task != null) {
                    pickTaskList.add(task);
                }
            }
        } else {
            // 处理普通站台情况
            TAppPickTask task = appPickTaskService.getOne(new LambdaQueryWrapper<TAppPickTask>()
                    .eq(TAppPickTask::getPickStand, inventoryConfirmRequest.getStandId())
                    .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode())
                    .last("LIMIT 1"));

            if (task != null) {
                pickTaskList.add(task);
            }
        }

        if (pickTaskList.isEmpty()) {
            return WmsApiResponse.error("当前站台没有箱子到达, 请检查。", null);
        }
        if (pickTaskList.size() > 1) {
            return WmsApiResponse.error("当前站台有多个箱子到达，请检查。", null);
        }
        // 获取当前拣选任务
        TAppPickTask thisPickTask = pickTaskList.getFirst();
        InventoryConfirmVo inventoryConfirmVo = conveyTaskService.getInventoryConfirm(thisPickTask.getVehicleId());
        if (inventoryConfirmVo != null) {
            // 返回结果
            return WmsApiResponse.success("查询盘点确认信息成功。", inventoryConfirmVo);
        }
        return WmsApiResponse.instanceOf(WmsApiResponseCodeEnums.WARNING.getCode(), "当前箱子没有要盘点的任务，请放行。", null);
    }

    /**
     * 确认盘点信息
     *
     * @param inventoryConfirmRequest 确认请求
     * @return 处理结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseWmsApiResponse confirmInventory(InventoryConfirmRequest inventoryConfirmRequest) {
        if (inventoryConfirmRequest == null) {
            return BaseWmsApiResponse.error("请求信息为空。");
        }
        if (StringUtils.isEmpty(inventoryConfirmRequest.getStandId())) {
            return BaseWmsApiResponse.error("请求信息缺少站台号。");
        }
        // 查询当前站台上的已到达的拣选任务
        List<TAppPickTask> pickTaskList = appPickTaskService.list(new LambdaQueryWrapper<TAppPickTask>()
                .eq(TAppPickTask::getPickStand, inventoryConfirmRequest.getStandId())
                .eq(TAppPickTask::getPickStatus, WmsPickTaskStatusEnum.ARRIVE.getCode())
                .eq(TAppPickTask::getPickType,2)
        );
        if (pickTaskList == null || pickTaskList.isEmpty()) {
            return BaseWmsApiResponse.error("当前站台没有箱子到达, 请检查。");
        }
        if (pickTaskList.size() > 1) {
            return BaseWmsApiResponse.error("当前站台有多个箱子到达，请检查。");
        }
        // 当前站台到达的拣选任务
        TAppPickTask thisPickTask = pickTaskList.getFirst();
        if (StringUtils.isNotEmpty(inventoryConfirmRequest.getInventoryId())) {
            TAppInventory targetInventory = appInventoryService.getById(inventoryConfirmRequest.getInventoryId());
            if (targetInventory != null) {
                if (!Objects.equals(targetInventory.getVehicleId(), thisPickTask.getVehicleId())) {
                    // 盘点的载具号与当前站台到达的拣选任务载具号不一致，请检查。
                    return BaseWmsApiResponse.error("盘点的载具号与当前站台到达的载具号不一致，请检查。");
                }
                if (inventoryConfirmRequest.getConfirmNum() == null || inventoryConfirmRequest.getConfirmNum() < 0) {
                    return BaseWmsApiResponse.error("请求信息中的盘点确认数量不正确。");
                }
                // 添加盘点记录
                TAppInventoryRecord inventoryRecord = new TAppInventoryRecord();
                inventoryRecord.setInventoryId(inventoryConfirmRequest.getInventoryId());
                inventoryRecord.setGoodsId(targetInventory.getGoodsId());
                inventoryRecord.setVehicleId(targetInventory.getVehicleId());
                // 查询这个载具-料号对应的库存数量
                List<TAppStock> thisVehicleAndGoodsStock = appStockService.list(new LambdaQueryWrapper<TAppStock>()
                        .eq(TAppStock::getVehicleId, targetInventory.getVehicleId())
                        .eq(TAppStock::getGoodsId, targetInventory.getGoodsId()));
                int stockNum = 0;
                if (thisVehicleAndGoodsStock != null && !thisVehicleAndGoodsStock.isEmpty()) {
                    // 获取realNum总和
                    stockNum = thisVehicleAndGoodsStock.stream().mapToInt(TAppStock::getRealNum).sum();
                }
                inventoryRecord.setStockNum(stockNum);
                inventoryRecord.setConfirmNum(inventoryConfirmRequest.getConfirmNum());
                inventoryRecord.setInvStand(inventoryConfirmRequest.getStandId());
                inventoryRecord.setInvUser(inventoryConfirmRequest.getUserName());
                inventoryRecord.setInvType(WmsInvTypeEnums.INV_TYPE_1.getCode());
                inventoryRecord.setInvStatus(WmsInvStatusEnums.CONFIRMED.getCode());
                if (stockNum < inventoryConfirmRequest.getConfirmNum()) {
                    // 盘盈
                    inventoryRecord.setInvResult(WmsInvResultEnums.PLUS.getCode());
                } else if (stockNum == inventoryConfirmRequest.getConfirmNum()) {
                    // 正常
                    inventoryRecord.setInvResult(WmsInvResultEnums.EQUAL.getCode());
                } else {
                    // 盘亏
                    inventoryRecord.setInvResult(WmsInvResultEnums.MINUS.getCode());
                }
                inventoryRecord.setInvCreateTime(targetInventory.getInvCreateTime());
                inventoryRecord.setInvConfirmTime(LocalDateTime.now());
                inventoryRecord.setInvOrderId(targetInventory.getInventoryId());
                appInventoryRecordService.save(inventoryRecord);
                // 移除任务表
                appInventoryService.removeById(inventoryConfirmRequest.getInventoryId());
                // 根据盘点确认信息更新库存
                StockConfirmEntity stockConfirm = new StockConfirmEntity();
                stockConfirm.setVehicleId(targetInventory.getVehicleId());
                stockConfirm.setGoodsId(targetInventory.getGoodsId());
                stockConfirm.setRealRemainQty(inventoryConfirmRequest.getConfirmNum());
                // 更新库存信息
                stockDataService.updateStockInfo(stockConfirm, inventoryConfirmRequest.getStandId(), inventoryConfirmRequest.getUserName(), "盘点确认", targetInventory.getInventoryId());
            } else {
                return BaseWmsApiResponse.error("请求的盘点任务号未查到对应的盘点任务。");
            }
        }
        // 查询库存获得当前载具中存储的库存列表
        LambdaQueryWrapper<TAppStock> stockQueryWrapper = new LambdaQueryWrapper<TAppStock>()
                .eq(TAppStock::getVehicleId, thisPickTask.getVehicleId());
        List<TAppStock> stockList = appStockService.list(stockQueryWrapper);
        // 界面直接点击确认/放行
        if (!stockList.isEmpty()) {
            // 判断是否还有其他盘点任务
            List<TAppInventory> otherInventoryList = appInventoryService.list(new LambdaQueryWrapper<TAppInventory>()
                    .eq(TAppInventory::getVehicleId, thisPickTask.getVehicleId())
                    .ne(TAppInventory::getInventoryId, inventoryConfirmRequest.getInventoryId()));
            if (otherInventoryList != null && !otherInventoryList.isEmpty()) {
                return BaseWmsApiResponse.error("当前载具还有其他的盘点任务，请继续盘点。");
            }
            // 判断还有没有当前站台的其他拣选任务
            TaskConfirmVo taskConfirmVo = conveyTaskService.getCurrentStandTask(thisPickTask);
            if (taskConfirmVo != null) {
                return BaseWmsApiResponse.warn("当前载具还有紧急出库任务，请切换到出库界面信息进行拣配。");
            }
            WorkConfirmVo resultVo = conveyTaskService.getCurrentStandWork(thisPickTask);
            if (resultVo != null) {
                return BaseWmsApiResponse.warn("当前载具还有工作，请切换到拣配界面进行拣配。");
            }
        } else {
            // 取消后续拣选任务
            conveyTaskService.cancelOtherStandPickTasks(thisPickTask.getVehicleId(), thisPickTask.getPickStand());
        }
        // 放行
        if (conveyTaskService.releaseStandVehicle(thisPickTask)) {
            return BaseWmsApiResponse.success("确认成功。");
        } else {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return BaseWmsApiResponse.error("释放箱子失败。");
        }
    }

    /**
     * 获取对应工单对应物料的缺料数量---实现
     * @param goodsId 料号
     * @param workOrder 工单号
     * @return 缺料数量
     */
    @Override
    public int getLackQty(String goodsId, String workOrder) {
        // 判断是否缺少料号和工单
        if (StringUtils.isEmpty(goodsId) || StringUtils.isEmpty(workOrder)) {
            return 0;
        }
        // 查询这个工单里面关于这个工单的缺料
        List<TAppWork> lackWorks = appWorkService.list(new LambdaQueryWrapper<TAppWork>()
                .eq(TAppWork::getWorkOrder, workOrder)
                .eq(TAppWork::getGoodsId, goodsId)
                .eq(TAppWork::getLackStatus, 1)
                .eq(TAppWork::getWorkStatus, 2));
        if (lackWorks == null || lackWorks.isEmpty()) {
            return 0;
        }
        // 计算数量的总数
        int sumLack = lackWorks.stream().mapToInt(work -> {
                    if (work.getFinishNum() < work.getNeedNum()) {
                        // 只有确实缺少数量时，才可以计算缺料数量
                        return work.getNeedNum() - work.getFinishNum();
                    }
                    return 0;
                }).sum();
        // 查询这个物料的库存
        List<TAppStock> thisGoodsStocks = appStockService.list(new LambdaQueryWrapper<TAppStock>()
                .eq(TAppStock::getGoodsId, goodsId));
        if (thisGoodsStocks != null && !thisGoodsStocks.isEmpty()) {
            // 如果库存存在，则取库存数量与需求数量的最小值
            int goodsStockNum = thisGoodsStocks.stream().mapToInt(TAppStock::getRemainNum).sum();
            return Math.min(goodsStockNum, sumLack);
        }
        // 没有库存的情况下，直接返回需求数量
        return sumLack;
    }


    /**
     * 更新出库单信息
     *
     * @param confirmTaskRequest 确认信息
     */
    private String updateTaskInfo(ConfirmTaskRequest confirmTaskRequest) {
        if (confirmTaskRequest == null) {
            return "请求参数为空";
        }
        TaskConfirmEntity taskConfirm = confirmTaskRequest.getTaskConfirm();
        if (taskConfirm == null || StringUtils.isEmpty(taskConfirm.getTaskId())) {
            return "请求参数不全";
        }
        // 查询对应的任务
        TAppOuts outs = appOutsService.getOne(new LambdaQueryWrapper<TAppOuts>()
                .eq(TAppOuts::getTaskId, taskConfirm.getTaskId()));
        if (outs == null || taskConfirm.getRealPickQty() == null) {
            return "未查到对应的任务或者实际拣选数量未填写";
        }
        outs.setPickNum(outs.getPickNum() + taskConfirm.getRealPickQty());
        outs.setUserName(confirmTaskRequest.getUserName());
        if (outs.getPickNum() >= outs.getNeedNum()) {
            // 读取所有wave_no的outs_check表的数据，全部反馈给EWM
            List<TAppOutsCheck> checkList = appOutsCheckService.list(new LambdaQueryWrapper<TAppOutsCheck>()
                    .eq(TAppOutsCheck::getTaskNo, taskConfirm.getTaskId()));

            // 回告EWm系统出库完成
            SendWarehouseOutCompletedRequest request = new SendWarehouseOutCompletedRequest();
            List<SendWarehouseOutCompletedRequest.PickingDetail> pickingDetails = new ArrayList<>();
            for (TAppOutsCheck check : checkList){
                SendWarehouseOutCompletedRequest.PickingDetail pickingDetail = new SendWarehouseOutCompletedRequest.PickingDetail();
                pickingDetail.setTaskNo(check.getTaskNo());
                pickingDetail.setMatNo(check.getMatNo());
                pickingDetail.setPickingQty(Double.valueOf(check.getPickingQty()));
                pickingDetail.setActQty(Double.valueOf(check.getActQty()));
                pickingDetail.setUnit(check.getUnit());
                pickingDetail.setContainerNo(check.getContainerNo());
                pickingDetails.add(pickingDetail);
            }
            request.setPickingDetail(pickingDetails);
            request.setWaveNo(outs.getWaveNo());
            request.setPickingType(outs.getPickingType());
            EwmApiBackResponse ewmApiBackResponse = ewmApiService.sendWarehouseOutCompleted(request);
            if (Objects.equals(ewmApiBackResponse.getState(), "successfully")) {
                log.info("调用EWM系统接口成功，请求参数: {}", request);
                appOutsCheckService.remove(new LambdaQueryWrapper<TAppOutsCheck>()
                        .eq(TAppOutsCheck::getTaskNo, taskConfirm.getTaskId())
                );
            }else {
                log.error("调用EWM系统接口异常，请求参数: {}", request);
                // 触发事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                // 返回错误信息
                return ewmApiBackResponse.toString();

            }

            // 生成记录
            TAppOutsRecord record = new TAppOutsRecord(
                    outs.getTaskId(),
                    outs.getGoodsId(),
                    outs.getVehicleId(),
                    outs.getNeedNum(),
                    outs.getDistributeNum(),
                    outs.getPickNum(),
                    outs.getOutType(),
                    outs.getDestination(),
                    outs.getUserName(),
                    outs.getReason(),
                    outs.getRequestTime(),
                    outs.getWorkOrder()
            );
            // 删除出库单
            appOutsService.removeById(outs.getTaskId());
            // 添加记录
            appOutsRecordService.save(record);
        } else {
            // 更新出库单
            appOutsService.updateById(outs);
        }
        // 判断是否是紧急出库且是缺料
//        if (Objects.equals(outs.getOutType(), WmsOutTypeEnums.EMERGE.getCode())
//                && outs.getReason().contains(EmergencyOutReasonEnums.GOODS_LACK.getReason()) && StringUtils.isNotEmpty(outs.getWorkOrder())) {
//            // 查询此工单下缺料的工作
//            List<TAppWork> lackGoodsWorks = appWorkService.list(new LambdaQueryWrapper<TAppWork>()
//                    .eq(TAppWork::getWorkOrder, outs.getWorkOrder())
//                    .eq(TAppWork::getWorkStatus, 2)
//                    .eq(TAppWork::getLackStatus, 1));
//            int canDistributeNum = taskConfirm.getRealPickQty();
//            List<TAppWork> needUpdateWorks = new ArrayList<>();
//            for (TAppWork lackGoodsWork : lackGoodsWorks) {
//                if (canDistributeNum == 0) {
//                    // 本次拣选数量不够分了
//                    break;
//                }
//                if (lackGoodsWork.getFinishNum() >= lackGoodsWork.getNeedNum()) {
//                    continue;
//                }
//                int remainNeedNum = lackGoodsWork.getNeedNum() - lackGoodsWork.getFinishNum();
//                // 这里需要重新设置完成数量。
//                if (remainNeedNum >= canDistributeNum) {
//                    canDistributeNum = 0;
//                    lackGoodsWork.setFinishNum(lackGoodsWork.getFinishNum() + canDistributeNum);
//                } else {
//                    canDistributeNum -= remainNeedNum;
//                    lackGoodsWork.setFinishNum(lackGoodsWork.getNeedNum());
//                    lackGoodsWork.setLackStatus(0);
//                }
//                needUpdateWorks.add(lackGoodsWork);
//            }
//            appWorkService.updateBatchById(needUpdateWorks);
//        }
        // 清除拣选计划
        LambdaQueryWrapper<TAppPickPlan> pickPlanQueryWrapper = new LambdaQueryWrapper<TAppPickPlan>()
                .eq(TAppPickPlan::getWorkIndex, confirmTaskRequest.getTaskConfirm().getTaskId());
        if (confirmTaskRequest.getStockConfirm() != null && StringUtils.isNotEmpty(confirmTaskRequest.getStockConfirm().getVehicleId())) {
            // 箱号
            pickPlanQueryWrapper.eq(TAppPickPlan::getVehicleId, confirmTaskRequest.getStockConfirm().getVehicleId());
        }
        appPickPlanService.remove(pickPlanQueryWrapper);
        return "";
    }
}
