自动化立体仓库 - WMS系统
zwl
3 天以前 2acfc2d2a0e956910c51bd996f443b3cb9bd3dc9
src/main/java/com/zy/common/service/CommonService.java
@@ -7,12 +7,14 @@
import com.core.common.Cools;
import com.core.exception.CoolException;
import com.zy.asrs.entity.*;
import com.zy.asrs.entity.param.BasCrnDepthRuleRuntimePreviewParam;
import com.zy.asrs.entity.result.FindLocNoAttributeVo;
import com.zy.asrs.entity.result.KeyValueVo;
import com.zy.asrs.service.*;
import com.zy.asrs.utils.Utils;
import com.zy.asrs.utils.VersionUtils;
import com.zy.common.entity.Parameter;
import com.zy.common.model.CrnDepthRuleProfile;
import com.zy.common.model.LocTypeDto;
import com.zy.common.model.Shelves;
import com.zy.common.model.StartupDto;
@@ -42,6 +44,45 @@
public class CommonService {
    private static final int MIN_SPARE_LOC_COUNT = 2;
    private static class Run2AreaSearchResult {
        private final LocMast locMast;
        private final RowLastno rowLastno;
        private final List<Integer> runnableCrnNos;
        /**
         * @param locMast 命中的空库位
         * @param rowLastno 命中库区对应的轮询游标记录
         * @param runnableCrnNos 当前库区可参与轮询的堆垛机顺序
         */
        private Run2AreaSearchResult(LocMast locMast, RowLastno rowLastno, List<Integer> runnableCrnNos) {
            this.locMast = locMast;
            this.rowLastno = rowLastno;
            this.runnableCrnNos = runnableCrnNos;
        }
    }
    private static class Run2SearchResult {
        private final LocMast locMast;
        private final RowLastno rowLastno;
        private final List<Integer> runnableCrnNos;
        private Run2SearchResult(LocMast locMast, RowLastno rowLastno, List<Integer> runnableCrnNos) {
            this.locMast = locMast;
            this.rowLastno = rowLastno;
            this.runnableCrnNos = runnableCrnNos;
        }
    }
    private static class Run2Cursor {
        private final int currentRow;
        private final Integer currentCrnNo;
        private Run2Cursor(int currentRow, Integer currentCrnNo) {
            this.currentRow = currentRow;
            this.currentCrnNo = currentCrnNo;
        }
    }
    @Autowired
    private WrkMastService wrkMastService;
    @Autowired
@@ -64,6 +105,8 @@
    private SlaveProperties slaveProperties;
    @Autowired
    private WrkDetlService wrkDetlService;
    @Autowired
    private BasCrnDepthRuleService basCrnDepthRuleService;
    /**
     * 生成工作号
@@ -138,6 +181,7 @@
    @Transactional
    public StartupDto getLocNo(Integer staDescId, Integer sourceStaNo, FindLocNoAttributeVo findLocNoAttributeVo, LocTypeDto locTypeDto, List<Integer> recommendRows) {
        try {
            locTypeDto = normalizeLocTypeDto(staDescId, findLocNoAttributeVo, locTypeDto);
            Integer whsType = Utils.GetWhsType(sourceStaNo);
            RowLastno rowLastno = rowLastnoService.selectById(whsType);
            RowLastnoType rowLastnoType = rowLastnoTypeService.selectById(rowLastno.getTypeId());
@@ -171,6 +215,130 @@
        }
    }
    /**
     * 空托盘识别规则:
     * 1. 以组托档物料编码 matnr=emptyPallet 为主,不再依赖 ioType=10。
     * 2. 保留 staDescId=10 的兼容判断,避免旧链路还未切换时行为突变。
     */
    private boolean isEmptyPalletRequest(Integer staDescId, FindLocNoAttributeVo findLocNoAttributeVo) {
        if (findLocNoAttributeVo != null && "emptyPallet".equalsIgnoreCase(findLocNoAttributeVo.getMatnr())) {
            return true;
        }
        return staDescId != null && staDescId == 10;
    }
    /**
     * 统一整理入库规格,避免不同入口传入的 locType 不一致。
     *
     * 空托盘的库位策略有两段:
     * 1. 首轮只限制 loc_type2=1,表示优先找窄库位。
     * 2. loc_type1 高度信息必须保留,后续再按低位向高位兼容。
     *
     * 非空托盘只保留 loc_type1,满托找位不再使用 loc_type2/loc_type3 过滤。
     */
    private LocTypeDto normalizeLocTypeDto(Integer staDescId, FindLocNoAttributeVo findLocNoAttributeVo, LocTypeDto locTypeDto) {
        LocTypeDto normalizedLocTypeDto = locTypeDto == null ? new LocTypeDto() : locTypeDto;
        if (!isEmptyPalletRequest(staDescId, findLocNoAttributeVo)) {
            normalizedLocTypeDto.setLocType2(null);
            normalizedLocTypeDto.setLocType3(null);
            return normalizedLocTypeDto;
        }
        if (findLocNoAttributeVo != null && Cools.isEmpty(findLocNoAttributeVo.getMatnr())) {
            findLocNoAttributeVo.setMatnr("emptyPallet");
        }
        normalizedLocTypeDto.setLocType2((short) 1);
        return normalizedLocTypeDto;
    }
    private LocTypeDto copyLocTypeDto(LocTypeDto locTypeDto) {
        if (locTypeDto == null) {
            return null;
        }
        LocTypeDto copied = new LocTypeDto();
        copied.setLocType1(locTypeDto.getLocType1());
        copied.setLocType2(locTypeDto.getLocType2());
        copied.setLocType3(locTypeDto.getLocType3());
        copied.setSiteId(locTypeDto.getSiteId());
        return copied;
    }
    /**
     * 空托盘固定按 4 段式找位:
     * 1. 严格高度 + narrow
     * 2. 严格高度 + any locType2
     * 3. 向上兼容高度 + narrow
     * 4. 向上兼容高度 + any locType2
     */
    private List<LocTypeDto> buildEmptyPalletSearchLocTypes(LocTypeDto locTypeDto) {
        LinkedHashSet<LocTypeDto> searchLocTypes = new LinkedHashSet<LocTypeDto>();
        LocTypeDto narrowStrictLocType = copyLocTypeDto(locTypeDto == null ? new LocTypeDto() : locTypeDto);
        if (narrowStrictLocType != null) {
            narrowStrictLocType.setLocType2((short) 1);
            searchLocTypes.add(narrowStrictLocType);
            LocTypeDto openStrictLocType = copyLocTypeDto(narrowStrictLocType);
            openStrictLocType.setLocType2(null);
            searchLocTypes.add(openStrictLocType);
            LocTypeDto narrowCompatibleLocType = buildUpwardCompatibleLocTypeDto(narrowStrictLocType);
            if (narrowCompatibleLocType != null) {
                narrowCompatibleLocType.setLocType2((short) 1);
                searchLocTypes.add(narrowCompatibleLocType);
                LocTypeDto openCompatibleLocType = copyLocTypeDto(narrowCompatibleLocType);
                openCompatibleLocType.setLocType2(null);
                searchLocTypes.add(openCompatibleLocType);
            }
        }
        return new ArrayList<LocTypeDto>(searchLocTypes);
    }
    private String buildEmptyPalletStageCode(LocTypeDto baseLocTypeDto, LocTypeDto stageLocTypeDto) {
        boolean compatibleHeight = baseLocTypeDto != null
                && baseLocTypeDto.getLocType1() != null
                && stageLocTypeDto != null
                && stageLocTypeDto.getLocType1() != null
                && !baseLocTypeDto.getLocType1().equals(stageLocTypeDto.getLocType1());
        boolean narrowOnly = stageLocTypeDto != null
                && stageLocTypeDto.getLocType2() != null
                && stageLocTypeDto.getLocType2() == 1;
        return (compatibleHeight ? "compatible-height" : "strict-height")
                + "-"
                + (narrowOnly ? "narrow-only" : "all-locType2");
    }
    /**
     * 判断当前规格是否属于满托找位。
     *
     * 满托只参考 loc_type1,但仍需显式排除 loc_type2=1 的窄库位。
     */
    private boolean isFullPalletLocTypeSearch(LocTypeDto locTypeDto) {
        return locTypeDto != null && locTypeDto.getLocType2() == null && locTypeDto.getLocType3() == null;
    }
    /**
     * 把 locType 条件追加到库位查询条件里。
     */
    private Wrapper<LocMast> applyLocTypeFilters(Wrapper<LocMast> wrapper, LocTypeDto locTypeDto, boolean includeLocType1) {
        if (wrapper == null || locTypeDto == null) {
            return wrapper;
        }
        if (includeLocType1 && locTypeDto.getLocType1() != null && locTypeDto.getLocType1() > 0) {
            wrapper.eq("loc_type1", locTypeDto.getLocType1());
        }
        if (isFullPalletLocTypeSearch(locTypeDto)) {
            wrapper.eq("loc_type2", 0);
        }
        if (locTypeDto.getLocType2() != null && locTypeDto.getLocType2() > 0) {
            wrapper.eq("loc_type2", locTypeDto.getLocType2());
        }
//        if (locTypeDto.getLocType3() != null && locTypeDto.getLocType3() > 0) {
//            wrapper.eq("loc_type3", locTypeDto.getLocType3());
//        }
        return wrapper;
    }
    /**
     * 解析本次找位应优先使用的库区,站点绑定优先于接口传参。
     */
    private Integer resolvePreferredArea(Integer sourceStaNo, FindLocNoAttributeVo findLocNoAttributeVo) {
        BasDevp sourceStation = basDevpService.selectById(sourceStaNo);
        Integer stationArea = parseArea(sourceStation == null ? null : sourceStation.getArea());
@@ -184,6 +352,9 @@
        return null;
    }
    /**
     * 把站点维护的库区值统一解析成 1/2/3。
     */
    private Integer parseArea(String area) {
        if (Cools.isEmpty(area)) {
            return null;
@@ -210,6 +381,9 @@
        return null;
    }
    /**
     * 读取 AGV 各库区对应的排配置。
     */
    private String getAgvAreaRowsConfig(Integer area) {
        Parameter parameter = Parameter.get();
        if (parameter == null || area == null) {
@@ -227,6 +401,9 @@
        }
    }
    /**
     * 解析 AGV 指定库区的排顺序,缺配置时回退旧默认排。
     */
    private List<Integer> getAgvAreaRows(Integer area, RowLastno rowLastno) {
        List<Integer> configuredRows = parseAgvRows(getAgvAreaRowsConfig(area), rowLastno);
        if (!configuredRows.isEmpty()) {
@@ -235,6 +412,9 @@
        return getLegacyAgvRows(rowLastno);
    }
    /**
     * 汇总 AGV 所有库区的回退排顺序。
     */
    private List<Integer> getAgvFallbackRows(RowLastno rowLastno) {
        LinkedHashSet<Integer> rows = new LinkedHashSet<>();
        for (int area = 1; area <= 3; area++) {
@@ -244,6 +424,9 @@
        return new ArrayList<>(rows);
    }
    /**
     * 把 AGV 库区排配置解析成有序排号列表。
     */
    private List<Integer> parseAgvRows(String configValue, RowLastno rowLastno) {
        List<Integer> rows = new ArrayList<>();
        if (rowLastno == null || Cools.isEmpty(configValue)) {
@@ -280,6 +463,9 @@
        return rows;
    }
    /**
     * 返回 AGV 旧逻辑使用的默认排顺序。
     */
    private List<Integer> getLegacyAgvRows(RowLastno rowLastno) {
        List<Integer> rows = new ArrayList<>();
        if (rowLastno == null) {
@@ -301,6 +487,9 @@
        return rows;
    }
    /**
     * 仅在排号落在仓库范围内时追加到 AGV 排列表。
     */
    private void addAgvRow(LinkedHashSet<Integer> rows, Integer row, RowLastno rowLastno) {
        if (rows == null || row == null || rowLastno == null) {
            return;
@@ -311,6 +500,9 @@
        rows.add(row);
    }
    /**
     * 安全解析整数配置,失败时返回 null。
     */
    private Integer safeParseInt(String value) {
        if (Cools.isEmpty(value)) {
            return null;
@@ -322,6 +514,9 @@
        }
    }
    /**
     * 返回 AGV 各库区对应的 bay 范围。
     */
    private int[] getAgvAreaBayRange(Integer area) {
        if (area == null) {
            return new int[]{1, 19};
@@ -338,6 +533,9 @@
        }
    }
    /**
     * 按指定排和 bay 范围顺序搜索 AGV 可用库位。
     */
    private LocMast findAgvLocByRows(RowLastno rowLastno, RowLastnoType rowLastnoType, List<Integer> rows,
                                     int startBay, int endBay, int curRow, int nearRow,
                                     LocTypeDto locTypeDto, boolean useDeepCheck) {
@@ -345,14 +543,14 @@
            if (row == null) {
                continue;
            }
            List<LocMast> locMasts = locMastService.selectList(new EntityWrapper<LocMast>()
            Wrapper<LocMast> wrapper = new EntityWrapper<LocMast>()
                    .eq("row1", row)
                    .ge("bay1", startBay)
                    .le("bay1", endBay)
                    .eq("loc_sts", "O")
                    .eq("loc_type1", locTypeDto.getLocType1())
                    .orderBy("lev1", true)
                    .orderBy("bay1", true));
                    .eq("loc_sts", "O");
            applyLocTypeFilters(wrapper, locTypeDto, true);
            wrapper.orderBy("lev1", true).orderBy("bay1", true);
            List<LocMast> locMasts = locMastService.selectList(wrapper);
            for (LocMast candidate : locMasts) {
                if (!VersionUtils.locMoveCheckLocTypeComplete(candidate, locTypeDto)) {
                    continue;
@@ -372,6 +570,10 @@
        }
        return null;
    }
    /**
     * 读取 run2 各库区对应的排配置,缺失时复用 AGV 库区配置。
     */
    private String getRun2AreaRowsConfig(Integer area) {
        Parameter parameter = Parameter.get();
        if (parameter == null || area == null) {
@@ -394,6 +596,9 @@
        return Cools.isEmpty(run2Config) ? getAgvAreaRowsConfig(area) : run2Config;
    }
    /**
     * 解析 run2 指定库区的排顺序,缺配置时回退旧默认排。
     */
    private List<Integer> getRun2AreaRows(Integer area, RowLastno rowLastno) {
        List<Integer> configuredRows = parseAgvRows(getRun2AreaRowsConfig(area), rowLastno);
        if (!configuredRows.isEmpty()) {
@@ -402,6 +607,9 @@
        return getLegacyAgvRows(rowLastno);
    }
    /**
     * 汇总 run2 其它库区的回退排顺序。
     */
    private List<Integer> getRun2FallbackRows(RowLastno rowLastno) {
        LinkedHashSet<Integer> rows = new LinkedHashSet<>();
        for (int area = 1; area <= 3; area++) {
@@ -411,29 +619,103 @@
        return new ArrayList<>(rows);
    }
    /**
     * 解析 run2 的起始堆垛机号,优先使用 currentCrnNo。
     */
    private Integer resolveRun2CrnNo(RowLastno rowLastno) {
        if (rowLastno == null) {
            return null;
        }
        Integer currentRow = rowLastno.getCurrentRow();
        Integer startCrnNo = getRun2StartCrnNo(rowLastno);
        Integer endCrnNo = getRun2EndCrnNo(rowLastno);
        Integer currentCrnNo = rowLastno.getCurrentCrnNo();
        if (currentCrnNo == null || currentCrnNo <= 0 || currentCrnNo < startCrnNo) {
            return startCrnNo;
        }
        if (endCrnNo != null && currentCrnNo > endCrnNo) {
            return startCrnNo;
        }
        return currentCrnNo;
    }
    private Integer getRun2StartCrnNo(RowLastno rowLastno) {
        if (rowLastno == null || rowLastno.getsCrnNo() == null) {
            return 1;
        }
        return rowLastno.getsCrnNo();
    }
    private Integer getRun2EndCrnNo(RowLastno rowLastno) {
        if (rowLastno == null) {
            return null;
        }
        Integer startCrnNo = getRun2StartCrnNo(rowLastno);
        if (rowLastno.geteCrnNo() != null && rowLastno.geteCrnNo() >= startCrnNo) {
            return rowLastno.geteCrnNo();
        }
        int crnCount = resolveCrnCount(rowLastno);
        if (crnCount <= 0) {
            return startCrnNo;
        }
        return startCrnNo + crnCount - 1;
    }
    /**
     * 兼容旧 currentRow 游标,把排号换算成对应的堆垛机号。
     */
    private Integer resolveRun2CrnNoByCurrentRow(RowLastno rowLastno, Integer currentRow) {
        if (rowLastno == null) {
            return null;
        }
        Integer rowSpan = getCrnRowSpan(rowLastno.getTypeId());
        if (rowSpan == null || rowSpan <= 0) {
            rowSpan = 2;
        }
        int startRow = rowLastno.getsRow() == null ? 1 : rowLastno.getsRow();
        int startCrnNo = rowLastno.getsCrnNo() == null ? 1 : rowLastno.getsCrnNo();
        if (currentRow == null) {
        int startCrnNo = getRun2StartCrnNo(rowLastno);
        if (currentRow == null || currentRow <= 0) {
            return startCrnNo;
        }
        int offset = Math.max(currentRow - startRow, 0) / rowSpan;
        int crnNo = startCrnNo + offset;
        Integer endCrnNo = rowLastno.geteCrnNo();
        Integer endCrnNo = getRun2EndCrnNo(rowLastno);
        if (endCrnNo != null && crnNo > endCrnNo) {
            return startCrnNo;
        }
        return crnNo;
    }
    private Integer getNextSequentialRun2CrnNo(RowLastno rowLastno, Integer currentCrnNo) {
        if (rowLastno == null) {
            return null;
        }
        Integer startCrnNo = getRun2StartCrnNo(rowLastno);
        Integer endCrnNo = getRun2EndCrnNo(rowLastno);
        if (currentCrnNo == null || currentCrnNo < startCrnNo) {
            return startCrnNo;
        }
        if (endCrnNo != null && currentCrnNo >= endCrnNo) {
            return startCrnNo;
        }
        return currentCrnNo + 1;
    }
    /**
     * 解析 run2 下一轮应从哪台堆垛机开始。
     */
    private Integer getNextRun2CurrentCrnNo(RowLastno rowLastno, List<Integer> runnableCrnNos, Integer selectedCrnNo) {
        if (!Cools.isEmpty(runnableCrnNos) && selectedCrnNo != null) {
            int index = runnableCrnNos.indexOf(selectedCrnNo);
            if (index >= 0) {
                return runnableCrnNos.get((index + 1) % runnableCrnNos.size());
            }
        }
        return getNextSequentialRun2CrnNo(rowLastno, resolveRun2CrnNo(rowLastno));
    }
    /**
     * 在整仓轮询模式下推进到下一台堆垛机对应的起始排。
     */
    private int getNextRun2CurrentRow(RowLastno rowLastno, int currentRow) {
        Integer rowSpan = getCrnRowSpan(rowLastno.getTypeId());
        if (rowSpan == null || rowSpan <= 0) {
@@ -448,6 +730,9 @@
        return currentRow + rowSpan;
    }
    /**
     * 从指定起点开始生成完整的堆垛机轮询顺序。
     */
    private List<Integer> getOrderedCrnNos(RowLastno rowLastno, Integer startCrnNo) {
        List<Integer> orderedCrnNos = new ArrayList<>();
        if (rowLastno == null) {
@@ -468,6 +753,430 @@
        return orderedCrnNos;
    }
    /**
     * 优先按 s_crn_no/e_crn_no 反推真实堆垛机数量。
     *
     * 之前有逻辑错误把 asr_row_lastno.crn_qty 当成轮询游标写回,
     * 导致“堆垛机数量”字段被污染。后续找位不能再直接信任 crn_qty,
     * 否则会少扫堆垛机,表现出来就是任务长期偏向某几台堆垛机。
     */
    private int resolveCrnCount(RowLastno rowLastno) {
        if (rowLastno == null) {
            return 0;
        }
        if (rowLastno.getsCrnNo() != null && rowLastno.geteCrnNo() != null && rowLastno.geteCrnNo() >= rowLastno.getsCrnNo()) {
            return rowLastno.geteCrnNo() - rowLastno.getsCrnNo() + 1;
        }
        if (rowLastno.getCrnQty() != null && rowLastno.getCrnQty() > 0) {
            return rowLastno.getCrnQty();
        }
        Integer rowSpan = getCrnRowSpan(rowLastno.getTypeId());
        if (rowSpan != null && rowSpan > 0 && rowLastno.getsRow() != null && rowLastno.geteRow() != null && rowLastno.geteRow() >= rowLastno.getsRow()) {
            return (rowLastno.geteRow() - rowLastno.getsRow() + 1 + rowSpan - 1) / rowSpan;
        }
        return 0;
    }
    private Integer getCrnStartRow(RowLastno rowLastno, Integer crnNo) {
        if (rowLastno == null || crnNo == null) {
            return null;
        }
        Integer rowSpan = getCrnRowSpan(rowLastno.getTypeId());
        if (rowSpan == null || rowSpan <= 0) {
            return null;
        }
        int startCrnNo = rowLastno.getsCrnNo() == null ? 1 : rowLastno.getsCrnNo();
        int startRow = rowLastno.getsRow() == null ? 1 : rowLastno.getsRow();
        if (crnNo < startCrnNo) {
            return null;
        }
        return startRow + (crnNo - startCrnNo) * rowSpan;
    }
    /**
     * 按“可入 + 自动连线 + 无故障”判断堆垛机是否在线可分配。
     */
    private boolean isCrnActive(Integer crnNo) {
        if (crnNo == null) {
            return false;
        }
        BasCrnp basCrnp = basCrnpService.selectById(crnNo);
        if (Cools.isEmpty(basCrnp)) {
            return false;
        }
        if (!"Y".equalsIgnoreCase(basCrnp.getInEnable())) {
            return false;
        }
        if (basCrnp.getCrnSts() == null || basCrnp.getCrnSts() != 3) {
            return false;
        }
        return basCrnp.getCrnErr() == null || basCrnp.getCrnErr() == 0;
    }
    /**
     * 判断某台堆垛机是否可以参与 run2 入库找位。
     *
     * routeRequired=true:
     * 普通入库必须同时满足设备可入、设备无故障、并且当前源站到该堆垛机存在有效目标站路径。
     *
     * routeRequired=false:
     * 空托盘跨库区找位时,只校验设备主档、故障和可入状态,不把 sta_desc 路径当成拦截条件。
     * 这样做是为了先满足“能找到库位”,目标站路径由后续主数据补齐。
     */
    private boolean canRun2CrnAcceptPakin(RowLastno rowLastno, Integer staDescId, Integer sourceStaNo, Integer crnNo) {
        return canRun2CrnAcceptPakin(rowLastno, staDescId, sourceStaNo, crnNo, true);
    }
    private boolean canRun2CrnAcceptPakin(RowLastno rowLastno, Integer staDescId, Integer sourceStaNo, Integer crnNo, boolean routeRequired) {
        if (!isCrnActive(crnNo)) {
            return false;
        }
        if (!routeRequired) {
            return true;
        }
        if (!Utils.BooleanWhsTypeSta(rowLastno, staDescId)) {
            return true;
        }
        StaDesc staDesc = staDescService.selectOne(new EntityWrapper<StaDesc>()
                .eq("type_no", staDescId)
                .eq("stn_no", sourceStaNo)
                .eq("crn_no", crnNo));
        return !Cools.isEmpty(staDesc) && !Cools.isEmpty(staDesc.getCrnStn());
    }
    /**
     * 按既定轮询顺序过滤出真正可参与本次找位的堆垛机列表。
     */
    private List<Integer> getOrderedRunnableRun2CrnNos(RowLastno rowLastno, Integer staDescId, Integer sourceStaNo, List<Integer> orderedCrnNos) {
        return getOrderedRunnableRun2CrnNos(rowLastno, staDescId, sourceStaNo, orderedCrnNos, true);
    }
    private List<Integer> getOrderedRunnableRun2CrnNos(RowLastno rowLastno, Integer staDescId, Integer sourceStaNo, List<Integer> orderedCrnNos, boolean routeRequired) {
        List<Integer> runnableCrnNos = new ArrayList<>();
        if (Cools.isEmpty(orderedCrnNos)) {
            return runnableCrnNos;
        }
        for (Integer candidateCrnNo : orderedCrnNos) {
            if (canRun2CrnAcceptPakin(rowLastno, staDescId, sourceStaNo, candidateCrnNo, routeRequired)) {
                runnableCrnNos.add(candidateCrnNo);
            }
        }
        return runnableCrnNos;
    }
    /**
     * 根据本次命中的堆垛机,把轮询游标推进到下一台可参与轮询的堆垛机。
     */
    private int getNextRun2CurrentRow(RowLastno rowLastno, List<Integer> runnableCrnNos, Integer selectedCrnNo, int currentRow) {
        if (Cools.isEmpty(runnableCrnNos) || selectedCrnNo == null) {
            return getNextRun2CurrentRow(rowLastno, currentRow);
        }
        int index = runnableCrnNos.indexOf(selectedCrnNo);
        if (index < 0) {
            return getNextRun2CurrentRow(rowLastno, currentRow);
        }
        Integer nextCrnNo = runnableCrnNos.get((index + 1) % runnableCrnNos.size());
        Integer nextRow = getCrnStartRow(rowLastno, nextCrnNo);
        return nextRow == null ? getNextRun2CurrentRow(rowLastno, currentRow) : nextRow;
    }
    private Run2Cursor getNextRun2Cursor(RowLastno rowLastno, List<Integer> runnableCrnNos, Integer selectedCrnNo, int currentRow) {
        if (rowLastno == null) {
            return null;
        }
        Integer nextCrnNo = getNextRun2CurrentCrnNo(rowLastno, runnableCrnNos, selectedCrnNo);
        Integer nextRow = nextCrnNo == null ? null : getCrnStartRow(rowLastno, nextCrnNo);
        if (nextRow == null) {
            int baseRow = currentRow == 0 ? (rowLastno.getsRow() == null ? 1 : rowLastno.getsRow()) : currentRow;
            nextRow = getNextRun2CurrentRow(rowLastno, baseRow);
            nextCrnNo = resolveRun2CrnNoByCurrentRow(rowLastno, nextRow);
        }
        return new Run2Cursor(nextRow, nextCrnNo);
    }
    private void updateRun2Cursor(RowLastno rowLastno, List<Integer> runnableCrnNos, Integer selectedCrnNo, int currentRow) {
        if (rowLastno == null) {
            return;
        }
        Run2Cursor nextCursor = getNextRun2Cursor(rowLastno, runnableCrnNos, selectedCrnNo, currentRow);
        if (nextCursor == null) {
            return;
        }
        rowLastno.setCurrentRow(nextCursor.currentRow);
        rowLastno.setCurrentCrnNo(nextCursor.currentCrnNo);
        rowLastnoService.updateById(rowLastno);
    }
    /**
     * 构造空托盘跨库区搜索顺序:
     * 先当前库区,再依次补足其它库区,避免重复。
     */
    private List<Integer> buildAreaSearchOrder(Integer preferredArea) {
        LinkedHashSet<Integer> areaOrder = new LinkedHashSet<>();
        if (preferredArea != null && preferredArea >= 1 && preferredArea <= 3) {
            areaOrder.add(preferredArea);
        }
        for (int area = 1; area <= 3; area++) {
            areaOrder.add(area);
        }
        return new ArrayList<>(areaOrder);
    }
    /**
     * 预览 run2 当前会参与的库区、堆垛机顺序和深浅排画像,不落任务档。
     */
    public Map<String, Object> previewRun2Allocation(BasCrnDepthRuleRuntimePreviewParam param) {
        if (param == null || param.getStaDescId() == null || param.getSourceStaNo() == null) {
            throw new CoolException("路径ID和源站不能为空");
        }
        FindLocNoAttributeVo findLocNoAttributeVo = new FindLocNoAttributeVo();
        findLocNoAttributeVo.setMatnr(param.getMatnr());
        findLocNoAttributeVo.setOutArea(param.getOutArea());
        LocTypeDto locTypeDto = new LocTypeDto();
        locTypeDto.setLocType1(param.getLocType1());
        locTypeDto.setLocType2(param.getLocType2());
        locTypeDto.setLocType3(param.getLocType3());
        locTypeDto = normalizeLocTypeDto(param.getStaDescId(), findLocNoAttributeVo, locTypeDto);
        Integer whsType = Utils.GetWhsType(param.getSourceStaNo());
        RowLastno rowLastno = rowLastnoService.selectById(whsType);
        if (Cools.isEmpty(rowLastno)) {
            throw new CoolException("未找到仓库轮询规则");
        }
        RowLastnoType rowLastnoType = rowLastnoTypeService.selectById(rowLastno.getTypeId());
        Integer preferredArea = resolvePreferredArea(param.getSourceStaNo(), findLocNoAttributeVo);
        boolean emptyPalletRequest = isEmptyPalletRequest(param.getStaDescId(), findLocNoAttributeVo);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("whsType", whsType);
        result.put("preferredArea", preferredArea);
        result.put("emptyPallet", emptyPalletRequest);
        result.put("locType", locTypeDto);
        result.put("stationPriorityEntries", Utils.getStationStorageAreaName(
                param.getSourceStaNo(),
                locTypeDto == null || locTypeDto.getLocType1() == null ? null : locTypeDto.getLocType1().intValue(),
                findLocNoAttributeVo.getMatnr()));
        List<Integer> orderedCrnNos = getOrderedCrnNos(rowLastno, resolveRun2CrnNo(rowLastno));
        List<Integer> runnableCrnNos = getOrderedRunnableRun2CrnNos(rowLastno, param.getStaDescId(), param.getSourceStaNo(), orderedCrnNos);
        result.put("orderedCrnNos", orderedCrnNos);
        result.put("runnableCrnNos", runnableCrnNos);
        if (emptyPalletRequest) {
            List<Integer> areaSearchOrder = buildAreaSearchOrder(preferredArea);
            List<Map<String, Object>> searchStages = new ArrayList<Map<String, Object>>();
            for (LocTypeDto stageLocTypeDto : buildEmptyPalletSearchLocTypes(locTypeDto)) {
                List<Map<String, Object>> areaPreviews = new ArrayList<Map<String, Object>>();
                for (Integer area : areaSearchOrder) {
                    RowLastno areaRowLastno = getAreaRowLastno(area, rowLastno);
                    RowLastnoType areaRowLastnoType = rowLastnoTypeService.selectById(areaRowLastno.getTypeId());
                    List<Integer> areaOrderedCrnNos = getOrderedCrnNos(areaRowLastno, resolveRun2CrnNo(areaRowLastno));
                    List<Integer> areaRunnableCrnNos = getOrderedRunnableRun2CrnNos(areaRowLastno, param.getStaDescId(),
                            param.getSourceStaNo(), areaOrderedCrnNos, false);
                    Map<String, Object> areaItem = new HashMap<String, Object>();
                    areaItem.put("area", area);
                    areaItem.put("orderedCrnNos", areaOrderedCrnNos);
                    areaItem.put("runnableCrnNos", areaRunnableCrnNos);
                    areaItem.put("profiles", buildRun2ProfilePreview(areaRowLastno, areaRowLastnoType, areaOrderedCrnNos,
                            param.getStaDescId(), param.getSourceStaNo(), stageLocTypeDto));
                    areaPreviews.add(areaItem);
                }
                Map<String, Object> stageItem = new HashMap<String, Object>();
                stageItem.put("stageCode", buildEmptyPalletStageCode(locTypeDto, stageLocTypeDto));
                stageItem.put("locType", stageLocTypeDto);
                stageItem.put("areaSearchOrder", areaSearchOrder);
                stageItem.put("areaPreviews", areaPreviews);
                searchStages.add(stageItem);
            }
            result.put("areaSearchOrder", areaSearchOrder);
            result.put("searchStages", searchStages);
            return result;
        }
        if (preferredArea != null) {
            List<Integer> preferredCrnNos = filterCrnNosByRows(rowLastno, orderedCrnNos, getRun2AreaRows(preferredArea, rowLastno));
            result.put("candidateCrnNos", preferredCrnNos);
            result.put("profiles", buildRun2ProfilePreview(rowLastno, rowLastnoType, preferredCrnNos,
                    param.getStaDescId(), param.getSourceStaNo(), locTypeDto));
            result.put("areaMode", "preferred-area-only");
            return result;
        }
        result.put("candidateCrnNos", orderedCrnNos);
        result.put("profiles", buildRun2ProfilePreview(rowLastno, rowLastnoType, orderedCrnNos,
                param.getStaDescId(), param.getSourceStaNo(), locTypeDto));
        result.put("areaMode", "warehouse-round-robin");
        return result;
    }
    /**
     * 组装某批堆垛机的运行时画像预览数据。
     */
    private List<Map<String, Object>> buildRun2ProfilePreview(RowLastno rowLastno, RowLastnoType rowLastnoType, List<Integer> crnNos,
                                                              Integer staDescId, Integer sourceStaNo, LocTypeDto locTypeDto) {
        List<Map<String, Object>> profiles = new ArrayList<Map<String, Object>>();
        if (Cools.isEmpty(crnNos)) {
            return profiles;
        }
        for (Integer crnNo : crnNos) {
            CrnDepthRuleProfile profile = basCrnDepthRuleService.resolveProfile(rowLastno, crnNo, getCrnStartRow(rowLastno, crnNo));
            Map<String, Object> item = new HashMap<String, Object>();
            item.put("crnNo", crnNo);
            item.put("active", isCrnActive(crnNo));
            item.put("targetStaNo", resolveTargetStaNo(rowLastno, staDescId, sourceStaNo, crnNo));
            item.put("layoutType", profile == null ? null : profile.getLayoutType());
            item.put("source", profile == null ? null : profile.getSource());
            item.put("searchRows", profile == null ? null : profile.getSearchRows());
            item.put("shallowRows", profile == null ? null : profile.getShallowRows());
            item.put("deepRows", profile == null ? null : profile.getDeepRows());
            LocMast firstMatchLoc = findConfiguredEmptyLocForCrn(rowLastno, rowLastnoType, crnNo,
                    getCrnStartRow(rowLastno, crnNo), locTypeDto);
            item.put("firstMatchLocNo", firstMatchLoc == null ? null : firstMatchLoc.getLocNo());
            item.put("assignableLocCount", countAssignableLocForCrn(rowLastno, rowLastnoType, crnNo,
                    getCrnStartRow(rowLastno, crnNo) == null ? 0 : getCrnStartRow(rowLastno, crnNo), locTypeDto));
            profiles.add(item);
        }
        return profiles;
    }
    /**
     * 根据库区取该库区对应的轮询记录。
     * 当前库里 1/2/3 库区正好复用了 asr_row_lastno 的 whs_type 主键,因此这里直接按 area 取。
     * 如果缺主数据,就回退到当前源站所在仓的 rowLastno,避免直接空指针。
     */
    private RowLastno getAreaRowLastno(Integer area, RowLastno defaultRowLastno) {
        if (area != null && area > 0) {
            RowLastno areaRowLastno = rowLastnoService.selectById(area);
            if (!Cools.isEmpty(areaRowLastno)) {
                return areaRowLastno;
            }
        }
        return defaultRowLastno;
    }
    /**
     * 空托盘 run2 专用搜索链路。
     *
     * 执行顺序:
     * 1. 先按固定规格阶段构造 4 段式 locType 回退顺序。
     * 2. 每个规格阶段都按“当前库区 -> 其它库区”的顺序搜索。
     * 3. 每个库区内部都按该库区自己的 rowLastno/currentRow 做轮询均分。
     *
     * 这里故意不复用普通 run2 的“推荐排 -> 当前库区排 -> 其它排”逻辑,
     * 因为空托盘的业务口径已经切换成“按库区找堆垛机”,不是按推荐排找巷道。
     */
    private Run2AreaSearchResult findEmptyPalletRun2Loc(RowLastno defaultRowLastno, Integer staDescId, Integer sourceStaNo,
                                                        StartupDto startupDto, Integer preferredArea, LocTypeDto locTypeDto) {
        for (LocTypeDto stageLocTypeDto : buildEmptyPalletSearchLocTypes(locTypeDto)) {
            String stageCode = buildEmptyPalletStageCode(locTypeDto, stageLocTypeDto);
            Run2AreaSearchResult searchResult = findEmptyPalletRun2AreaLoc(defaultRowLastno, staDescId, sourceStaNo,
                    startupDto, preferredArea, stageLocTypeDto, stageCode);
            if (!Cools.isEmpty(searchResult) && !Cools.isEmpty(searchResult.locMast)) {
                return searchResult;
            }
        }
        return null;
    }
    private Run2AreaSearchResult findEmptyPalletRun2AreaLoc(RowLastno defaultRowLastno, Integer staDescId, Integer sourceStaNo,
                                                            StartupDto startupDto, Integer preferredArea, LocTypeDto locTypeDto,
                                                            String stageCode) {
        for (Integer area : buildAreaSearchOrder(preferredArea)) {
            RowLastno areaRowLastno = getAreaRowLastno(area, defaultRowLastno);
            if (Cools.isEmpty(areaRowLastno)) {
                continue;
            }
            RowLastnoType areaRowLastnoType = rowLastnoTypeService.selectById(areaRowLastno.getTypeId());
            if (Cools.isEmpty(areaRowLastnoType)) {
                continue;
            }
            Integer areaStartCrnNo = resolveRun2CrnNo(areaRowLastno);
            List<Integer> orderedAreaCrnNos = getOrderedCrnNos(areaRowLastno, areaStartCrnNo);
            // 空托盘跨库区时只筛设备主档和故障状态,不强依赖 sta_desc。
            List<Integer> runnableAreaCrnNos = getOrderedRunnableRun2CrnNos(areaRowLastno, staDescId, sourceStaNo, orderedAreaCrnNos, false);
            if (Cools.isEmpty(runnableAreaCrnNos)) {
                continue;
            }
            LocMast locMast = findRun2EmptyLocByCrnNos(areaRowLastno, areaRowLastnoType, runnableAreaCrnNos, locTypeDto,
                    staDescId, sourceStaNo, startupDto, area, stageCode + "-area-" + area, false);
            if (!Cools.isEmpty(locMast)) {
                return new Run2AreaSearchResult(locMast, areaRowLastno, runnableAreaCrnNos);
            }
        }
        return null;
    }
    /**
     * 空托盘命中库位后,按命中库区回写该库区自己的轮询游标。
     * 这样 A/B/C 三个库区会分别维护各自的“下一台堆垛机”,不会互相覆盖。
     */
    private void advanceEmptyPalletRun2Cursor(Run2AreaSearchResult searchResult, LocMast locMast) {
        if (searchResult == null || searchResult.rowLastno == null || locMast == null) {
            return;
        }
        RowLastno updateRowLastno = searchResult.rowLastno;
        int currentRow = updateRowLastno.getCurrentRow() == null ? 0 : updateRowLastno.getCurrentRow();
        updateRun2Cursor(updateRowLastno, searchResult.runnableCrnNos, locMast.getCrnNo(), currentRow);
    }
    /**
     * 普通物料 run2 找位主流程。
     *
     * 执行顺序:
     * 1. 先看站点是否配置了“堆垛机 + 库位类型”优先级。
     * 2. 没配库区时,直接按当前 run2 轮询顺序找位。
     * 3. 配了库区时,只在当前库区查找,普通托盘不跨库区兜底。
     */
    private Run2SearchResult findNormalRun2Loc(RowLastno rowLastno, RowLastnoType rowLastnoType, Integer sourceStaNo,
                                               Integer staDescId, FindLocNoAttributeVo findLocNoAttributeVo, LocTypeDto locTypeDto,
                                               StartupDto startupDto, Integer preferredArea, List<Integer> orderedCrnNos) {
        List<Map<String, Integer>> stationCrnLocTypes = Utils.getStationStorageAreaName(
                sourceStaNo,
                locTypeDto == null || locTypeDto.getLocType1() == null ? null : locTypeDto.getLocType1().intValue(),
                findLocNoAttributeVo == null ? null : findLocNoAttributeVo.getMatnr());
        if (!Cools.isEmpty(stationCrnLocTypes)) {
            // 站点优先级只是“优先尝试”,没有命中时必须继续走默认/库区回退,
            // 否则会把“优先候选无位”误判成“整仓无位”。
            LocMast locMast = findRun2EmptyLocByCrnLocTypeEntries(rowLastno, rowLastnoType, stationCrnLocTypes,
                    locTypeDto, staDescId, sourceStaNo, startupDto, preferredArea, "station-priority");
            if (!Cools.isEmpty(locMast)) {
                return new Run2SearchResult(locMast, rowLastno,
                        getOrderedRunnableRun2CrnNos(rowLastno, staDescId, sourceStaNo, extractCrnNos(stationCrnLocTypes)));
            }
        }
        List<Integer> candidateCrnNos;
        if (preferredArea == null) {
            candidateCrnNos = new ArrayList<>(orderedCrnNos);
        } else {
            candidateCrnNos = filterCrnNosByRows(rowLastno, orderedCrnNos, getRun2AreaRows(preferredArea, rowLastno));
        }
        List<Integer> runnableCrnNos = getOrderedRunnableRun2CrnNos(rowLastno, staDescId, sourceStaNo, candidateCrnNos);
        LocMast locMast = findRun2EmptyLocByCrnNos(rowLastno, rowLastnoType, candidateCrnNos, locTypeDto,
                staDescId, sourceStaNo, startupDto, preferredArea, preferredArea == null ? "default" : "preferred-area");
        return new Run2SearchResult(locMast, rowLastno, runnableCrnNos);
    }
    /**
     * 普通物料命中库位后,沿用 run2 原有的全仓轮询游标推进方式。
     */
    private void advanceNormalRun2Cursor(RowLastno rowLastno, int curRow) {
        updateRun2Cursor(rowLastno, null, null, curRow);
    }
    /**
     * 普通物料游标优先按“本次真正可用的堆垛机集合”推进。
     *
     * 这样即使库区定义里存在不存在的堆垛机,或者路径主数据只覆盖部分堆垛机,
     * 满板任务也会在真实可作业的堆垛机之间轮询,不会因为理论堆垛机号的空洞而长期回落到同一台。
     */
    private void advanceNormalRun2Cursor(RowLastno rowLastno, int curRow, List<Integer> runnableCrnNos, Integer selectedCrnNo) {
        updateRun2Cursor(rowLastno, runnableCrnNos, selectedCrnNo, curRow);
    }
    /**
     * 根据排范围把整仓堆垛机顺序裁剪为某个库区内的堆垛机集合。
     */
    private List<Integer> filterCrnNosByRows(RowLastno rowLastno, List<Integer> orderedCrnNos, List<Integer> rows) {
        if (Cools.isEmpty(rows)) {
            return new ArrayList<>(orderedCrnNos);
@@ -497,33 +1206,9 @@
        return result;
    }
    private List<Integer> mapRowsToCrnNos(RowLastno rowLastno, List<Integer> rows) {
        List<Integer> result = new ArrayList<>();
        if (rowLastno == null || Cools.isEmpty(rows)) {
            return result;
        }
        LinkedHashSet<Integer> orderedCrnNos = new LinkedHashSet<>();
        Integer rowSpan = getCrnRowSpan(rowLastno.getTypeId());
        if (rowSpan == null || rowSpan <= 0) {
            rowSpan = 2;
        }
        int startCrnNo = rowLastno.getsCrnNo() == null ? 1 : rowLastno.getsCrnNo();
        int endCrnNo = rowLastno.geteCrnNo() == null ? startCrnNo + rowLastno.getCrnQty() - 1 : rowLastno.geteCrnNo();
        int startRow = rowLastno.getsRow() == null ? 1 : rowLastno.getsRow();
        int endRow = rowLastno.geteRow() == null ? Integer.MAX_VALUE : rowLastno.geteRow();
        for (Integer row : rows) {
            if (row == null || row < startRow || row > endRow) {
                continue;
            }
            int crnNo = startCrnNo + (row - startRow) / rowSpan;
            if (crnNo >= startCrnNo && crnNo <= endCrnNo) {
                orderedCrnNos.add(crnNo);
            }
        }
        result.addAll(orderedCrnNos);
        return result;
    }
    /**
     * 解析当前源站到目标堆垛机的入库目标站号。
     */
    private Integer resolveTargetStaNo(RowLastno rowLastno, Integer staDescId, Integer sourceStaNo, Integer crnNo) {
        if (!Utils.BooleanWhsTypeSta(rowLastno, staDescId)) {
            return null;
@@ -537,8 +1222,8 @@
            return null;
        }
        BasDevp staNo = basDevpService.selectById(staDesc.getCrnStn());
        if (Cools.isEmpty(staNo) || !"Y".equals(staNo.getAutoing())) {
            log.error("目标站{}不可用", staDesc.getCrnStn());
        if (Cools.isEmpty(staNo)) {
            log.error("目标站{}不存在", staDesc.getCrnStn());
            return null;
        }
        return staNo.getDevNo();
@@ -552,9 +1237,26 @@
                JSON.toJSONString(locTypeDto));
    }
    /**
     * 按给定堆垛机顺序依次找空库位。
     *
     * 这里同时承担三类过滤:
     * 1. 设备侧过滤:堆垛机故障或不存在时直接跳过。
     * 2. 路径侧过滤:当前源站到该堆垛机目标站无路径时跳过。
     * 3. 库位侧过滤:无空库位或库位规格不匹配时跳过。
     *
     * 对空托盘来说,candidateCrnNos 由 run2 的轮询顺序生成,因此天然具备“均分到每个堆垛机”的效果。
     */
    private LocMast findRun2EmptyLocByCrnNos(RowLastno rowLastno, RowLastnoType rowLastnoType, List<Integer> candidateCrnNos,
                                             LocTypeDto locTypeDto, Integer staDescId, Integer sourceStaNo, StartupDto startupDto,
                                             Integer preferredArea, String stage) {
        return findRun2EmptyLocByCrnNos(rowLastno, rowLastnoType, candidateCrnNos, locTypeDto,
                staDescId, sourceStaNo, startupDto, preferredArea, stage, true);
    }
    private LocMast findRun2EmptyLocByCrnNos(RowLastno rowLastno, RowLastnoType rowLastnoType, List<Integer> candidateCrnNos,
                                             LocTypeDto locTypeDto, Integer staDescId, Integer sourceStaNo, StartupDto startupDto,
                                             Integer preferredArea, String stage, boolean routeRequired) {
        if (Cools.isEmpty(candidateCrnNos)) {
            log.warn("run2 skip empty candidate list. stage={}, sourceStaNo={}, preferredArea={}, spec={}",
                    stage, sourceStaNo, preferredArea, JSON.toJSONString(locTypeDto));
@@ -564,49 +1266,60 @@
        List<Integer> routeBlockedCrns = new ArrayList<>();
        List<Integer> noEmptyCrns = new ArrayList<>();
        List<Integer> locTypeBlockedCrns = new ArrayList<>();
        for (Integer candidateCrnNo : candidateCrnNos) {
            if (candidateCrnNo == null || !basCrnpService.checkSiteError(candidateCrnNo, true)) {
                crnErrorCrns.add(candidateCrnNo);
                continue;
            }
            Integer targetStaNo = resolveTargetStaNo(rowLastno, staDescId, sourceStaNo, candidateCrnNo);
            if (Utils.BooleanWhsTypeSta(rowLastno, staDescId) && targetStaNo == null) {
                routeBlockedCrns.add(candidateCrnNo);
                continue;
            }
            Wrapper<LocMast> openWrapper = new EntityWrapper<LocMast>()
                    .eq("crn_no", candidateCrnNo)
                    .eq("loc_sts", "O")
                    .eq("loc_type1", locTypeDto.getLocType1())
                    .orderBy("lev1")
                    .orderBy("bay1");
            LocMast anyOpenLoc = locMastService.selectOne(openWrapper);
            if (Cools.isEmpty(anyOpenLoc)) {
                noEmptyCrns.add(candidateCrnNo);
                continue;
            }
            Wrapper<LocMast> wrapper = new EntityWrapper<LocMast>()
                    .eq("crn_no", candidateCrnNo)
                    .eq("loc_sts", "O")
                    .eq("loc_type1", locTypeDto.getLocType1())
                    .orderBy("lev1")
                    .orderBy("bay1");
            if (locTypeDto != null && locTypeDto.getLocType1() != null) {
                wrapper.eq("loc_type1", locTypeDto.getLocType1());
            }
            LocMast candidateLoc = locMastService.selectOne(wrapper);
            if (Cools.isEmpty(candidateLoc) || (locTypeDto != null && !VersionUtils.locMoveCheckLocTypeComplete(candidateLoc, locTypeDto))) {
                locTypeBlockedCrns.add(candidateCrnNo);
                continue;
            }
            if (targetStaNo != null) {
                startupDto.setStaNo(targetStaNo);
            }
            return candidateLoc;
        }
        logRun2NoMatch(stage, sourceStaNo, preferredArea, candidateCrnNos, locTypeDto, crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
        return null;
        return findRun2EmptyLocByCrnNosRecursively(rowLastno, rowLastnoType, candidateCrnNos, locTypeDto,
                staDescId, sourceStaNo, startupDto, preferredArea, stage, routeRequired, 0,
                crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
    }
    private LocMast findRun2EmptyLocByCrnNosRecursively(RowLastno rowLastno, RowLastnoType rowLastnoType,
                                                        List<Integer> candidateCrnNos, LocTypeDto locTypeDto,
                                                        Integer staDescId, Integer sourceStaNo, StartupDto startupDto,
                                                        Integer preferredArea, String stage, boolean routeRequired, int index,
                                                        List<Integer> crnErrorCrns, List<Integer> routeBlockedCrns,
                                                        List<Integer> noEmptyCrns, List<Integer> locTypeBlockedCrns) {
        if (index >= candidateCrnNos.size()) {
            logRun2NoMatch(stage, sourceStaNo, preferredArea, candidateCrnNos, locTypeDto,
                    crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
            return null;
        }
        Integer candidateCrnNo = candidateCrnNos.get(index);
        if (!isCrnActive(candidateCrnNo)) {
            crnErrorCrns.add(candidateCrnNo);
            return findRun2EmptyLocByCrnNosRecursively(rowLastno, rowLastnoType, candidateCrnNos, locTypeDto,
                    staDescId, sourceStaNo, startupDto, preferredArea, stage, routeRequired, index + 1,
                    crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
        }
        Integer targetStaNo = routeRequired ? resolveTargetStaNo(rowLastno, staDescId, sourceStaNo, candidateCrnNo) : null;
        if (routeRequired && Utils.BooleanWhsTypeSta(rowLastno, staDescId) && targetStaNo == null) {
            routeBlockedCrns.add(candidateCrnNo);
            return findRun2EmptyLocByCrnNosRecursively(rowLastno, rowLastnoType, candidateCrnNos, locTypeDto,
                    staDescId, sourceStaNo, startupDto, preferredArea, stage, routeRequired, index + 1,
                    crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
        }
        Integer preferredNearRow = getCrnStartRow(rowLastno, candidateCrnNo);
        LocMast candidateLoc = findConfiguredEmptyLocForCrn(rowLastno, rowLastnoType, candidateCrnNo,
                preferredNearRow, locTypeDto);
        if (Cools.isEmpty(candidateLoc)) {
            int availableLocCount = countAssignableLocForCrn(rowLastno, rowLastnoType, candidateCrnNo,
                    preferredNearRow == null ? 0 : preferredNearRow, locTypeDto);
            if (availableLocCount <= 0) {
                noEmptyCrns.add(candidateCrnNo);
            } else {
                locTypeBlockedCrns.add(candidateCrnNo);
            }
            return findRun2EmptyLocByCrnNosRecursively(rowLastno, rowLastnoType, candidateCrnNos, locTypeDto,
                    staDescId, sourceStaNo, startupDto, preferredArea, stage, routeRequired, index + 1,
                    crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
        }
        if (targetStaNo != null) {
            startupDto.setStaNo(targetStaNo);
        }
        return candidateLoc;
    }
    /**
     * 按站点配置的“堆垛机 + 高低类型”优先级找位,并套用统一均衡策略。
     */
    private LocMast findRun2EmptyLocByCrnLocTypeEntries(RowLastno rowLastno, RowLastnoType rowLastnoType,
                                                        List<Map<String, Integer>> crnLocTypeEntries, LocTypeDto locTypeDto,
                                                        Integer staDescId, Integer sourceStaNo, StartupDto startupDto,
@@ -641,7 +1354,7 @@
        Integer candidateCrnNo = crnLocTypeEntry == null ? null : crnLocTypeEntry.get("crnNo");
        Short candidateLocType1 = crnLocTypeEntry == null || crnLocTypeEntry.get("locType1") == null
                ? null : crnLocTypeEntry.get("locType1").shortValue();
        if (candidateCrnNo == null || !basCrnpService.checkSiteError(candidateCrnNo, true)) {
        if (!isCrnActive(candidateCrnNo)) {
            crnErrorCrns.add(candidateCrnNo);
            return findRun2EmptyLocByCrnLocTypeEntriesRecursively(rowLastno, rowLastnoType, crnLocTypeEntries, locTypeDto,
                    staDescId, sourceStaNo, startupDto, preferredArea, stage, index + 1, candidateCrnNos,
@@ -655,15 +1368,17 @@
                    crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
        }
        LocTypeDto searchLocTypeDto = buildRun2SearchLocTypeDto(locTypeDto, candidateLocType1);
        LocMast candidateLoc = findRun2OrderedEmptyLocByCrnLocType(rowLastnoType, candidateCrnNo, candidateLocType1, searchLocTypeDto);
        Integer preferredNearRow = getCrnStartRow(rowLastno, candidateCrnNo);
        LocMast candidateLoc = findConfiguredEmptyLocForCrn(rowLastno, rowLastnoType, candidateCrnNo,
                preferredNearRow, searchLocTypeDto);
        if (Cools.isEmpty(candidateLoc)) {
            noEmptyCrns.add(candidateCrnNo);
            return findRun2EmptyLocByCrnLocTypeEntriesRecursively(rowLastno, rowLastnoType, crnLocTypeEntries, locTypeDto,
                    staDescId, sourceStaNo, startupDto, preferredArea, stage, index + 1, candidateCrnNos,
                    crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
        }
        if (searchLocTypeDto != null && !VersionUtils.locMoveCheckLocTypeComplete(candidateLoc, searchLocTypeDto)) {
            locTypeBlockedCrns.add(candidateCrnNo);
            int availableLocCount = countAssignableLocForCrn(rowLastno, rowLastnoType, candidateCrnNo,
                    preferredNearRow == null ? 0 : preferredNearRow, searchLocTypeDto);
            if (availableLocCount <= 0) {
                noEmptyCrns.add(candidateCrnNo);
            } else {
                locTypeBlockedCrns.add(candidateCrnNo);
            }
            return findRun2EmptyLocByCrnLocTypeEntriesRecursively(rowLastno, rowLastnoType, crnLocTypeEntries, locTypeDto,
                    staDescId, sourceStaNo, startupDto, preferredArea, stage, index + 1, candidateCrnNos,
                    crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
@@ -674,6 +1389,9 @@
        return candidateLoc;
    }
    /**
     * 从站点优先级配置中抽取不重复的堆垛机顺序。
     */
    private List<Integer> extractCrnNos(List<Map<String, Integer>> crnLocTypeEntries) {
        LinkedHashSet<Integer> orderedCrnNos = new LinkedHashSet<>();
        if (Cools.isEmpty(crnLocTypeEntries)) {
@@ -688,6 +1406,9 @@
        return new ArrayList<>(orderedCrnNos);
    }
    /**
     * 用站点优先级里的 locType1 覆盖本次查询的高度条件。
     */
    private LocTypeDto buildRun2SearchLocTypeDto(LocTypeDto locTypeDto, Short candidateLocType1) {
        if (locTypeDto == null && candidateLocType1 == null) {
            return null;
@@ -705,6 +1426,9 @@
        return searchLocTypeDto;
    }
    /**
     * 按站点优先配置直接查某台堆垛机上的第一个可用空库位。
     */
    private LocMast findRun2OrderedEmptyLocByCrnLocType(RowLastnoType rowLastnoType, Integer candidateCrnNo,
                                                        Short candidateLocType1, LocTypeDto locTypeDto) {
        if (candidateCrnNo == null) {
@@ -716,6 +1440,7 @@
        if (candidateLocType1 != null) {
            wrapper.eq("loc_type1", candidateLocType1);
        }
        applyLocTypeFilters(wrapper, locTypeDto, false);
        // 单伸堆垛机按层、列递增顺序找第一个空库位。
        if (rowLastnoType != null && rowLastnoType.getType() != null && (rowLastnoType.getType() == 1 || rowLastnoType.getType() == 2)) {
            wrapper.orderBy("lev1", true).orderBy("bay1", true);
@@ -841,30 +1566,252 @@
        return offset < bestOffset;
    }
    private int countAvailableLocForCrn(RowLastno rowLastno, RowLastnoType rowLastnoType, int crnNo, int preferredNearRow) {
        List<Integer> searchRows = getCrnSearchRows(rowLastno, crnNo, preferredNearRow);
        if (searchRows.isEmpty()) {
            return 0;
    /**
     * 推导库位主档查询时应使用的 whsType。
     */
    private Long resolveLocWhsType(RowLastno rowLastno, RowLastnoType rowLastnoType) {
        if (rowLastno != null && rowLastno.getWhsType() != null) {
            return rowLastno.getWhsType().longValue();
        }
        return locMastService.selectCount(new EntityWrapper<LocMast>()
                .in("row1", searchRows)
                .eq("loc_sts", "O")
                .eq("whs_type", rowLastnoType.getType().longValue()));
        if (rowLastnoType != null && rowLastnoType.getType() != null) {
            return rowLastnoType.getType().longValue();
        }
        return null;
    }
    private int countAvailableSingleExtensionLocForCrn(RowLastno rowLastno, RowLastnoType rowLastnoType, int crnNo, int preferredNearRow, LocTypeDto locTypeDto) {
        List<Integer> searchRows = getCrnSearchRows(rowLastno, crnNo, preferredNearRow);
        if (searchRows.isEmpty()) {
            return 0;
    /**
     * 判断库位是否满足本次规格约束。
     */
    private boolean matchesLocType(LocMast locMast, LocTypeDto locTypeDto) {
        if (locMast != null && isFullPalletLocTypeSearch(locTypeDto) && locMast.getLocType2() != null
                && locMast.getLocType2() == 1) {
            return false;
        }
        return locTypeDto == null || VersionUtils.locMoveCheckLocTypeComplete(locMast, locTypeDto);
    }
    /**
     * 查询某一排上的所有空库位,并按单伸/双伸策略排序。
     */
    private List<LocMast> findOpenLocsByRow(RowLastno rowLastno, RowLastnoType rowLastnoType, Integer row,
                                            Integer crnNo, LocTypeDto locTypeDto, boolean singleExtension) {
        List<LocMast> result = new ArrayList<LocMast>();
        if (row == null) {
            return result;
        }
        Wrapper<LocMast> wrapper = new EntityWrapper<LocMast>()
                .in("row1", searchRows)
                .eq("loc_sts", "O")
                .eq("whs_type", rowLastnoType.getType().longValue());
        if (locTypeDto != null && locTypeDto.getLocType1() != null) {
            wrapper.eq("loc_type1", locTypeDto.getLocType1());
//                .eq("row1", row)
                .eq("loc_sts", "O");
        if (crnNo != null) {
            wrapper.eq("crn_no", crnNo);
        }
        return locMastService.selectCount(wrapper);
        applyLocTypeFilters(wrapper, locTypeDto, true);
        if (singleExtension) {
            wrapper.orderBy("lev1", true).orderBy("bay1", true);
        } else {
            wrapper.orderBy("lev1", true).orderBy("bay1", true);
        }
        List<LocMast> locMasts = locMastService.selectList(wrapper);
        for (LocMast locMast : locMasts) {
            if (matchesLocType(locMast, locTypeDto)) {
                result.add(locMast);
            }
        }
        return result;
    }
    /**
     * 按排、列、层精确定位某个库位位置上的状态记录。
     */
    private LocMast findLocByPosition(RowLastno rowLastno, RowLastnoType rowLastnoType, Integer crnNo,
                                      Integer row, Integer bay, Integer lev, String... statuses) {
        if (row == null || bay == null || lev == null) {
            return null;
        }
        EntityWrapper<LocMast> wrapper = new EntityWrapper<LocMast>();
        wrapper.eq("row1", row);
        wrapper.eq("bay1", bay);
        wrapper.eq("lev1", lev);
        if (crnNo != null) {
            wrapper.eq("crn_no", crnNo);
        }
        Long whsType = resolveLocWhsType(rowLastno, rowLastnoType);
        if (whsType != null) {
            wrapper.eq("whs_type", whsType);
        }
        if (statuses != null && statuses.length > 0) {
            if (statuses.length == 1) {
                wrapper.eq("loc_sts", statuses[0]);
            } else {
                wrapper.in("loc_sts", statuses);
            }
        }
        return locMastService.selectOne(wrapper);
    }
    /**
     * 在一对浅排/深排之间选择真正可投放的目标库位。
     */
    private LocMast findPairAssignableLoc(RowLastno rowLastno, RowLastnoType rowLastnoType, Integer crnNo,
                                          Integer shallowRow, Integer deepRow, LocTypeDto locTypeDto) {
        List<LocMast> shallowOpenLocs = findOpenLocsByRow(rowLastno, rowLastnoType, shallowRow, crnNo, locTypeDto, false);
        if (Cools.isEmpty(shallowOpenLocs)) {
            return null;
        }
        if (deepRow == null) {
            return shallowOpenLocs.get(0);
        }
        for (LocMast shallowLoc : shallowOpenLocs) {
            LocMast deepOpenLoc = findLocByPosition(rowLastno, rowLastnoType, crnNo, deepRow, shallowLoc.getBay1(), shallowLoc.getLev1(), "O");
            if (!Cools.isEmpty(deepOpenLoc) && matchesLocType(deepOpenLoc, locTypeDto)) {
                return deepOpenLoc;
            }
        }
        for (LocMast shallowLoc : shallowOpenLocs) {
            LocMast deepBlockingLoc = findLocByPosition(rowLastno, rowLastnoType, crnNo, deepRow, shallowLoc.getBay1(), shallowLoc.getLev1(), "F", "D");
            if (!Cools.isEmpty(deepBlockingLoc)) {
                return shallowLoc;
            }
            if (findLocByPosition(rowLastno, rowLastnoType, crnNo, deepRow, shallowLoc.getBay1(), shallowLoc.getLev1()) == null) {
                return shallowLoc;
            }
        }
        return null;
    }
    /**
     * 按某台堆垛机的深浅排画像搜索第一个可分配空库位。
     */
    private LocMast findConfiguredEmptyLocForCrn(RowLastno rowLastno, RowLastnoType rowLastnoType, Integer crnNo,
                                                 Integer preferredNearRow, LocTypeDto locTypeDto) {
        if (rowLastno == null || crnNo == null) {
            return null;
        }
        CrnDepthRuleProfile profile = basCrnDepthRuleService.resolveProfile(rowLastno, crnNo, preferredNearRow);
        if (profile == null || Cools.isEmpty(profile.getSearchRows())) {
            return null;
        }
        LinkedHashSet<Integer> processedShallowRows = new LinkedHashSet<Integer>();
        boolean singleExtension = profile.isSingleExtension();
        for (Integer searchRow : profile.getSearchRows()) {
            if (searchRow == null) {
                continue;
            }
            if (!singleExtension) {
                if (profile.isShallowRow(searchRow)) {
                    if (!processedShallowRows.add(searchRow)) {
                        continue;
                    }
                    LocMast candidateLoc = findPairAssignableLoc(rowLastno, rowLastnoType, crnNo, searchRow,
                            profile.getPairedDeepRow(searchRow), locTypeDto);
                    if (!Cools.isEmpty(candidateLoc)) {
                        return candidateLoc;
                    }
                    continue;
                }
                if (profile.isDeepRow(searchRow)) {
                    Integer shallowRow = profile.getPairedShallowRow(searchRow);
                    if (shallowRow != null) {
                        if (!processedShallowRows.add(shallowRow)) {
                            continue;
                        }
                        LocMast candidateLoc = findPairAssignableLoc(rowLastno, rowLastnoType, crnNo, shallowRow,
                                searchRow, locTypeDto);
                        if (!Cools.isEmpty(candidateLoc)) {
                            return candidateLoc;
                        }
                        continue;
                    }
                }
            }
            List<LocMast> locMasts = findOpenLocsByRow(rowLastno, rowLastnoType, searchRow, crnNo, locTypeDto, singleExtension);
            if (!Cools.isEmpty(locMasts)) {
                return locMasts.get(0);
            }
        }
        return null;
    }
    /**
     * 统计某台堆垛机当前画像下可参与分配的空库位数量。
     */
    private int countAssignableLocForCrn(RowLastno rowLastno, RowLastnoType rowLastnoType, int crnNo, int preferredNearRow, LocTypeDto locTypeDto) {
        CrnDepthRuleProfile profile = basCrnDepthRuleService.resolveProfile(rowLastno, crnNo, preferredNearRow);
        if (profile == null || Cools.isEmpty(profile.getSearchRows())) {
            return 0;
        }
        int count = 0;
        LinkedHashSet<Integer> processedShallowRows = new LinkedHashSet<Integer>();
        boolean singleExtension = profile.isSingleExtension();
        for (Integer searchRow : profile.getSearchRows()) {
            if (searchRow == null) {
                continue;
            }
            if (!singleExtension) {
                if (profile.isShallowRow(searchRow)) {
                    if (!processedShallowRows.add(searchRow)) {
                        continue;
                    }
                    count += countAssignablePairLocs(rowLastno, rowLastnoType, crnNo, searchRow,
                            profile.getPairedDeepRow(searchRow), locTypeDto);
                    continue;
                }
                if (profile.isDeepRow(searchRow)) {
                    Integer shallowRow = profile.getPairedShallowRow(searchRow);
                    if (shallowRow != null) {
                        if (!processedShallowRows.add(shallowRow)) {
                            continue;
                        }
                        count += countAssignablePairLocs(rowLastno, rowLastnoType, crnNo, shallowRow, searchRow, locTypeDto);
                        continue;
                    }
                }
            }
            count += findOpenLocsByRow(rowLastno, rowLastnoType, searchRow, crnNo, locTypeDto, singleExtension).size();
        }
        return count;
    }
    /**
     * 统计一对浅排/深排上的可分配库位数量。
     */
    private int countAssignablePairLocs(RowLastno rowLastno, RowLastnoType rowLastnoType, Integer crnNo,
                                        Integer shallowRow, Integer deepRow, LocTypeDto locTypeDto) {
        List<LocMast> shallowOpenLocs = findOpenLocsByRow(rowLastno, rowLastnoType, shallowRow, crnNo, locTypeDto, false);
        if (Cools.isEmpty(shallowOpenLocs)) {
            return 0;
        }
        if (deepRow == null) {
            return shallowOpenLocs.size();
        }
        int count = 0;
        for (LocMast shallowLoc : shallowOpenLocs) {
            LocMast deepOpenLoc = findLocByPosition(rowLastno, rowLastnoType, crnNo, deepRow, shallowLoc.getBay1(), shallowLoc.getLev1(), "O");
            if (!Cools.isEmpty(deepOpenLoc) && matchesLocType(deepOpenLoc, locTypeDto)) {
                count++;
                continue;
            }
            LocMast deepBlockingLoc = findLocByPosition(rowLastno, rowLastnoType, crnNo, deepRow, shallowLoc.getBay1(), shallowLoc.getLev1(), "F", "D");
            if (!Cools.isEmpty(deepBlockingLoc) ||
                    findLocByPosition(rowLastno, rowLastnoType, crnNo, deepRow, shallowLoc.getBay1(), shallowLoc.getLev1()) == null) {
                count++;
            }
        }
        return count;
    }
    /**
     * 统计某台堆垛机所有可用空库位数量,不附带规格过滤。
     */
    private int countAvailableLocForCrn(RowLastno rowLastno, RowLastnoType rowLastnoType, int crnNo, int preferredNearRow) {
        return countAssignableLocForCrn(rowLastno, rowLastnoType, crnNo, preferredNearRow, null);
    }
    /**
     * 统计某台单伸堆垛机在当前规格约束下的可用空库位数量。
     */
    private int countAvailableSingleExtensionLocForCrn(RowLastno rowLastno, RowLastnoType rowLastnoType, int crnNo, int preferredNearRow, LocTypeDto locTypeDto) {
        return countAssignableLocForCrn(rowLastno, rowLastnoType, crnNo, preferredNearRow, locTypeDto);
    }
    private Optional<CrnRowInfo> findBalancedSingleExtensionCrnAndNearRow(RowLastno rowLastno, int curRow, int crnNumber, int times,
@@ -928,35 +1875,20 @@
        return Optional.ofNullable(fallbackInfo);
    }
    /**
     * 返回某台堆垛机本次找位应扫描的排顺序。
     */
    private List<Integer> getCrnSearchRows(RowLastno rowLastno, int crnNo, int preferredNearRow) {
        List<Integer> searchRows = new ArrayList<>();
        addSearchRow(searchRows, preferredNearRow, rowLastno);
        Integer rowSpan = getCrnRowSpan(rowLastno.getTypeId());
        if (rowSpan == null) {
            return searchRows;
        CrnDepthRuleProfile profile = basCrnDepthRuleService.resolveProfile(rowLastno, crnNo, preferredNearRow);
        if (profile == null || Cools.isEmpty(profile.getSearchRows())) {
            return new ArrayList<Integer>();
        }
        int crnOffset = crnNo - rowLastno.getsCrnNo();
        if (crnOffset < 0) {
            return searchRows;
        }
        int startRow = rowLastno.getsRow() + crnOffset * rowSpan;
        switch (rowLastno.getTypeId()) {
            case 1:
                addSearchRow(searchRows, startRow + 1, rowLastno);
                addSearchRow(searchRows, startRow + 2, rowLastno);
                break;
            case 2:
                addSearchRow(searchRows, startRow, rowLastno);
                addSearchRow(searchRows, startRow + 1, rowLastno);
                break;
            default:
                break;
        }
        return searchRows;
        return new ArrayList<Integer>(profile.getSearchRows());
    }
    /**
     * 按库型返回每台堆垛机占用的排跨度。
     */
    private Integer getCrnRowSpan(Integer typeId) {
        if (typeId == null) {
            return null;
@@ -971,6 +1903,9 @@
        }
    }
    /**
     * 向搜索排列表追加一个合法且不重复的排号。
     */
    private void addSearchRow(List<Integer> searchRows, Integer row, RowLastno rowLastno) {
        if (row == null) {
            return;
@@ -983,67 +1918,16 @@
        }
    }
    /**
     * run/run2 标准堆垛机统一的空库位查询入口。
     */
    private LocMast findStandardEmptyLoc(RowLastno rowLastno, RowLastnoType rowLastnoType, int crnNo, int nearRow, LocTypeDto locTypeDto) {
        for (Integer searchRow : getCrnSearchRows(rowLastno, crnNo, nearRow)) {
            List<LocMast> locMasts = locMastService.selectList(new EntityWrapper<LocMast>()
                    .eq("row1", searchRow)
                    .eq("loc_sts", "O")
                    .eq("whs_type", rowLastnoType.getType().longValue())
                    .orderBy("lev1", true)
                    .orderBy("bay1", true));
            for (LocMast locMast1 : locMasts) {
                if (!VersionUtils.locMoveCheckLocTypeComplete(locMast1, locTypeDto)) {
                    continue;
                }
                if (Utils.BooleanWhsTypeStaIoType(rowLastno)) {
                    String shallowLoc = Utils.getDeepLoc(slaveProperties, locMast1.getLocNo());
                    LocMast locMast2 = locMastService.selectOne(new EntityWrapper<LocMast>()
                            .eq("loc_no", shallowLoc)
                            .eq("loc_sts", "O")
                            .eq("whs_type", rowLastnoType.getType().longValue()));
                    if (!Cools.isEmpty(locMast2)) {
                        return locMast2;
                    }
                } else if (!Cools.isEmpty(locMast1)) {
                    return locMast1;
                }
            }
            if (!Utils.BooleanWhsTypeStaIoType(rowLastno)) {
                continue;
            }
            for (LocMast locMast1 : locMasts) {
                if (!VersionUtils.locMoveCheckLocTypeComplete(locMast1, locTypeDto)) {
                    continue;
                }
                String shallowLoc = Utils.getDeepLoc(slaveProperties, locMast1.getLocNo());
                LocMast locMast2 = locMastService.selectOne(new EntityWrapper<LocMast>()
                        .eq("loc_no", shallowLoc)
                        .eq("loc_sts", "O")
                        .eq("whs_type", rowLastnoType.getType().longValue()));
                if (!Cools.isEmpty(locMast2)) {
                    return locMast2;
                }
                locMast2 = locMastService.selectOne(new EntityWrapper<LocMast>()
                        .eq("loc_no", shallowLoc)
                        .eq("loc_sts", "F")
                        .eq("whs_type", rowLastnoType.getType().longValue()));
                if (!Cools.isEmpty(locMast2)) {
                    return locMast1;
                }
                locMast2 = locMastService.selectOne(new EntityWrapper<LocMast>()
                        .eq("loc_no", shallowLoc)
                        .eq("loc_sts", "D")
                        .eq("whs_type", rowLastnoType.getType().longValue()));
                if (!Cools.isEmpty(locMast2)) {
                    return locMast1;
                }
            }
        }
        return null;
        return findConfiguredEmptyLocForCrn(rowLastno, rowLastnoType, crnNo, nearRow, locTypeDto);
    }
    /**
     * 构造只提升 locType1 的向上兼容规格。
     */
    private LocTypeDto buildUpwardCompatibleLocTypeDto(LocTypeDto locTypeDto) {
        if (locTypeDto == null || locTypeDto.getLocType1() == null || locTypeDto.getLocType1() >= 2) {
            return null;
@@ -1054,6 +1938,16 @@
        compatibleLocTypeDto.setLocType3(locTypeDto.getLocType3());
        compatibleLocTypeDto.setSiteId(locTypeDto.getSiteId());
        return compatibleLocTypeDto;
    }
    /**
     * 统一封装找库位失败后的兼容重试顺序。
     *
     * 兼容规则固定为:
     * 只允许 loc_type1 低位向高位兼容,loc_type2/loc_type3 不参与满托找位。
     */
    private LocTypeDto buildRetryCompatibleLocTypeDto(Integer staDescId, FindLocNoAttributeVo findLocNoAttributeVo, LocTypeDto locTypeDto) {
        return buildUpwardCompatibleLocTypeDto(locTypeDto);
    }
@@ -1091,7 +1985,7 @@
        }
        int sRow = rowLastno.getsRow();
        int eRow = rowLastno.geteRow();
        int crnNumber = rowLastno.getCrnQty();
        int crnNumber = resolveCrnCount(rowLastno);
        // ===============>>>> 开始执行
@@ -1261,9 +2155,9 @@
                times = times + 1;
                return getLocNoRun(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, locTypeDto, times);
            }
            LocTypeDto compatibleLocTypeDto = buildUpwardCompatibleLocTypeDto(locTypeDto);
            LocTypeDto compatibleLocTypeDto = buildRetryCompatibleLocTypeDto(staDescId, findLocNoAttributeVo, locTypeDto);
            if (compatibleLocTypeDto != null) {
                log.warn("locType1 upward compatibility retry. source={}, target={}", JSON.toJSONString(locTypeDto), JSON.toJSONString(compatibleLocTypeDto));
                log.warn("locType compatibility retry. source={}, target={}", JSON.toJSONString(locTypeDto), JSON.toJSONString(compatibleLocTypeDto));
                return getLocNoRun(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, compatibleLocTypeDto, 0);
            }
            log.error("No empty location found. spec={}, times={}", JSON.toJSONString(locTypeDto), times);
@@ -1285,12 +2179,20 @@
        return getLocNoRun2(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, locTypeDto, null, times);
    }
    /**
     * run2 入库找位主流程。
     *
     * 当前方法只保留“组织流程”和“统一收口”的职责,具体策略拆成独立方法:
     * 1. 普通物料:按 row_lastno 自身轮询顺序 -> 站点优先库区/堆垛机 -> 其它库区。
     * 2. 空托盘:优先库区 loc_type2=1 -> 其它库区 loc_type2=1 -> loc_type1=2 兼容。
     * 3. 命中库位后分别回写普通物料游标或空托盘库区游标。
     *
     * WCS 传入的推荐排不再参与 run2 选位,避免上游 row 参数把任务重新绑回固定堆垛机。
     */
    public StartupDto getLocNoRun2(Integer whsType, Integer staDescId, Integer sourceStaNo, FindLocNoAttributeVo findLocNoAttributeVo, Integer moveCrnNo, LocTypeDto locTypeDto, List<Integer> recommendRows, int times) {
        int crnNo = 0;
        int nearRow = 0;
        int curRow = 0;
        int rowCount = 0;
        LocMast locMast = null;
        StartupDto startupDto = new StartupDto();
@@ -1303,42 +2205,25 @@
        if (Cools.isEmpty(rowLastnoType)) {
            throw new CoolException("数据异常,请联系管理员===》库位规则类型未知");
        }
        int crnNumber = rowLastno.getCrnQty();
        rowCount = crnNumber;
        curRow = rowLastno.getCurrentRow();
        int curRow = rowLastno.getCurrentRow() == null ? 0 : rowLastno.getCurrentRow();
        crnNo = resolveRun2CrnNo(rowLastno);
        Integer preferredArea = findLocNoAttributeVo.getOutArea();
        boolean emptyPalletRequest = isEmptyPalletRequest(staDescId, findLocNoAttributeVo);
        Run2AreaSearchResult emptyPalletAreaSearchResult = null;
        Run2SearchResult normalRun2SearchResult = null;
        List<Integer> orderedCrnNos = getOrderedCrnNos(rowLastno, crnNo);
        List<Integer> triedCrnNos = new ArrayList<>();
        List<Integer> recommendCrnNos = mapRowsToCrnNos(rowLastno, recommendRows);
        if (!Cools.isEmpty(recommendCrnNos)) {
            locMast = findRun2EmptyLocByCrnNos(rowLastno, rowLastnoType, recommendCrnNos, locTypeDto, staDescId, sourceStaNo, startupDto, preferredArea, "recommend");
            triedCrnNos.addAll(recommendCrnNos);
        }
        if (Cools.isEmpty(locMast)) {
            List<Map<String, Integer>> stationCrnLocTypes = Utils.getStationStorageAreaName(
                    sourceStaNo,
                    locTypeDto == null || locTypeDto.getLocType1() == null ? null : locTypeDto.getLocType1().intValue(),
                    findLocNoAttributeVo == null ? null : findLocNoAttributeVo.getMatnr());
            if (!Cools.isEmpty(stationCrnLocTypes)) {
                locMast = findRun2EmptyLocByCrnLocTypeEntries(rowLastno, rowLastnoType, stationCrnLocTypes,
                        locTypeDto, staDescId, sourceStaNo, startupDto, preferredArea, "station-priority");
            } else if (preferredArea == null) {
                List<Integer> defaultCrnNos = new ArrayList<>(orderedCrnNos);
                defaultCrnNos.removeAll(triedCrnNos);
                locMast = findRun2EmptyLocByCrnNos(rowLastno, rowLastnoType, defaultCrnNos, locTypeDto, staDescId, sourceStaNo, startupDto, preferredArea, "default");
            } else {
                List<Integer> preferredCrnNos = filterCrnNosByRows(rowLastno, orderedCrnNos, getRun2AreaRows(preferredArea, rowLastno));
                preferredCrnNos.removeAll(triedCrnNos);
                locMast = findRun2EmptyLocByCrnNos(rowLastno, rowLastnoType, preferredCrnNos, locTypeDto, staDescId, sourceStaNo, startupDto, preferredArea, "preferred-area");
                if (Cools.isEmpty(locMast)) {
                    List<Integer> fallbackCrnNos = filterCrnNosByRows(rowLastno, orderedCrnNos, getRun2FallbackRows(rowLastno));
                    fallbackCrnNos.removeAll(triedCrnNos);
                    fallbackCrnNos.removeAll(preferredCrnNos);
                    locMast = findRun2EmptyLocByCrnNos(rowLastno, rowLastnoType, fallbackCrnNos, locTypeDto, staDescId, sourceStaNo, startupDto, preferredArea, "fallback-area");
                }
        List<Integer> orderedRunnableCrnNos = getOrderedRunnableRun2CrnNos(rowLastno, staDescId, sourceStaNo, orderedCrnNos);
        if (emptyPalletRequest) {
            emptyPalletAreaSearchResult = findEmptyPalletRun2Loc(rowLastno, staDescId, sourceStaNo, startupDto, preferredArea, locTypeDto);
            if (!Cools.isEmpty(emptyPalletAreaSearchResult)) {
                locMast = emptyPalletAreaSearchResult.locMast;
            }
        } else {
            normalRun2SearchResult = findNormalRun2Loc(rowLastno, rowLastnoType, sourceStaNo, staDescId, findLocNoAttributeVo,
                    locTypeDto, startupDto, preferredArea, orderedCrnNos);
            if (normalRun2SearchResult != null) {
                locMast = normalRun2SearchResult.locMast;
            }
        }
@@ -1346,24 +2231,27 @@
            crnNo = locMast.getCrnNo();
            nearRow = locMast.getRow1();
        }
        if (curRow == 0) {
            curRow = rowLastno.getsRow() == null ? 1 : rowLastno.getsRow();
        if (emptyPalletRequest) {
            advanceEmptyPalletRun2Cursor(emptyPalletAreaSearchResult, locMast);
        } else if (!Cools.isEmpty(locMast)) {
            List<Integer> cursorCrnNos = normalRun2SearchResult == null || Cools.isEmpty(normalRun2SearchResult.runnableCrnNos)
                    ? orderedRunnableCrnNos
                    : normalRun2SearchResult.runnableCrnNos;
            advanceNormalRun2Cursor(rowLastno, curRow, cursorCrnNos, locMast.getCrnNo());
        }
        curRow = getNextRun2CurrentRow(rowLastno, curRow);
        rowLastno.setCurrentRow(curRow);
        rowLastnoService.updateById(rowLastno);
        if (Cools.isEmpty(locMast) || !locMast.getLocSts().equals("O")) {
            if (times < rowCount * 2) {
                times = times + 1;
                return getLocNoRun2(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, locTypeDto, recommendRows, times);
            if (emptyPalletRequest) {
                log.error("No empty location found. spec={}, preferredArea={}, nearRow={}",
                        JSON.toJSONString(locTypeDto), preferredArea, nearRow);
                throw new CoolException("没有空库位");
            }
            LocTypeDto compatibleLocTypeDto = buildUpwardCompatibleLocTypeDto(locTypeDto);
            LocTypeDto compatibleLocTypeDto = buildRetryCompatibleLocTypeDto(staDescId, findLocNoAttributeVo, locTypeDto);
            if (compatibleLocTypeDto != null) {
                log.warn("locType1 upward compatibility retry. source={}, target={}", JSON.toJSONString(locTypeDto), JSON.toJSONString(compatibleLocTypeDto));
                log.warn("locType compatibility retry. source={}, target={}", JSON.toJSONString(locTypeDto), JSON.toJSONString(compatibleLocTypeDto));
                return getLocNoRun2(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, compatibleLocTypeDto, recommendRows, 0);
            }
            log.error("No empty location found. spec={}, times={}, preferredArea={}, nearRow={}", JSON.toJSONString(locTypeDto), times, preferredArea, nearRow);
            log.error("No empty location found. spec={}, preferredArea={}, nearRow={}", JSON.toJSONString(locTypeDto), preferredArea, nearRow);
            throw new CoolException("没有空库位");
        }
@@ -1374,21 +2262,11 @@
        startupDto.setLocNo(locMast.getLocNo());
        return startupDto;
    }
    /**
     * 单伸堆垛机复用统一画像算法查询空库位。
     */
    private LocMast findSingleExtensionEmptyLoc(RowLastno rowLastno, int crnNo, int nearRow, RowLastnoType rowLastnoType, LocTypeDto locTypeDto) {
        for (Integer searchRow : getCrnSearchRows(rowLastno, crnNo, nearRow)) {
            List<LocMast> locMasts = locMastService.selectList(new EntityWrapper<LocMast>()
                    .eq("row1", searchRow)
                    .eq("loc_sts", "O")
                    .eq("whs_type", rowLastnoType.getType().longValue())
                    .orderBy("bay1", true)
                    .orderBy("lev1", true));
            for (LocMast locMast : locMasts) {
                if (VersionUtils.locMoveCheckLocTypeComplete(locMast, locTypeDto)) {
                    return locMast;
                }
            }
        }
        return null;
        return findConfiguredEmptyLocForCrn(rowLastno, rowLastnoType, crnNo, nearRow, locTypeDto);
    }
    public StartupDto getLocNoRun4(Integer whsType, Integer staDescId, Integer sourceStaNo, FindLocNoAttributeVo findLocNoAttributeVo, Integer moveCrnNo, LocTypeDto locTypeDto, int times) {
@@ -1411,7 +2289,7 @@
        }
        int sRow = rowLastno.getsRow();
        int eRow = rowLastno.geteRow();
        int crnNumber = rowLastno.getCrnQty();
        int crnNumber = resolveCrnCount(rowLastno);
        // ===============>>>> 开始执行
        curRow = rowLastno.getCurrentRow();
@@ -1821,9 +2699,9 @@
                times = times + 1;
                return getLocNoRun4(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, locTypeDto, times);
            }
            LocTypeDto compatibleLocTypeDto = buildUpwardCompatibleLocTypeDto(locTypeDto);
            LocTypeDto compatibleLocTypeDto = buildRetryCompatibleLocTypeDto(staDescId, findLocNoAttributeVo, locTypeDto);
            if (compatibleLocTypeDto != null) {
                log.warn("locType1 upward compatibility retry. source={}, target={}", JSON.toJSONString(locTypeDto), JSON.toJSONString(compatibleLocTypeDto));
                log.warn("locType compatibility retry. source={}, target={}", JSON.toJSONString(locTypeDto), JSON.toJSONString(compatibleLocTypeDto));
                return getLocNoRun4(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, compatibleLocTypeDto, 0);
            }
            log.error("No empty location found. spec={}, times={}", JSON.toJSONString(locTypeDto), times);
@@ -1842,6 +2720,7 @@
    }
    public StartupDto getLocNoRun5(Integer whsType, Integer staDescId, Integer sourceStaNo, FindLocNoAttributeVo findLocNoAttributeVo, Integer moveCrnNo, LocTypeDto locTypeDto, List<Integer> recommendRows, int times) {
        // WCS 传入的推荐排不再参与 AGV/平库选位,统一按库位排号自身轮询逻辑找位。
        // 初始化参数
        int crnNo = 0;      //堆垛机号
@@ -1912,20 +2791,6 @@
        // 开始查找库位 ==============================>>
        if (Cools.isEmpty(locMast) && !Cools.isEmpty(recommendRows)) {
            for (Integer recommendRow : recommendRows) {
                if (Cools.isEmpty(recommendRow)) {
                    continue;
                }
                LocMast recommendLoc = locMastService.queryFreeLocMast(recommendRow, locTypeDto.getLocType1(), rowLastnoType.getType().longValue());
                if (!Cools.isEmpty(recommendLoc) && VersionUtils.locMoveCheckLocTypeComplete(recommendLoc, locTypeDto)) {
                    locMast = recommendLoc;
                    crnNo = recommendLoc.getCrnNo();
                    break;
                }
            }
        }
        Integer preferredArea = findLocNoAttributeVo.getOutArea();
        if (Cools.isEmpty(locMast) && preferredArea == null) {
@@ -1968,9 +2833,9 @@
                times = times + 1;
                return getLocNoRun5(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, locTypeDto, recommendRows, times);
            }
            LocTypeDto compatibleLocTypeDto = buildUpwardCompatibleLocTypeDto(locTypeDto);
            LocTypeDto compatibleLocTypeDto = buildRetryCompatibleLocTypeDto(staDescId, findLocNoAttributeVo, locTypeDto);
            if (compatibleLocTypeDto != null) {
                log.warn("locType1 upward compatibility retry. source={}, target={}", JSON.toJSONString(locTypeDto), JSON.toJSONString(compatibleLocTypeDto));
                log.warn("locType compatibility retry. source={}, target={}", JSON.toJSONString(locTypeDto), JSON.toJSONString(compatibleLocTypeDto));
                return getLocNoRun5(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, compatibleLocTypeDto, recommendRows, 0);
            }
            log.error("No empty location found. spec={}, times={}", JSON.toJSONString(locTypeDto), times);