chen.lin
13 小时以前 7114476c50f620866d81de90b96dbffb38d0d648
rsf-server/src/main/java/com/vincent/rsf/server/manager/service/impl/TaskServiceImpl.java
@@ -19,6 +19,7 @@
import com.vincent.rsf.server.api.service.WcsService;
import com.vincent.rsf.server.common.constant.Constants;
import com.vincent.rsf.server.manager.controller.params.LocToTaskParams;
import com.vincent.rsf.server.manager.controller.params.PakinItem;
import com.vincent.rsf.server.manager.enums.*;
import com.vincent.rsf.framework.common.R;
import com.vincent.rsf.framework.exception.CoolException;
@@ -453,25 +454,21 @@
     * @throws Exception
     */
    @Override
    public void complateInTask(List<Task> tasks) throws Exception {
    public void complateInTask(List<Task> tasks) {
        AtomicBoolean success = new AtomicBoolean(false);
        if (success.compareAndSet(false, true)) {
            Long loginUserId = SystemAuthUtils.getLoginUserId();
            for (Task task : tasks) {
                try {
                    if (task.getTaskType().equals(TaskType.TASK_TYPE_IN.type)) {
                        //1.入库
                        complateInstock(task, loginUserId);
                    } else if (task.getTaskType().equals(TaskType.TASK_TYPE_PICK_IN.type) || task.getTaskType().equals(TaskType.TASK_TYPE_CHECK_IN.type)) {
                        //53.拣料再入库
                        //57.盘点再入库
                        pickComplateInStock(task, loginUserId);
                    } else if (task.getTaskType().equals(TaskType.TASK_TYPE_LOC_MOVE.type)) {
                        //移库
                        moveInStock(task, loginUserId);
                    }
                } catch (Exception ex) {
                    log.error(ex.getMessage(), ex);
                if (task.getTaskType().equals(TaskType.TASK_TYPE_IN.type)) {
                    //1.入库
                    complateInstock(task, loginUserId);
                } else if (task.getTaskType().equals(TaskType.TASK_TYPE_PICK_IN.type) || task.getTaskType().equals(TaskType.TASK_TYPE_CHECK_IN.type)) {
                    //53.拣料再入库
                    //57.盘点再入库
                    pickComplateInStock(task, loginUserId);
                } else if (task.getTaskType().equals(TaskType.TASK_TYPE_LOC_MOVE.type)) {
                    //移库
                    moveInStock(task, loginUserId);
                }
            }
        }
@@ -707,7 +704,7 @@
     * @param loginUserId
     */
    @Transactional(rollbackFor = Exception.class)
    public void pickComplateInStock(Task task, Long loginUserId) throws Exception {
    public void pickComplateInStock(Task task, Long loginUserId) {
        if (Objects.isNull(task)) {
            return;
        }
@@ -746,12 +743,15 @@
                locWorking.setAnfme(taskItem.getAnfme());
            }
            BeanUtils.copyProperties(locWorking, locItem);
            locItem.setWorkQty(0.0).setLocCode(loc.getCode()).setLocId(loc.getId()).setId(null).setUpdateBy(loginUserId).setUpdateTime(new Date());
            items.add(locItem);
            locItem.setWorkQty(0.0).setQty(0.0).setLocCode(loc.getCode()).setLocId(loc.getId()).setId(null).setUpdateBy(loginUserId).setUpdateTime(new Date());
            //数量为零的不入库
            if (locItem.getAnfme().compareTo(0.0) > 0) {
                items.add(locItem);
            }
        }
        if (!locItemService.saveBatch(items)) {
            throw new CoolException("作业库存回写失败!!");
//            throw new CoolException("作业库存回写失败!!");
        }
        TaskItem taskItem = taskItems.stream().findFirst().get();
@@ -777,16 +777,132 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R removeTask(Long[] ids, Long loginUserId) {
        List<Integer> longs = Arrays.asList(TaskStsType.GENERATE_IN.id, TaskStsType.GENERATE_OUT.id);
        // 先查询所有任务(不限制状态),用于检查RCS任务
        List<Integer> list = Arrays.asList(TaskType.TASK_TYPE_IN.type, TaskType.TASK_TYPE_OUT.type, TaskType.TASK_TYPE_PICK_AGAIN_OUT.type,
                TaskType.TASK_TYPE_CHECK_OUT.type, TaskType.TASK_TYPE_EMPITY_IN.type, TaskType.TASK_TYPE_LOC_MOVE.type,
                TaskType.TASK_TYPE_EMPITY_OUT.type, TaskType.TASK_TYPE_MERGE_OUT.type);
        List<Task> allTasks = this.list(new LambdaQueryWrapper<Task>()
                .in(Task::getTaskType, list)
                .in(Task::getId, (Object[]) ids));
        if (allTasks.isEmpty()) {
            throw new CoolException("任务不存在!!");
        }
        // 收集需要取消的RCS任务编号和批次编号(不限制状态,只要已下发到RCS就需要取消)
        List<String> rcsTaskCodes = new ArrayList<>();
        String batchNo = null;
        for (Task task : allTasks) {
            // 判断任务是否已下发到RCS
            // 入库任务:状态 >= WCS_EXECUTE_IN(2) 表示已下发
            // 出库任务:状态 >= WCS_EXECUTE_OUT(102) 表示已下发
            boolean isRcsTask = false;
            if (task.getTaskType() < 100) {
                // 入库任务
                if (task.getTaskStatus() >= TaskStsType.WCS_EXECUTE_IN.id) {
                    isRcsTask = true;
                }
            } else {
                // 出库任务
                if (task.getTaskStatus() >= TaskStsType.WCS_EXECUTE_OUT.id) {
                    isRcsTask = true;
                }
            }
            if (isRcsTask && StringUtils.isNotBlank(task.getTaskCode())) {
                rcsTaskCodes.add(task.getTaskCode());
                // 获取批次编号,优先使用任务的barcode,如果没有则使用任务编号
                if (StringUtils.isBlank(batchNo)) {
                    if (StringUtils.isNotBlank(task.getBarcode())) {
                        batchNo = task.getBarcode();
                    } else if (StringUtils.isNotBlank(task.getTaskCode())) {
                        // 如果任务没有barcode,使用任务编号作为批次编号
                        batchNo = task.getTaskCode();
                    }
                }
                log.info("任务已下发到RCS,需要取消RCS任务 - 任务ID:{},任务编号:{},任务状态:{},托盘码:{}",
                        task.getId(), task.getTaskCode(), task.getTaskStatus(), task.getBarcode());
            }
        }
        // 如果有任务已下发到RCS,先调用RCS取消接口
        boolean rcsCancelSuccess = false;
        if (!rcsTaskCodes.isEmpty()) {
            try {
                log.info("========== 开始取消RCS任务 ==========");
                log.info("需要取消的RCS任务编号:{}", rcsTaskCodes);
                String rcsUrl = rcsApi.getHost() + ":" + rcsApi.getPort() + RcsConstant.cancelTask;
                log.info("RCS取消任务请求地址:{}", rcsUrl);
                // 如果没有批次编号,使用第一个任务编号作为批次编号
                if (StringUtils.isBlank(batchNo) && !rcsTaskCodes.isEmpty()) {
                    batchNo = rcsTaskCodes.get(0);
                }
                Map<String, Object> cancelParams = new HashMap<>();
                cancelParams.put("tasks", rcsTaskCodes);
                if (StringUtils.isNotBlank(batchNo)) {
                    cancelParams.put("batchNo", batchNo);
                }
                log.info("RCS取消任务请求参数:{}", JSONObject.toJSONString(cancelParams));
                HttpHeaders headers = new HttpHeaders();
                headers.add("Content-Type", "application/json");
                headers.add("api-version", "v2.0");
                HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(cancelParams, headers);
                long startTime = System.currentTimeMillis();
                ResponseEntity<String> exchange = restTemplate.exchange(rcsUrl, HttpMethod.POST, httpEntity, String.class);
                long endTime = System.currentTimeMillis();
                log.info("RCS取消任务响应耗时:{}ms", (endTime - startTime));
                log.info("RCS取消任务响应状态码:{}", exchange.getStatusCode());
                log.info("RCS取消任务响应体:{}", exchange.getBody());
                if (Objects.isNull(exchange.getBody())) {
                    log.error("RCS取消任务失败:响应体为空");
                    throw new CoolException("RCS取消任务失败:响应体为空");
                }
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.coercionConfigDefaults()
                        .setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsEmpty);
                CommonResponse result = objectMapper.readValue(exchange.getBody(), CommonResponse.class);
                if (result.getCode() == 200) {
                    log.info("========== RCS任务取消成功 ==========");
                    log.info("成功取消的RCS任务编号:{}", rcsTaskCodes);
                    rcsCancelSuccess = true;
                } else {
                    log.error("RCS取消任务失败:{}", result.getMsg());
                    throw new CoolException("RCS取消任务失败:" + result.getMsg());
                }
            } catch (JsonProcessingException e) {
                log.error("RCS取消任务响应解析失败:{}", e.getMessage(), e);
                throw new CoolException("RCS取消任务响应解析失败:" + e.getMessage());
            } catch (Exception e) {
                log.error("RCS取消任务异常:{}", e.getMessage(), e);
                throw new CoolException("RCS取消任务异常:" + e.getMessage());
            }
        }
        // 查询符合取消条件的任务(状态为1、101、199)
        List<Integer> allowedStatuses = Arrays.asList(TaskStsType.GENERATE_IN.id, TaskStsType.GENERATE_OUT.id, TaskStsType.WAVE_SEED.id);
        List<Task> tasks = this.list(new LambdaQueryWrapper<Task>()
                .in(Task::getTaskType, list)
                .in(Task::getId, ids)
                .in(Task::getTaskStatus, longs));
        if (tasks.isEmpty()) {
                .in(Task::getId, (Object[]) ids)
                .in(Task::getTaskStatus, allowedStatuses));
        // 如果符合取消条件的任务为空,但RCS取消成功,允许继续(可能是任务状态已变更)
        if (tasks.isEmpty() && !rcsCancelSuccess) {
            throw new CoolException("任务已处执行状态不可取消!!");
        }
        // 如果符合取消条件的任务为空,但RCS取消成功,记录日志并返回
        if (tasks.isEmpty() && rcsCancelSuccess) {
            log.warn("WMS内部任务状态不符合取消条件,但RCS任务已成功取消 - 任务ID:{}", Arrays.toString(ids));
            return R.ok("RCS任务已取消,WMS内部任务状态已变更");
        }
        for (Task task : tasks) {
            //取消移库任务
@@ -1020,17 +1136,18 @@
                .setBarcode(task.getBarcode())
                .setTaskStatus(TaskStsType.GENERATE_IN.id);
        TaskInParam param = new TaskInParam();
        param.setSourceStaNo(task.getTargSite())
                .setIoType(type)
                .setLocType1(Integer.parseInt(loc.getType()));
//        TaskInParam param = new TaskInParam();
//        param.setSourceStaNo(task.getTargSite())
//                .setIoType(type)
//                .setLocType1(Integer.parseInt(loc.getType()));
        //获取新库位
        InTaskMsgDto locInfo = wcsService.getLocNo(param);
//        InTaskMsgDto locInfo = wcsService.getLocNo(param);
        if (Objects.isNull(locInfo)) {
            throw new CoolException("获取库位失败!!");
        }
        task.setTargLoc(locInfo.getLocNo())
//        if (Objects.isNull(locInfo)) {
//            throw new CoolException("获取库位失败!!");
//        }
        //希日上报物有情况,不需要获取新库位
        task.setTargLoc(task.getOrgLoc())
                .setOrgSite(task.getTargSite());
        if (!this.updateById(task)) {
@@ -1075,7 +1192,6 @@
            TaskItem taskItem = taskItems.stream().findFirst().get();
            taskItem.setMatnrId(working.getMatnrId())
                    .setMaktx(working.getMaktx())
                    .setMatnrId(working.getMatnrId())
                    .setMatnrCode(working.getMatnrCode())
                    .setSpec(working.getSpec())
                    .setAnfme(working.getAnfme())
@@ -1100,26 +1216,25 @@
        List<LocItemWorking> workings = new ArrayList<>();
        List<TaskItem> items = taskItemService.list(new LambdaQueryWrapper<TaskItem>().eq(TaskItem::getTaskId, task.getId()));
        items.forEach(taskItem -> {
            if (taskItem.getAnfme() > 0) {
                LocItemWorking itemWorking = new LocItemWorking();
                BeanUtils.copyProperties(taskItem, itemWorking);
                itemWorking.setTaskId(task.getId())
                        .setQty(0.0)
                        .setLocId(loc1.getId())
                        .setLocCode(loc1.getCode());
                workings.add(itemWorking);
            }
            LocItemWorking itemWorking = new LocItemWorking();
            BeanUtils.copyProperties(taskItem, itemWorking);
            itemWorking.setTaskId(task.getId())
                    .setQty(0.0)
                    .setLocId(loc1.getId())
                    .setLocCode(loc1.getCode());
            workings.add(itemWorking);
        });
        if (!locItemWorkingService.saveBatch(workings)) {
            throw new CoolException("临时库存更新失败!!");
        if (!workings.isEmpty()) {
            if (!locItemWorkingService.saveBatch(workings)) {
                throw new CoolException("临时库存更新失败!!");
            }
        }
        loc1.setUseStatus(LocStsType.LOC_STS_TYPE_S.type);
        if (!locService.updateById(loc1)) {
            throw new CoolException("库位预约入库失败!!");
        }
        locService.updateById(loc1);
//        if (!locService.updateById(loc1)) {
//            throw new CoolException("库位预约入库失败!!");
//        }
        return task;
    }
@@ -1131,7 +1246,7 @@
     */
    @Synchronized
    @Transactional(rollbackFor = Exception.class)
    public void complateOutStock(Task task, Long loginUserId) throws Exception {
    public void complateOutStock(Task task, Long loginUserId) {
        if (Objects.isNull(task)) {
            throw new CoolException("参数不能为空!!");
        }
@@ -1228,15 +1343,26 @@
                throw new CoolException(e.getMessage());
            }
        }
        /**修改为库位状态为O.空库*/
        if (!locService.update(new LambdaUpdateWrapper<Loc>()
                .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_O.type)
                .set(Loc::getBarcode, null)
                .set(Loc::getUpdateBy, loginUserId)
                .set(Loc::getUpdateTime, new Date())
                .eq(Loc::getId, loc.getId()))) {
            throw new CoolException("库位状态修改失败!!");
        if (task.getTaskType().equals(TaskType.TASK_TYPE_PICK_AGAIN_OUT.type) || task.getTaskType().equals(TaskType.TASK_TYPE_CHECK_OUT.type)) {
            /**修改为库位状态为S.预约入库,保留原有库位*/
            if (!locService.update(new LambdaUpdateWrapper<Loc>()
                    .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_S.type)
                    .set(Loc::getBarcode, null)
                    .set(Loc::getUpdateBy, loginUserId)
                    .set(Loc::getUpdateTime, new Date())
                    .eq(Loc::getId, loc.getId()))) {
                throw new CoolException("库位状态修改失败!!");
            }
        } else {
            /**修改为库位状态为O.空库*/
            if (!locService.update(new LambdaUpdateWrapper<Loc>()
                    .set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_O.type)
                    .set(Loc::getBarcode, null)
                    .set(Loc::getUpdateBy, loginUserId)
                    .set(Loc::getUpdateTime, new Date())
                    .eq(Loc::getId, loc.getId()))) {
                throw new CoolException("库位状态修改失败!!");
            }
        }
        if (!this.update(new LambdaUpdateWrapper<Task>()
@@ -1390,20 +1516,34 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pubTaskToWcs(List<Task> tasks) {
        WcsTaskParams taskParams = new WcsTaskParams();
        List<TaskItemParam> items = new ArrayList<>();
        tasks.forEach(task -> {
        /**任务下发接口*/
        String pubTakUrl = rcsApi.getHost() + ":" + rcsApi.getPort() + RcsConstant.pubTask;
        for (Task task : tasks) {
            WcsTaskParams taskParams = new WcsTaskParams();
            List<TaskItemParam> items = new ArrayList<>();
            // 设置批次编号(使用当前任务的任务编码)
            String batchNo = task.getTaskCode();
            if (StringUtils.isBlank(batchNo)) {
                // 如果任务编号为空,生成一个默认值
                batchNo = "BATCH_" + System.currentTimeMillis();
            }
            taskParams.setBatchNo(batchNo);
            log.info("任务批次编号:{}", batchNo);
            // 构建当前任务的参数
            TaskItemParam itemParam = new TaskItemParam();
            //任务类型,任务编码
            itemParam.setTaskType(RcsTaskType.getTypeDesc(task.getTaskType()))
                    .setSeqNum(task.getTaskCode());
            //主参数
            taskParams.setBatch(task.getBarcode());
            //任务编码(对应seqNum)
            itemParam.setTaskNo(task.getTaskCode());
            itemParam.setPriority(1);
            BasStation station = null;
            if (!task.getTaskType().equals(TaskType.TASK_TYPE_LOC_MOVE.type)) {
                station = basStationService.getOne(new LambdaQueryWrapper<BasStation>().eq(BasStation::getStationName, task.getTargSite()));
                if (Objects.isNull(station)) {
                    throw new CoolException("站点不存在!!");
                    log.error("========== RCS任务下发失败 ==========");
                    log.error("站点不存在!!任务编码:{},目标站点:{}", task.getTaskCode(), task.getTargSite());
                    continue;
                }
            }
@@ -1412,12 +1552,16 @@
                if (task.getTaskType() <= TaskType.TASK_TYPE_CHECK_IN.type && !task.getTaskType().equals(TaskType.TASK_TYPE_LOC_MOVE.type)) {
                    station.setUseStatus(LocStsType.LOC_STS_TYPE_R.type);
                    if (!basStationService.updateById(station)) {
                        throw new CoolException("站点状态更新失败!!");
                        log.error("========== RCS任务下发失败 ==========");
                        log.error("站点状态更新失败!!任务编码:{},站点:{}", task.getTaskCode(), station.getStationName());
                        continue;
                    }
                } else if (task.getTaskType() >= TaskType.TASK_TYPE_OUT.type) {
                    station.setUseStatus(LocStsType.LOC_STS_TYPE_S.type);
                    if (!basStationService.updateById(station)) {
                        throw new CoolException("站点状态更新失败!!");
                        log.error("========== RCS任务下发失败 ==========");
                        log.error("站点状态更新失败!!任务编码:{},站点:{}", task.getTaskCode(), station.getStationName());
                        continue;
                    }
                }
            }
@@ -1440,52 +1584,170 @@
                    || task.getTaskType().equals(TaskType.TASK_TYPE_EMPITY_OUT.type)
                    || task.getTaskType().equals(TaskType.TASK_TYPE_CHECK_OUT.type)
                    || task.getTaskType().equals(TaskType.TASK_TYPE_MERGE_OUT.type)) {
                /**出库参数*/
                itemParam.setOriLoc(task.getOrgLoc())
                        .setDestSta(task.getTargSite());
                /**出库参数 - 需要根据任务明细中的多个库位进行组装*/
                // 查询任务明细
                List<TaskItem> taskItems = taskItemService.list(new LambdaQueryWrapper<TaskItem>().eq(TaskItem::getTaskId, task.getId()));
                if (!taskItems.isEmpty()) {
                    // 通过TaskItem的source字段查询LocItem,获取库位信息
                    Set<String> locCodes = new HashSet<>();
                    Map<String, LocItem> locItemMap = new HashMap<>();
                    for (TaskItem taskItem : taskItems) {
                        if (taskItem.getSource() != null) {
                            // source字段对应LocItem的id
                            LocItem locItem = locItemService.getById(taskItem.getSource());
                            if (locItem != null && StringUtils.isNotBlank(locItem.getLocCode())) {
                                locCodes.add(locItem.getLocCode());
                                locItemMap.put(locItem.getLocCode(), locItem);
                            }
                        }
                    }
                    // 如果通过source没有找到库位,使用Task的orgLoc作为默认值
                    if (locCodes.isEmpty() && StringUtils.isNotBlank(task.getOrgLoc())) {
                        locCodes.add(task.getOrgLoc());
                    }
                    // 为每个不同的库位创建一个TaskItemParam
                    for (String locCode : locCodes) {
                        TaskItemParam outItemParam = new TaskItemParam();
                        outItemParam.setTaskNo(task.getTaskCode());
                        outItemParam.setPriority(1);
                        outItemParam.setOriLoc(locCode);
                        outItemParam.setDestSta(task.getTargSite());
                        if (task.getBarcode() != null) {
                            outItemParam.setZpallet(task.getBarcode());
                        }
                        items.add(outItemParam);
                    }
                    log.info("出库任务包含{}个库位:{}", locCodes.size(), locCodes);
                } else {
                    // 如果没有任务明细,使用Task的orgLoc
                    itemParam.setOriLoc(task.getOrgLoc())
                            .setDestSta(task.getTargSite());
                    items.add(itemParam);
                }
            } else {
                /**站点间移库参数*/
                itemParam.setOriSta(task.getOrgSite()).setDestSta(task.getTargSite());
                BasStation curSta = basStationService.getOne(new LambdaQueryWrapper<BasStation>().eq(BasStation::getStationName, task.getOrgSite()));
                if (Objects.isNull(curSta)) {
                    throw new CoolException("站点不存在!!");
                    log.error("========== RCS任务下发失败 ==========");
                    log.error("站点不存在!!任务编码:{},源站点:{}", task.getTaskCode(), task.getOrgSite());
                    continue;
                }
                if (curSta.getType().equals(StationTypeEnum.STATION_TYPE_NORMAL.type)) {
                    if (!curSta.getUseStatus().equals(LocStsType.LOC_STS_TYPE_F.type)) {
                        throw new CoolException("当前站点不是F.在库状态!!");
                        log.error("========== RCS任务下发失败 ==========");
                        log.error("当前站点不是F.在库状态!!任务编码:{},站点:{},当前状态:{}", task.getTaskCode(), curSta.getStationName(), curSta.getUseStatus());
                        continue;
                    }
                }
                if (station.getType().equals(StationTypeEnum.STATION_TYPE_NORMAL.type)) {
                    if (!station.getUseStatus().equals(LocStsType.LOC_STS_TYPE_O.type)) {
                        throw new CoolException("目标站点不是O.空闲状态!!");
                // 站点间移库需要获取目标站点
                BasStation targetStation = basStationService.getOne(new LambdaQueryWrapper<BasStation>().eq(BasStation::getStationName, task.getTargSite()));
                if (Objects.isNull(targetStation)) {
                    log.error("========== RCS任务下发失败 ==========");
                    log.error("目标站点不存在!!任务编码:{},目标站点:{}", task.getTaskCode(), task.getTargSite());
                    continue;
                }
                if (targetStation.getType().equals(StationTypeEnum.STATION_TYPE_NORMAL.type)) {
                    if (!targetStation.getUseStatus().equals(LocStsType.LOC_STS_TYPE_O.type)) {
                        log.error("========== RCS任务下发失败 ==========");
                        log.error("目标站点不是O.空闲状态!!任务编码:{},站点:{},当前状态:{}", task.getTaskCode(), targetStation.getStationName(), targetStation.getUseStatus());
                        continue;
                    }
                }
            }
            items.add(itemParam);
        });
        taskParams.setTaskList(items);
        /**任务下发接口*/
        String pubTakUrl = rcsApi.getHost() + ":" + rcsApi.getPort() + RcsConstant.pubTask;
        /**RCS基础配置链接*/
        log.info("任务下发,请求地址: {}, 请求参数: {}", pubTakUrl, JSONObject.toJSONString(taskParams));
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("api-version", "v2.0");
        HttpEntity httpEntity = new HttpEntity(taskParams, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(pubTakUrl, HttpMethod.POST, httpEntity, String.class);
        log.info("任务下发后,响应结果: {}", exchange);
        if (Objects.isNull(exchange.getBody())) {
            throw new CoolException("任务下发失败!!");
        } else {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.coercionConfigDefaults()
                        .setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsEmpty);
                CommonResponse result = objectMapper.readValue(exchange.getBody(), CommonResponse.class);
                if (result.getCode() == 200) {
                    tasks.forEach(task -> {
            // 对于非出库任务,添加单个itemParam
            if (!(task.getTaskType().equals(TaskType.TASK_TYPE_OUT.type)
                    || task.getTaskType().equals(TaskType.TASK_TYPE_PICK_AGAIN_OUT.type)
                    || task.getTaskType().equals(TaskType.TASK_TYPE_EMPITY_OUT.type)
                    || task.getTaskType().equals(TaskType.TASK_TYPE_CHECK_OUT.type)
                    || task.getTaskType().equals(TaskType.TASK_TYPE_MERGE_OUT.type))) {
                items.add(itemParam);
            }
            taskParams.setTasks(items);
            // 记录当前任务信息
            log.info("  RCS- 任务编码:{},任务类型:{},源库位:{},目标库位:{},源站点:{},目标站点:{}",
                    task.getTaskCode(), task.getTaskType(), task.getOrgLoc(),
                    task.getTargLoc(), task.getOrgSite(), task.getTargSite());
            log.info("RCS-请求参数:{}", JSONObject.toJSONString(taskParams));
            // 发送当前任务
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json");
            headers.add("api-version", "v2.0");
            HttpEntity httpEntity = new HttpEntity(taskParams, headers);
            /**RCS基础配置链接*/
            log.info("========== 开始下发任务到RCS ==========");
            log.info("请求RCS-地址:{}", pubTakUrl);
            log.info("请求RCS-参数:{}", JSONObject.toJSONString(taskParams));
            long startTime = System.currentTimeMillis();
            ResponseEntity<String> exchange = null;
            try {
                exchange = restTemplate.exchange(pubTakUrl, HttpMethod.POST, httpEntity, String.class);
                long endTime = System.currentTimeMillis();
                log.info("RCS响应耗时:{}ms", (endTime - startTime));
                log.info("RCS响应状态码:{}", exchange.getStatusCode());
                log.info("RCS响应头:{}", exchange.getHeaders());
                log.info("RCS响应体:{}", exchange.getBody());
            } catch (org.springframework.web.client.ResourceAccessException e) {
                long endTime = System.currentTimeMillis();
                log.error("========== RCS任务下发资源访问异常 ==========");
                log.error("请求RCS-资源访问异常(可能包含连接超时),耗时:{}ms,任务编码:{}", (endTime - startTime), task.getTaskCode(), e);
                log.error("请求RCS-请求地址:{}", pubTakUrl);
                log.error("请求RCS-请求参数:{}", JSONObject.toJSONString(taskParams));
                // 检查是否是连接超时异常
                Throwable cause = e.getCause();
                String errorMsg = e.getMessage();
                if (cause instanceof java.net.SocketTimeoutException ||
                    (cause instanceof java.net.ConnectException && cause.getMessage() != null && cause.getMessage().contains("timed out")) ||
                    (errorMsg != null && (errorMsg.contains("Connection timed out") || errorMsg.contains("timed out") || errorMsg.contains("timeout")))) {
                    log.error("RCS连接超时,任务下发失败!任务编码:{},错误信息:{}", task.getTaskCode(), errorMsg);
                } else {
                    log.error("RCS资源访问异常,任务下发失败!任务编码:{},错误信息:{}", task.getTaskCode(), errorMsg);
                }
                continue;
            } catch (Exception e) {
                long endTime = System.currentTimeMillis();
                log.error("========== RCS任务下发异常 ==========");
                log.error("请求RCS-异常,耗时:{}ms,任务编码:{}", (endTime - startTime), task.getTaskCode(), e);
                log.error("请求RCS-地址:{}", pubTakUrl);
                log.error("请求RCS-参数:{}", JSONObject.toJSONString(taskParams));
                String errorMsg = e.getMessage();
                // 检查是否是连接超时相关的异常
                if (errorMsg != null && (errorMsg.contains("Connection timed out") || errorMsg.contains("timed out") || errorMsg.contains("timeout"))) {
                    log.error("RCS连接超时,任务下发失败!任务编码:{},错误信息:{}", task.getTaskCode(), errorMsg);
                } else {
                    log.error("RCS任务下发异常!任务编码:{},错误信息:{}", task.getTaskCode(), errorMsg);
                }
                continue;
            }
            if (Objects.isNull(exchange) || Objects.isNull(exchange.getBody())) {
                log.error("========== RCS任务下发失败 ==========");
                log.error("请求RCS-RCS响应体为空,无法解析响应结果");
                log.error("请求RCS-地址:{}", pubTakUrl);
                log.error("请求RCS-参数:{}", JSONObject.toJSONString(taskParams));
                log.error("请求RCS-失败的任务编码:{}", task.getTaskCode());
                log.error("任务下发失败,RCS响应体为空!!任务编码:{}", task.getTaskCode());
                continue;
            } else {
                try {
                    ObjectMapper objectMapper = new ObjectMapper();
                    objectMapper.coercionConfigDefaults()
                            .setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsEmpty);
                    CommonResponse result = objectMapper.readValue(exchange.getBody(), CommonResponse.class);
                    log.info("RCS响应解析结果 - code:{},msg:{},data:{}",
                            result.getCode(), result.getMsg(), result.getData());
                    if (result.getCode() == 200) {
                        log.info("RCS任务下发成功,开始更新任务状态 - 任务编码:{}", task.getTaskCode());
                        if (task.getTaskType().equals(TaskType.TASK_TYPE_IN.type)
                                || task.getTaskType().equals(TaskType.TASK_TYPE_PICK_IN.type)
                                || task.getTaskType().equals(TaskType.TASK_TYPE_CHECK_IN.type)
@@ -1495,20 +1757,28 @@
                            BasStation curSta = basStationService.getOne(new LambdaQueryWrapper<BasStation>().eq(BasStation::getStationName, task.getOrgSite()));
                            if (Objects.isNull(curSta)) {
                                throw new CoolException("站点不存在!!");
                                log.error("========== RCS任务下发失败 ==========");
                                log.error("站点不存在!!任务编码:{},源站点:{}", task.getTaskCode(), task.getOrgSite());
                                continue;
                            }
                            log.info("更新入库任务状态 - 任务编码:{},新状态:{}", task.getTaskCode(), TaskStsType.WCS_EXECUTE_IN.id);
                            if (!taskService.update(new LambdaUpdateWrapper<Task>().eq(Task::getTaskCode, task.getTaskCode())
                                    .set(Task::getTaskStatus, TaskStsType.WCS_EXECUTE_IN.id))) {
                                throw new CoolException("任务状态修改失败!!");
                                log.error("========== RCS任务下发失败 ==========");
                                log.error("任务状态修改失败!!任务编码:{}", task.getTaskCode());
                                continue;
                            }
                            log.info("入库任务状态更新成功 - 任务编码:{}", task.getTaskCode());
                            /**排除移库功能*/
                            if (!task.getTaskType().equals(TaskType.TASK_TYPE_LOC_MOVE.type)) {
                                /**如果是普通站点,修改站点状态为出库预约*/
                                if (curSta.getType().equals(StationTypeEnum.STATION_TYPE_NORMAL.type)) {
                                    curSta.setUseStatus(LocStsType.LOC_STS_TYPE_R.type);
                                    if (!basStationService.updateById(curSta)) {
                                        throw new CoolException("站点预约失败!!");
                                        log.error("========== RCS任务下发失败 ==========");
                                        log.error("站点预约失败!!任务编码:{},站点:{}", task.getTaskCode(), curSta.getStationName());
                                        continue;
                                    }
                                }
                            }
@@ -1519,31 +1789,51 @@
                                || task.getTaskType().equals(TaskType.TASK_TYPE_PICK_AGAIN_OUT.type)) {
                            BasStation curSta = basStationService.getOne(new LambdaQueryWrapper<BasStation>().eq(BasStation::getStationName, task.getTargSite()));
                            if (Objects.isNull(curSta)) {
                                throw new CoolException("站点不存在!!");
                                log.error("========== RCS任务下发失败 ==========");
                                log.error("站点不存在!!任务编码:{},目标站点:{}", task.getTaskCode(), task.getTargSite());
                                continue;
                            }
                            log.info("更新出库任务状态 - 任务编码:{},新状态:{}", task.getTaskCode(), TaskStsType.WCS_EXECUTE_OUT.id);
                            if (!taskService.update(new LambdaUpdateWrapper<Task>().eq(Task::getTaskCode, task.getTaskCode())
                                    .set(Task::getTaskStatus, TaskStsType.WCS_EXECUTE_OUT.id))) {
                                throw new CoolException("任务状态修改失败!!");
                                log.error("========== RCS任务下发失败 ==========");
                                log.error("任务状态修改失败!!任务编码:{}", task.getTaskCode());
                                continue;
                            }
                            log.info("出库任务状态更新成功 - 任务编码:{}", task.getTaskCode());
                            /**如果是普通站点,修改站点状态为入库预约*/
                            if (curSta.getType().equals(StationTypeEnum.STATION_TYPE_NORMAL.type)) {
                                curSta.setUseStatus(LocStsType.LOC_STS_TYPE_S.type);
                                if (!basStationService.updateById(curSta)) {
                                    throw new CoolException("站点预约失败!!");
                                    log.error("========== RCS任务下发失败 ==========");
                                    log.error("站点预约失败!!任务编码:{},站点:{}", task.getTaskCode(), curSta.getStationName());
                                    continue;
                                }
                            }
                        }
                    });
                } else {
                    log.error(JSONObject.toJSONString(result));
//                    throw new CoolException("任务下发失败!!");
                    } else {
                        log.error("========== RCS任务下发失败 ==========");
                        log.error("RCS返回错误 - code:{},msg:{},data:{}",
                                result.getCode(), result.getMsg(), result.getData());
                        log.error("失败的任务编码:{},任务类型:{}", task.getTaskCode(), task.getTaskType());
                        log.error("任务下发失败!!任务编码:{}", task.getTaskCode());
                        continue;
                    }
                } catch (JsonProcessingException e) {
                    log.error("========== RCS任务下发异常 ==========");
                    log.error("解析RCS响应失败,响应体:{},任务编码:{}", exchange.getBody(), task.getTaskCode(), e);
                    log.error("解析RCS响应失败:{},任务编码:{}", e.getMessage(), task.getTaskCode());
                    continue;
                } catch (Exception e) {
                    log.error("========== RCS任务下发异常 ==========");
                    log.error("任务下发过程中发生异常,任务编码:{}", task.getTaskCode(), e);
                    log.error("任务下发异常:{},任务编码:{}", e.getMessage(), task.getTaskCode());
                    continue;
                }
            } catch (JsonProcessingException e) {
                throw new CoolException(e.getMessage());
            }
        }
        log.info("========== RCS任务下发完成,共{}个任务已处理 ==========", tasks.size());
    }/**
@@ -1585,12 +1875,9 @@
        if (taskItems.isEmpty()) {
            throw new CoolException("任务明细不存在!!");
        }
        try {
            //更新库位明细
            saveLocItem(taskItems, task.getId(), loginUserId);
        } catch (Exception e) {
            throw new CoolException("库位明细更新失败!!");
        }
        //更新库位明细
        saveLocItem(taskItems, task.getId(), loginUserId);
        /**对任务明细按组拖明细进行分组*/
        Map<Long, List<TaskItem>> orderMap = taskItems.stream().collect(Collectors.groupingBy(TaskItem::getSource));
@@ -1600,16 +1887,26 @@
                throw new CoolException("数据错误:组拖数据不存在,请联系管理员!!");
            }
            List<TaskItem> items = orderMap.get(key);
            try {
                //保存库存明细
                saveStockItems(items, task, pakinItem.getId(), pakinItem.getAsnCode(), pakinItem.getWkType(), pakinItem.getType(), loginUserId);
                //移出收货区库存, 修改组托状态
                removeReceiptStock(pakinItem, loginUserId);
            } catch (Exception e) {
                logger.error("<UNK>", e);
                throw new CoolException(e.getMessage());
            }
            //保存入出库明细
            saveStockItems(items, task, pakinItem.getId(), pakinItem.getAsnCode(), pakinItem.getWkType(), pakinItem.getType(), loginUserId);
            //移出收货区库存, 修改组托状态
            removeReceiptStock(pakinItem, loginUserId);
        });
        Set<Long> pkinItemIds = taskItems.stream().map(TaskItem::getSource).collect(Collectors.toSet());
        List<WaitPakinItem> pakinItems = waitPakinItemService.list(new LambdaQueryWrapper<WaitPakinItem>().in(WaitPakinItem::getId, pkinItemIds));
        if (pakinItems.isEmpty()) {
            throw new CoolException("组托明细不存在!!");
        }
        Set<Long> pakinIds = pakinItems.stream().map(WaitPakinItem::getPakinId).collect(Collectors.toSet());
        if (!waitPakinService.update(new LambdaUpdateWrapper<WaitPakin>()
                .set(WaitPakin::getIoStatus, PakinIOStatus.PAKIN_IO_STATUS_TASK_DONE.val)
                .set(WaitPakin::getUpdateBy, loginUserId)
                .in(WaitPakin::getId, pakinIds))) {
            throw new CoolException("组拖状态修改失败!!");
        }
        /**修改库位状态为F.在库*/
        if (!locService.update(new LambdaUpdateWrapper<Loc>().set(Loc::getUseStatus, LocStsType.LOC_STS_TYPE_F.type).eq(Loc::getCode, task.getTargLoc()))) {
            throw new CoolException("库位状态修改失败!!");
@@ -1637,13 +1934,6 @@
        Double workQty = Math.round((itemServiceOne.getWorkQty() - pakinItem.getAnfme()) * 1000000) / 1000000.0;
        Double qty = Math.round((itemServiceOne.getQty() + pakinItem.getAnfme()) * 1000000) / 1000000.0;
        itemServiceOne.setWorkQty(workQty).setQty(qty);
        if (!waitPakinService.update(new LambdaUpdateWrapper<WaitPakin>()
                .set(WaitPakin::getIoStatus, PakinIOStatus.PAKIN_IO_STATUS_TASK_DONE.val)
                .set(WaitPakin::getUpdateBy, loginUserId)
                .eq(WaitPakin::getId, pakinItem.getPakinId()))) {
            throw new CoolException("组拖状态修改失败!!");
        }
        if (qty.compareTo(itemServiceOne.getAnfme()) == 0.00) {
            if (!warehouseAreasItemService.removeById(itemServiceOne.getId())) {
@@ -1682,8 +1972,8 @@
            LocItem locItem = locItemService.getOne(new LambdaQueryWrapper<LocItem>()
                    .eq(LocItem::getMatnrId, taskItem.getMatnrId())
                    .eq(LocItem::getLocId, loc.getId())
                    .eq(StringUtils.isNoneBlank(taskItem.getBatch()), LocItem::getBatch, taskItem.getBatch())
                    .eq(StringUtils.isNoneBlank(taskItem.getFieldsIndex()), LocItem::getFieldsIndex, taskItem.getFieldsIndex()));
                    .eq(StringUtils.isNotBlank(taskItem.getBatch()), LocItem::getBatch, taskItem.getBatch())
                    .eq(StringUtils.isNotBlank(taskItem.getFieldsIndex()), LocItem::getFieldsIndex, taskItem.getFieldsIndex()));
            if (Objects.isNull(locItem)) {
                BeanUtils.copyProperties(taskItem, item);
                item.setLocCode(loc.getCode())
@@ -1696,11 +1986,13 @@
                    throw new CoolException("库位明细更新失败!!");
                }
            } else {
                locItem.setAnfme(Math.round((locItem.getAnfme() + taskItem.getAnfme()) * 1000000) / 1000000.0)
                        .setUpdateTime(new Date());
                if (!locItemService.saveOrUpdate(locItem)) {
                    throw new CoolException("库位明细更新失败!!");
                }
                logger.error("当前票号:"  + locItem.getFieldsIndex()  + " 已在库内,请检查后再操作!!");
//                throw new CoolException("当前票号已在库内,请检查后再操作!!");
//                locItem.setAnfme(Math.round((locItem.getAnfme() + taskItem.getAnfme()) * 1000000) / 1000000.0)
//                        .setUpdateTime(new Date());
//                if (!locItemService.saveOrUpdate(locItem)) {
//                    throw new CoolException("库位明细更新失败!!");
//                }
            }
        });