自动化立体仓库 - WMS系统
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
package com.zy.common.service;
 
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.core.common.Arith;
import com.core.common.Cools;
import com.core.exception.CoolException;
import com.zy.asrs.entity.*;
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.LocTypeDto;
import com.zy.common.model.Shelves;
import com.zy.common.model.StartupDto;
import com.zy.common.properties.SlaveProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
 
/**
 * 货架核心功能
 * Created by vincent on 2020/6/11
 */
@Slf4j
@Service
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;
        }
    }
 
    @Autowired
    private WrkMastService wrkMastService;
    @Autowired
    private WrkLastnoService wrkLastnoService;
    @Autowired
    private RowLastnoService rowLastnoService;
    @Autowired
    private RowLastnoTypeService rowLastnoTypeService;
    @Autowired
    private BasCrnpService basCrnpService;
    @Autowired
    private StaDescService staDescService;
    @Autowired
    private BasDevpService basDevpService;
    @Autowired
    private LocMastService locMastService;
    @Autowired
    private LocDetlService locDetlService;
    @Autowired
    private SlaveProperties slaveProperties;
    @Autowired
    private WrkDetlService wrkDetlService;
 
    /**
     * 生成工作号
     *
     * @param wrkMk
     * @return workNo(工作号)
     */
    public int getWorkNo(Integer wrkMk) {
        WrkLastno wrkLastno = wrkLastnoService.selectById(wrkMk);
        if (Cools.isEmpty(wrkLastno)) {
            throw new CoolException("数据异常,请联系管理员");
        }
 
        int workNo = wrkLastno.getWrkNo();
        int sNo = wrkLastno.getSNo();
        int eNo = wrkLastno.getENo();
        workNo = workNo >= eNo ? sNo : workNo + 1;
        while (true) {
            WrkMast wrkMast = wrkMastService.selectById(workNo);
            if (null != wrkMast) {
                workNo = workNo >= eNo ? sNo : workNo + 1;
            } else {
                break;
            }
        }
        // 修改序号记录
        if (workNo > 0) {
            wrkLastno.setWrkNo(workNo);
            wrkLastnoService.updateById(wrkLastno);
        }
        // 检验
        if (workNo == 0) {
            throw new CoolException("生成工作号失败,请联系管理员");
        } else {
            if (wrkMastService.selectById(workNo) != null) {
                throw new CoolException("生成工作号" + workNo + "在工作档中已存在");
            }
        }
        return workNo;
    }
 
    //拆盘机处空板扫码,驱动托盘向码垛位,不入库
    @Transactional
    public StartupDto getScanBarcodeEmptyBoard() {
        StartupDto startupDto = new StartupDto();
        Integer staNo = 0;
        if (wrkMastService.selectCount(new EntityWrapper<WrkMast>().eq("io_type", 201).eq("staNo", 216)) < 2) {
            staNo = 216;
        }
        if (wrkMastService.selectCount(new EntityWrapper<WrkMast>().eq("io_type", 201).eq("staNo", 220)) < 2) {
            staNo = 220;
        }
 
        startupDto.setStaNo(staNo);
        return startupDto;
    }
 
    /**
     * 检索库位号
     *
     * @param staDescId            路径ID
     * @param sourceStaNo          源站
     * @param findLocNoAttributeVo 属性
     * @param locTypeDto           类型
     * @return locNo 检索到的库位号
     */
    @Transactional
    public StartupDto getLocNo(Integer staDescId, Integer sourceStaNo, FindLocNoAttributeVo findLocNoAttributeVo, LocTypeDto locTypeDto) {
        return getLocNo(staDescId, sourceStaNo, findLocNoAttributeVo, locTypeDto, null);
    }
 
    @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());
            Integer preferredArea = resolvePreferredArea(sourceStaNo, findLocNoAttributeVo);
            if (preferredArea != null) {
                findLocNoAttributeVo.setOutArea(preferredArea);
            }
 
            /**
             * 库型 1: 标准堆垛机库  2: 平库  3: 穿梭板  4: 四向车  5: AGV  0: 未知
             */
            switch (rowLastnoType.getType()) {
                case 1:
                case 2:
                    return getLocNoRun2(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, 0, locTypeDto, recommendRows, 0);
                case 3:
                    return getLocNoRun(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, 0, locTypeDto, 0);
                case 4:
                    return getLocNoRun4(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, 4, locTypeDto, 0);
                case 5:
                    return getLocNoRun5(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, 0, locTypeDto, recommendRows, 0);
                default:
                    throw new CoolException("站点=" + sourceStaNo + " 未查询到对应的库位规则");
            }
        } catch (CoolException e) {
            log.error("站点={} 查找库位失败: {}", sourceStaNo, e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            log.error("站点={} 查找库位异常", sourceStaNo, e);
            throw new CoolException("站点=" + sourceStaNo + " 查找库位失败");
        }
    }
 
    /**
     * 空托盘识别规则:
     * 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,高低位都允许参与搜索。
     *
     * 这样做的原因是现场口径已经改成“先找窄库位”,而不是“先找低位窄库位”。
     * 因此这里会主动清空 locType1,防止被站点默认值带成低位优先。
     */
    private LocTypeDto normalizeLocTypeDto(Integer staDescId, FindLocNoAttributeVo findLocNoAttributeVo, LocTypeDto locTypeDto) {
        if (!isEmptyPalletRequest(staDescId, findLocNoAttributeVo)) {
            return locTypeDto;
        }
        if (findLocNoAttributeVo != null && Cools.isEmpty(findLocNoAttributeVo.getMatnr())) {
            findLocNoAttributeVo.setMatnr("emptyPallet");
        }
        LocTypeDto normalizedLocTypeDto = locTypeDto == null ? new LocTypeDto() : locTypeDto;
        // 空托盘首轮不限制高低位,只保留“窄库位优先”的约束。
        normalizedLocTypeDto.setLocType1(null);
        normalizedLocTypeDto.setLocType2((short) 1);
        return normalizedLocTypeDto;
    }
 
    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 (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());
        if (stationArea != null) {
            return stationArea;
        }
        Integer requestArea = findLocNoAttributeVo.getOutArea();
        if (requestArea != null && requestArea >= 1 && requestArea <= 3) {
            return requestArea;
        }
        return null;
    }
 
    private Integer parseArea(String area) {
        if (Cools.isEmpty(area)) {
            return null;
        }
        String normalized = area.trim();
        if (normalized.isEmpty()) {
            return null;
        }
        try {
            int areaNo = Integer.parseInt(normalized);
            return areaNo >= 1 && areaNo <= 3 ? areaNo : null;
        } catch (NumberFormatException ignored) {
        }
        String upper = normalized.toUpperCase(Locale.ROOT);
        if ("A".equals(upper) || "A区".equals(upper) || "A库".equals(upper) || "A库区".equals(upper)) {
            return 1;
        }
        if ("B".equals(upper) || "B区".equals(upper) || "B库".equals(upper) || "B库区".equals(upper)) {
            return 2;
        }
        if ("C".equals(upper) || "C区".equals(upper) || "C库".equals(upper) || "C库区".equals(upper)) {
            return 3;
        }
        return null;
    }
 
    private String getAgvAreaRowsConfig(Integer area) {
        Parameter parameter = Parameter.get();
        if (parameter == null || area == null) {
            return null;
        }
        switch (area) {
            case 1:
                return parameter.getAgvArea1Rows();
            case 2:
                return parameter.getAgvArea2Rows();
            case 3:
                return parameter.getAgvArea3Rows();
            default:
                return null;
        }
    }
 
    private List<Integer> getAgvAreaRows(Integer area, RowLastno rowLastno) {
        List<Integer> configuredRows = parseAgvRows(getAgvAreaRowsConfig(area), rowLastno);
        if (!configuredRows.isEmpty()) {
            return configuredRows;
        }
        return getLegacyAgvRows(rowLastno);
    }
 
    private List<Integer> getAgvFallbackRows(RowLastno rowLastno) {
        LinkedHashSet<Integer> rows = new LinkedHashSet<>();
        for (int area = 1; area <= 3; area++) {
            rows.addAll(parseAgvRows(getAgvAreaRowsConfig(area), rowLastno));
        }
        rows.addAll(getLegacyAgvRows(rowLastno));
        return new ArrayList<>(rows);
    }
 
    private List<Integer> parseAgvRows(String configValue, RowLastno rowLastno) {
        List<Integer> rows = new ArrayList<>();
        if (rowLastno == null || Cools.isEmpty(configValue)) {
            return rows;
        }
        LinkedHashSet<Integer> orderedRows = new LinkedHashSet<>();
        String normalized = configValue.replace(",", ",")
                .replace(";", ";")
                .replace("、", ",")
                .replaceAll("\\s+", "");
        if (normalized.isEmpty()) {
            return rows;
        }
        for (String segment : normalized.split("[,;]")) {
            if (segment == null || segment.isEmpty()) {
                continue;
            }
            if (segment.contains("-")) {
                String[] rangeParts = segment.split("-", 2);
                Integer startRow = safeParseInt(rangeParts[0]);
                Integer endRow = safeParseInt(rangeParts[1]);
                if (startRow == null || endRow == null) {
                    continue;
                }
                int step = startRow <= endRow ? 1 : -1;
                for (int row = startRow; step > 0 ? row <= endRow : row >= endRow; row += step) {
                    addAgvRow(orderedRows, row, rowLastno);
                }
                continue;
            }
            addAgvRow(orderedRows, safeParseInt(segment), rowLastno);
        }
        rows.addAll(orderedRows);
        return rows;
    }
 
    private List<Integer> getLegacyAgvRows(RowLastno rowLastno) {
        List<Integer> rows = new ArrayList<>();
        if (rowLastno == null) {
            return rows;
        }
        LinkedHashSet<Integer> orderedRows = new LinkedHashSet<>();
        int startRow = Math.min(38, rowLastno.geteRow());
        int endRow = Math.max(32, rowLastno.getsRow());
        if (startRow >= endRow) {
            for (int row = startRow; row >= endRow; row--) {
                addAgvRow(orderedRows, row, rowLastno);
            }
        } else {
            for (int row = rowLastno.geteRow(); row >= rowLastno.getsRow(); row--) {
                addAgvRow(orderedRows, row, rowLastno);
            }
        }
        rows.addAll(orderedRows);
        return rows;
    }
 
    private void addAgvRow(LinkedHashSet<Integer> rows, Integer row, RowLastno rowLastno) {
        if (rows == null || row == null || rowLastno == null) {
            return;
        }
        if (row < rowLastno.getsRow() || row > rowLastno.geteRow()) {
            return;
        }
        rows.add(row);
    }
 
    private Integer safeParseInt(String value) {
        if (Cools.isEmpty(value)) {
            return null;
        }
        try {
            return Integer.parseInt(value.trim());
        } catch (NumberFormatException ignored) {
            return null;
        }
    }
 
    private int[] getAgvAreaBayRange(Integer area) {
        if (area == null) {
            return new int[]{1, 19};
        }
        switch (area) {
            case 1:
                return new int[]{1, 12};
            case 2:
                return new int[]{13, 36};
            case 3:
                return new int[]{37, 56};
            default:
                return new int[]{1, 56};
        }
    }
 
    private LocMast findAgvLocByRows(RowLastno rowLastno, RowLastnoType rowLastnoType, List<Integer> rows,
                                     int startBay, int endBay, int curRow, int nearRow,
                                     LocTypeDto locTypeDto, boolean useDeepCheck) {
        for (Integer row : rows) {
            if (row == null) {
                continue;
            }
            Wrapper<LocMast> wrapper = new EntityWrapper<LocMast>()
                    .eq("row1", row)
                    .ge("bay1", startBay)
                    .le("bay1", endBay)
                    .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;
                }
                if (useDeepCheck) {
                    if (!Utils.BooleanWhsTypeStaIoType(rowLastno)) {
                        continue;
                    }
                    LocMast deepLoc = locMastService.selectLocByLocStsPakInO(curRow, nearRow, candidate, rowLastnoType.getType().longValue());
                    if (!Cools.isEmpty(deepLoc) && deepLoc.getRow1() == curRow) {
                        return deepLoc;
                    }
                    continue;
                }
                return candidate;
            }
        }
        return null;
    }
    private String getRun2AreaRowsConfig(Integer area) {
        Parameter parameter = Parameter.get();
        if (parameter == null || area == null) {
            return null;
        }
        String run2Config;
        switch (area) {
            case 1:
                run2Config = parameter.getRun2Area1Rows();
                break;
            case 2:
                run2Config = parameter.getRun2Area2Rows();
                break;
            case 3:
                run2Config = parameter.getRun2Area3Rows();
                break;
            default:
                return null;
        }
        return Cools.isEmpty(run2Config) ? getAgvAreaRowsConfig(area) : run2Config;
    }
 
    private List<Integer> getRun2AreaRows(Integer area, RowLastno rowLastno) {
        List<Integer> configuredRows = parseAgvRows(getRun2AreaRowsConfig(area), rowLastno);
        if (!configuredRows.isEmpty()) {
            return configuredRows;
        }
        return getLegacyAgvRows(rowLastno);
    }
 
    private List<Integer> getRun2FallbackRows(RowLastno rowLastno) {
        LinkedHashSet<Integer> rows = new LinkedHashSet<>();
        for (int area = 1; area <= 3; area++) {
            rows.addAll(parseAgvRows(getRun2AreaRowsConfig(area), rowLastno));
        }
        rows.addAll(getLegacyAgvRows(rowLastno));
        return new ArrayList<>(rows);
    }
 
    private Integer resolveRun2CrnNo(RowLastno rowLastno) {
        if (rowLastno == null) {
            return null;
        }
        Integer currentRow = rowLastno.getCurrentRow();
        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) {
            return startCrnNo;
        }
        int offset = Math.max(currentRow - startRow, 0) / rowSpan;
        int crnNo = startCrnNo + offset;
        Integer endCrnNo = rowLastno.geteCrnNo();
        if (endCrnNo != null && crnNo > endCrnNo) {
            return startCrnNo;
        }
        return crnNo;
    }
 
    private int getNextRun2CurrentRow(RowLastno rowLastno, int currentRow) {
        Integer rowSpan = getCrnRowSpan(rowLastno.getTypeId());
        if (rowSpan == null || rowSpan <= 0) {
            rowSpan = 2;
        }
        int startRow = rowLastno.getsRow() == null ? 1 : rowLastno.getsRow();
        int endRow = rowLastno.geteRow() == null ? currentRow : rowLastno.geteRow();
        int lastStartRow = Math.max(startRow, endRow - rowSpan + 1);
        if (currentRow >= lastStartRow) {
            return startRow;
        }
        return currentRow + rowSpan;
    }
 
    private List<Integer> getOrderedCrnNos(RowLastno rowLastno, Integer startCrnNo) {
        List<Integer> orderedCrnNos = new ArrayList<>();
        if (rowLastno == null) {
            return orderedCrnNos;
        }
        int start = rowLastno.getsCrnNo() == null ? 1 : rowLastno.getsCrnNo();
        int end = rowLastno.geteCrnNo() == null ? start + rowLastno.getCrnQty() - 1 : rowLastno.geteCrnNo();
        int first = startCrnNo == null ? start : startCrnNo;
        if (first < start || first > end) {
            first = start;
        }
        for (int crnNo = first; crnNo <= end; crnNo++) {
            orderedCrnNos.add(crnNo);
        }
        for (int crnNo = start; crnNo < first; crnNo++) {
            orderedCrnNos.add(crnNo);
        }
        return orderedCrnNos;
    }
 
    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;
    }
 
    /**
     * 判断某台堆垛机是否可以参与 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 (crnNo == null) {
            return false;
        }
        BasCrnp basCrnp = basCrnpService.selectById(crnNo);
        if (Cools.isEmpty(basCrnp)) {
            return false;
        }
        if (!"Y".equals(basCrnp.getInEnable())) {
            return false;
        }
        if (basCrnp.getCrnSts() != null && basCrnp.getCrnSts() != 3) {
            return false;
        }
        if (basCrnp.getCrnErr() != null && basCrnp.getCrnErr() != 0) {
            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));
        if (Cools.isEmpty(staDesc)) {
            return false;
        }
        BasDevp targetSta = basDevpService.selectById(staDesc.getCrnStn());
        return !Cools.isEmpty(targetSta) && "Y".equals(targetSta.getAutoing());
    }
 
    /**
     * 按既定轮询顺序过滤出真正可参与本次找位的堆垛机列表。
     */
    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 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);
    }
 
    /**
     * 根据库区取该库区对应的轮询记录。
     * 当前库里 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. 先按站点绑定库区找 loc_type2=1。
     * 2. 当前库区没有,再按其它库区继续找 loc_type2=1。
     * 3. 每个库区内部都按该库区自己的 rowLastno/currentRow 做轮询均分。
     *
     * 这里故意不复用普通 run2 的“推荐排 -> 当前库区排 -> 其它排”逻辑,
     * 因为空托盘的业务口径已经切换成“按库区找堆垛机”,不是按推荐排找巷道。
     */
    private Run2AreaSearchResult findEmptyPalletRun2AreaLoc(RowLastno defaultRowLastno, Integer staDescId, Integer sourceStaNo,
                                                            StartupDto startupDto, Integer preferredArea, LocTypeDto locTypeDto) {
        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);
            List<Integer> candidateCrnNos = Cools.isEmpty(runnableAreaCrnNos) ? orderedAreaCrnNos : runnableAreaCrnNos;
            if (Cools.isEmpty(candidateCrnNos)) {
                continue;
            }
            LocMast locMast = findRun2EmptyLocByCrnNos(areaRowLastno, areaRowLastnoType, candidateCrnNos, locTypeDto,
                    staDescId, sourceStaNo, startupDto, area, "empty-pallet-area-" + area, false);
            if (!Cools.isEmpty(locMast)) {
                return new Run2AreaSearchResult(locMast, areaRowLastno, candidateCrnNos);
            }
        }
        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 updateCurRow = updateRowLastno.getCurrentRow() == null || updateRowLastno.getCurrentRow() == 0
                ? (updateRowLastno.getsRow() == null ? 1 : updateRowLastno.getsRow())
                : updateRowLastno.getCurrentRow();
        updateCurRow = getNextRun2CurrentRow(updateRowLastno, searchResult.runnableCrnNos, locMast.getCrnNo(), updateCurRow);
        updateRowLastno.setCurrentRow(updateCurRow);
        rowLastnoService.updateById(updateRowLastno);
    }
 
    /**
     * 普通 run2 的推荐排优先阶段。
     *
     * 推荐排只对普通物料生效,空托盘已经切换成“按库区轮询堆垛机”的规则,
     * 因此这里会直接跳过空托盘请求,避免 row 参数把空托盘重新带回旧逻辑。
     */
    private LocMast findRun2RecommendLoc(RowLastno rowLastno, RowLastnoType rowLastnoType, boolean emptyPalletRequest,
                                         List<Integer> recommendRows, LocTypeDto locTypeDto, Integer staDescId,
                                         Integer sourceStaNo, StartupDto startupDto, Integer preferredArea,
                                         List<Integer> triedCrnNos) {
        if (emptyPalletRequest) {
            return null;
        }
        List<Integer> recommendCrnNos = mapRowsToCrnNos(rowLastno, recommendRows);
        if (Cools.isEmpty(recommendCrnNos)) {
            return null;
        }
        LocMast locMast = findRun2EmptyLocByCrnNos(rowLastno, rowLastnoType, recommendCrnNos, locTypeDto,
                staDescId, sourceStaNo, startupDto, preferredArea, "recommend");
        triedCrnNos.addAll(recommendCrnNos);
        return locMast;
    }
 
    /**
     * 普通物料 run2 找位主流程。
     *
     * 执行顺序:
     * 1. 先看站点是否配置了“堆垛机 + 库位类型”优先级。
     * 2. 没配库区时,直接按当前 run2 轮询顺序找位。
     * 3. 配了库区时,先在当前库区找,再回退到其它库区。
     */
    private LocMast findNormalRun2Loc(RowLastno rowLastno, RowLastnoType rowLastnoType, Integer sourceStaNo,
                                      Integer staDescId, FindLocNoAttributeVo findLocNoAttributeVo, LocTypeDto locTypeDto,
                                      StartupDto startupDto, Integer preferredArea, List<Integer> orderedCrnNos,
                                      List<Integer> triedCrnNos) {
        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)) {
            return findRun2EmptyLocByCrnLocTypeEntries(rowLastno, rowLastnoType, stationCrnLocTypes,
                    locTypeDto, staDescId, sourceStaNo, startupDto, preferredArea, "station-priority");
        }
        if (preferredArea == null) {
            List<Integer> defaultCrnNos = new ArrayList<>(orderedCrnNos);
            defaultCrnNos.removeAll(triedCrnNos);
            return findRun2EmptyLocByCrnNos(rowLastno, rowLastnoType, defaultCrnNos, locTypeDto,
                    staDescId, sourceStaNo, startupDto, preferredArea, "default");
        }
        List<Integer> preferredCrnNos = filterCrnNosByRows(rowLastno, orderedCrnNos, getRun2AreaRows(preferredArea, rowLastno));
        preferredCrnNos.removeAll(triedCrnNos);
        LocMast locMast = findRun2EmptyLocByCrnNos(rowLastno, rowLastnoType, preferredCrnNos, locTypeDto,
                staDescId, sourceStaNo, startupDto, preferredArea, "preferred-area");
        if (!Cools.isEmpty(locMast)) {
            return locMast;
        }
        List<Integer> fallbackCrnNos = filterCrnNosByRows(rowLastno, orderedCrnNos, getRun2FallbackRows(rowLastno));
        fallbackCrnNos.removeAll(triedCrnNos);
        fallbackCrnNos.removeAll(preferredCrnNos);
        return findRun2EmptyLocByCrnNos(rowLastno, rowLastnoType, fallbackCrnNos, locTypeDto,
                staDescId, sourceStaNo, startupDto, preferredArea, "fallback-area");
    }
 
    /**
     * 普通物料命中库位后,沿用 run2 原有的全仓轮询游标推进方式。
     */
    private void advanceNormalRun2Cursor(RowLastno rowLastno, int curRow) {
        if (rowLastno == null) {
            return;
        }
        int updateCurRow = curRow == 0 ? (rowLastno.getsRow() == null ? 1 : rowLastno.getsRow()) : curRow;
        updateCurRow = getNextRun2CurrentRow(rowLastno, updateCurRow);
        rowLastno.setCurrentRow(updateCurRow);
        rowLastnoService.updateById(rowLastno);
    }
 
    private List<Integer> filterCrnNosByRows(RowLastno rowLastno, List<Integer> orderedCrnNos, List<Integer> rows) {
        if (Cools.isEmpty(rows)) {
            return new ArrayList<>(orderedCrnNos);
        }
        LinkedHashSet<Integer> rowSet = new LinkedHashSet<>(rows);
        List<Integer> result = new ArrayList<>();
        Integer rowSpan = getCrnRowSpan(rowLastno.getTypeId());
        if (rowSpan == null || rowSpan <= 0) {
            rowSpan = 2;
        }
        int startCrnNo = rowLastno.getsCrnNo() == null ? 1 : rowLastno.getsCrnNo();
        int startRow = rowLastno.getsRow() == null ? 1 : rowLastno.getsRow();
        int endRow = rowLastno.geteRow() == null ? Integer.MAX_VALUE : rowLastno.geteRow();
        for (Integer crnNo : orderedCrnNos) {
            if (crnNo == null || crnNo < startCrnNo) {
                continue;
            }
            int crnOffset = crnNo - startCrnNo;
            int crnStartRow = startRow + crnOffset * rowSpan;
            for (int row = crnStartRow; row < crnStartRow + rowSpan && row <= endRow; row++) {
                if (rowSet.contains(row)) {
                    result.add(crnNo);
                    break;
                }
            }
        }
        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;
        }
        StaDesc staDesc = staDescService.selectOne(new EntityWrapper<StaDesc>()
                .eq("type_no", staDescId)
                .eq("stn_no", sourceStaNo)
                .eq("crn_no", crnNo));
        if (Cools.isEmpty(staDesc)) {
            log.error("type_no={},stn_no={},crn_no={}", staDescId, sourceStaNo, crnNo);
            return null;
        }
        BasDevp staNo = basDevpService.selectById(staDesc.getCrnStn());
        if (Cools.isEmpty(staNo) || !"Y".equals(staNo.getAutoing())) {
            log.error("目标站{}不可用", staDesc.getCrnStn());
            return null;
        }
        return staNo.getDevNo();
    }
 
    private void logRun2NoMatch(String stage, Integer sourceStaNo, Integer preferredArea, List<Integer> candidateCrnNos,
                                LocTypeDto locTypeDto, List<Integer> crnErrorCrns, List<Integer> routeBlockedCrns,
                                List<Integer> noEmptyCrns, List<Integer> locTypeBlockedCrns) {
        log.warn("run2 no location. stage={}, sourceStaNo={}, preferredArea={}, candidateCrnNos={}, crnErrorCrns={}, routeBlockedCrns={}, noEmptyCrns={}, locTypeBlockedCrns={}, spec={}",
                stage, sourceStaNo, preferredArea, candidateCrnNos, crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns,
                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));
            return null;
        }
        List<Integer> crnErrorCrns = new ArrayList<>();
        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 (routeRequired && Utils.BooleanWhsTypeSta(rowLastno, staDescId) && targetStaNo == null) {
                routeBlockedCrns.add(candidateCrnNo);
                continue;
            }
            Wrapper<LocMast> openWrapper = new EntityWrapper<LocMast>()
                    .eq("crn_no", candidateCrnNo)
                    .eq("loc_sts", "O");
            applyLocTypeFilters(openWrapper, locTypeDto, true);
            openWrapper.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");
            applyLocTypeFilters(wrapper, locTypeDto, true);
            wrapper.orderBy("lev1").orderBy("bay1");
            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;
    }
    private LocMast findRun2EmptyLocByCrnLocTypeEntries(RowLastno rowLastno, RowLastnoType rowLastnoType,
                                                        List<Map<String, Integer>> crnLocTypeEntries, LocTypeDto locTypeDto,
                                                        Integer staDescId, Integer sourceStaNo, StartupDto startupDto,
                                                        Integer preferredArea, String stage) {
        if (Cools.isEmpty(crnLocTypeEntries)) {
            log.warn("run2 skip empty crn-locType list. stage={}, sourceStaNo={}, preferredArea={}, spec={}",
                    stage, sourceStaNo, preferredArea, JSON.toJSONString(locTypeDto));
            return null;
        }
        List<Integer> candidateCrnNos = extractCrnNos(crnLocTypeEntries);
        List<Integer> crnErrorCrns = new ArrayList<>();
        List<Integer> routeBlockedCrns = new ArrayList<>();
        List<Integer> noEmptyCrns = new ArrayList<>();
        List<Integer> locTypeBlockedCrns = new ArrayList<>();
        return findRun2EmptyLocByCrnLocTypeEntriesRecursively(rowLastno, rowLastnoType, crnLocTypeEntries, locTypeDto,
                staDescId, sourceStaNo, startupDto, preferredArea, stage, 0, candidateCrnNos,
                crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
    }
 
    private LocMast findRun2EmptyLocByCrnLocTypeEntriesRecursively(RowLastno rowLastno, RowLastnoType rowLastnoType,
                                                                   List<Map<String, Integer>> crnLocTypeEntries, LocTypeDto locTypeDto,
                                                                   Integer staDescId, Integer sourceStaNo, StartupDto startupDto,
                                                                   Integer preferredArea, String stage, int index,
                                                                   List<Integer> candidateCrnNos, List<Integer> crnErrorCrns,
                                                                   List<Integer> routeBlockedCrns, List<Integer> noEmptyCrns,
                                                                   List<Integer> locTypeBlockedCrns) {
        if (index >= crnLocTypeEntries.size()) {
            logRun2NoMatch(stage, sourceStaNo, preferredArea, candidateCrnNos, locTypeDto, crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
            return null;
        }
        Map<String, Integer> crnLocTypeEntry = crnLocTypeEntries.get(index);
        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)) {
            crnErrorCrns.add(candidateCrnNo);
            return findRun2EmptyLocByCrnLocTypeEntriesRecursively(rowLastno, rowLastnoType, crnLocTypeEntries, locTypeDto,
                    staDescId, sourceStaNo, startupDto, preferredArea, stage, index + 1, candidateCrnNos,
                    crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
        }
        Integer targetStaNo = resolveTargetStaNo(rowLastno, staDescId, sourceStaNo, candidateCrnNo);
        if (Utils.BooleanWhsTypeSta(rowLastno, staDescId) && targetStaNo == null) {
            routeBlockedCrns.add(candidateCrnNo);
            return findRun2EmptyLocByCrnLocTypeEntriesRecursively(rowLastno, rowLastnoType, crnLocTypeEntries, locTypeDto,
                    staDescId, sourceStaNo, startupDto, preferredArea, stage, index + 1, candidateCrnNos,
                    crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
        }
        LocTypeDto searchLocTypeDto = buildRun2SearchLocTypeDto(locTypeDto, candidateLocType1);
        LocMast candidateLoc = findRun2OrderedEmptyLocByCrnLocType(rowLastnoType, candidateCrnNo, candidateLocType1, 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);
            return findRun2EmptyLocByCrnLocTypeEntriesRecursively(rowLastno, rowLastnoType, crnLocTypeEntries, locTypeDto,
                    staDescId, sourceStaNo, startupDto, preferredArea, stage, index + 1, candidateCrnNos,
                    crnErrorCrns, routeBlockedCrns, noEmptyCrns, locTypeBlockedCrns);
        }
        if (targetStaNo != null) {
            startupDto.setStaNo(targetStaNo);
        }
        return candidateLoc;
    }
 
    private List<Integer> extractCrnNos(List<Map<String, Integer>> crnLocTypeEntries) {
        LinkedHashSet<Integer> orderedCrnNos = new LinkedHashSet<>();
        if (Cools.isEmpty(crnLocTypeEntries)) {
            return new ArrayList<>();
        }
        for (Map<String, Integer> crnLocTypeEntry : crnLocTypeEntries) {
            if (crnLocTypeEntry == null || crnLocTypeEntry.get("crnNo") == null) {
                continue;
            }
            orderedCrnNos.add(crnLocTypeEntry.get("crnNo"));
        }
        return new ArrayList<>(orderedCrnNos);
    }
 
    private LocTypeDto buildRun2SearchLocTypeDto(LocTypeDto locTypeDto, Short candidateLocType1) {
        if (locTypeDto == null && candidateLocType1 == null) {
            return null;
        }
        LocTypeDto searchLocTypeDto = new LocTypeDto();
        if (locTypeDto != null) {
            searchLocTypeDto.setLocType1(locTypeDto.getLocType1());
            searchLocTypeDto.setLocType2(locTypeDto.getLocType2());
            searchLocTypeDto.setLocType3(locTypeDto.getLocType3());
            searchLocTypeDto.setSiteId(locTypeDto.getSiteId());
        }
        if (candidateLocType1 != null) {
            searchLocTypeDto.setLocType1(candidateLocType1);
        }
        return searchLocTypeDto;
    }
 
    private LocMast findRun2OrderedEmptyLocByCrnLocType(RowLastnoType rowLastnoType, Integer candidateCrnNo,
                                                        Short candidateLocType1, LocTypeDto locTypeDto) {
        if (candidateCrnNo == null) {
            return null;
        }
        Wrapper<LocMast> wrapper = new EntityWrapper<LocMast>()
                .eq("crn_no", candidateCrnNo)
                .eq("loc_sts", "O");
        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);
        } else {
            wrapper.orderBy("lev1", true).orderBy("bay1", true);
        }
        LocMast candidateLoc = locMastService.selectOne(wrapper);
        if (Cools.isEmpty(candidateLoc)) {
            return null;
        }
        if (locTypeDto != null && !VersionUtils.locMoveCheckLocTypeComplete(candidateLoc, locTypeDto)) {
            return null;
        }
        return candidateLoc;
    }
 
    private Optional<CrnRowInfo> findAvailableCrnAndNearRow(RowLastno rowLastno, int curRow, int crnNumber, int times,
                                                            FindLocNoAttributeVo findLocNoAttributeVo, LocTypeDto locTypeDto,
                                                            RowLastnoType rowLastnoType) {
        int attempt = times;
        while (attempt < crnNumber * 4) {
            int[] params = Utils.LocNecessaryParameters(rowLastno, curRow, crnNumber);
            curRow = params[1];
            int crnNo = params[2];
//            if (!basCrnpService.checkSiteError(crnNo, true)) {
//                attempt++;
//                continue;
//            }
            int rowCount = params[0];
            int nearRow = params[3];
 
            // 只取数量判断,避免拉整 list
            int availableLocCount = locMastService.selectCount(new EntityWrapper<LocMast>()
                    .eq("row1", nearRow)
                    .eq("loc_sts", "O")
                    .eq("whs_type", 1));
            int crnCountO = wrkMastService.selectCount(new EntityWrapper<WrkMast>()
                    .eq("crn_no", crnNo).le("io_type", 100));
            if (availableLocCount - crnCountO <= 2) { // 可以提成常量,比如 MIN_SPARE_SLOTS = 2
                log.error("{}号堆垛机没有空库位!!! 尺寸规格: {}, 轮询次数:{}", crnNo, JSON.toJSONString(locTypeDto), attempt);
                attempt++;
                continue;
            }
            return Optional.of(new CrnRowInfo(crnNo, nearRow, curRow, rowCount, attempt));
        }
        return Optional.empty();
    }
 
    private Optional<CrnRowInfo> findBalancedCrnAndNearRow(RowLastno rowLastno, int curRow, int crnNumber, int times,
                                                           FindLocNoAttributeVo findLocNoAttributeVo, LocTypeDto locTypeDto,
                                                           RowLastnoType rowLastnoType) {
        int maxScanTimes = Math.max(crnNumber * 2, 1);
        int scanCurRow = curRow;
        Map<Integer, Integer> availableLocCountCache = new HashMap<>();
        Map<Integer, Integer> crnTaskCountCache = new HashMap<>();
 
        CrnRowInfo bestInfo = null;
        int bestTaskCount = Integer.MAX_VALUE;
        int bestSpareLocCount = Integer.MIN_VALUE;
        int bestOffset = Integer.MAX_VALUE;
        CrnRowInfo fallbackInfo = null;
        int fallbackTaskCount = Integer.MAX_VALUE;
        int fallbackAvailableLocCount = Integer.MIN_VALUE;
        int fallbackOffset = Integer.MAX_VALUE;
 
        for (int attempt = 0; attempt < maxScanTimes; attempt++) {
            int[] params = Utils.LocNecessaryParameters(rowLastno, scanCurRow, crnNumber);
            scanCurRow = params[1];
            int rowCount = params[0];
            int crnNo = params[2];
            int nearRow = params[3];
 
            if (attempt < times) {
                continue;
            }
 
            int availableLocCount = availableLocCountCache.computeIfAbsent(crnNo, key ->
                    countAvailableLocForCrn(rowLastno, rowLastnoType, key, nearRow));
            int crnTaskCount = crnTaskCountCache.computeIfAbsent(crnNo, key ->
                    wrkMastService.selectCount(new EntityWrapper<WrkMast>()
                            .eq("crn_no", key)
                            .le("io_type", 100)));
            int spareLocCount = availableLocCount - crnTaskCount;
            int offset = attempt - times;
 
            if (availableLocCount > 0 && isBetterCrnCandidate(crnTaskCount, availableLocCount, offset,
                    fallbackTaskCount, fallbackAvailableLocCount, fallbackOffset)) {
                fallbackInfo = new CrnRowInfo(crnNo, nearRow, scanCurRow, rowCount, attempt);
                fallbackTaskCount = crnTaskCount;
                fallbackAvailableLocCount = availableLocCount;
                fallbackOffset = offset;
            }
 
            if (spareLocCount <= MIN_SPARE_LOC_COUNT) {
                log.warn("{}号堆垛机可用空库位余量不足,降级候选继续保留。尺寸规格:{},轮询次数:{}", crnNo, JSON.toJSONString(locTypeDto), attempt);
                continue;
            }
 
            if (isBetterCrnCandidate(crnTaskCount, spareLocCount, offset, bestTaskCount, bestSpareLocCount, bestOffset)) {
                bestInfo = new CrnRowInfo(crnNo, nearRow, scanCurRow, rowCount, attempt);
                bestTaskCount = crnTaskCount;
                bestSpareLocCount = spareLocCount;
                bestOffset = offset;
            }
        }
        if (bestInfo != null) {
            return Optional.of(bestInfo);
        }
        if (fallbackInfo != null) {
            log.warn("堆垛机均衡分配未找到满足余量阈值的候选,降级使用仍有空位的堆垛机: crnNo={}", fallbackInfo.getCrnNo());
        }
        return Optional.ofNullable(fallbackInfo);
    }
 
    private boolean isBetterCrnCandidate(int taskCount, int spareLocCount, int offset,
                                         int bestTaskCount, int bestSpareLocCount, int bestOffset) {
        if (taskCount != bestTaskCount) {
            return taskCount < bestTaskCount;
        }
        if (spareLocCount != bestSpareLocCount) {
            return spareLocCount > bestSpareLocCount;
        }
        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;
        }
        return locMastService.selectCount(new EntityWrapper<LocMast>()
                .in("row1", searchRows)
                .eq("loc_sts", "O")
                .eq("whs_type", rowLastnoType.getType().longValue()));
    }
 
    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;
        }
        Wrapper<LocMast> wrapper = new EntityWrapper<LocMast>()
                .in("row1", searchRows)
                .eq("loc_sts", "O");
        applyLocTypeFilters(wrapper, locTypeDto, true);
        return locMastService.selectCount(wrapper);
    }
 
    private Optional<CrnRowInfo> findBalancedSingleExtensionCrnAndNearRow(RowLastno rowLastno, int curRow, int crnNumber, int times,
                                                                           LocTypeDto locTypeDto, RowLastnoType rowLastnoType) {
        int maxScanTimes = Math.max(crnNumber * 2, 1);
        int scanCurRow = curRow;
        Map<Integer, Integer> availableLocCountCache = new HashMap<>();
        Map<Integer, Integer> crnTaskCountCache = new HashMap<>();
 
        CrnRowInfo bestInfo = null;
        int bestTaskCount = Integer.MAX_VALUE;
        int bestSpareLocCount = Integer.MIN_VALUE;
        int bestOffset = Integer.MAX_VALUE;
        CrnRowInfo fallbackInfo = null;
        int fallbackTaskCount = Integer.MAX_VALUE;
        int fallbackAvailableLocCount = Integer.MIN_VALUE;
        int fallbackOffset = Integer.MAX_VALUE;
 
        for (int attempt = 0; attempt < maxScanTimes; attempt++) {
            int[] params = Utils.LocNecessaryParameters(rowLastno, scanCurRow, crnNumber);
            scanCurRow = params[1];
            int rowCount = params[0];
            int crnNo = params[2];
            int nearRow = params[3];
 
            if (attempt < times) {
                continue;
            }
 
            int availableLocCount = availableLocCountCache.computeIfAbsent(crnNo, key ->
                    countAvailableSingleExtensionLocForCrn(rowLastno, rowLastnoType, key, nearRow, locTypeDto));
            int crnTaskCount = crnTaskCountCache.computeIfAbsent(crnNo, key ->
                    wrkMastService.selectCount(new EntityWrapper<WrkMast>()
                            .eq("crn_no", key)
                            .le("io_type", 100)));
            int spareLocCount = availableLocCount - crnTaskCount;
            int offset = attempt - times;
 
            if (availableLocCount > 0 && isBetterCrnCandidate(crnTaskCount, availableLocCount, offset,
                    fallbackTaskCount, fallbackAvailableLocCount, fallbackOffset)) {
                fallbackInfo = new CrnRowInfo(crnNo, nearRow, scanCurRow, rowCount, attempt);
                fallbackTaskCount = crnTaskCount;
                fallbackAvailableLocCount = availableLocCount;
                fallbackOffset = offset;
            }
 
            if (spareLocCount <= MIN_SPARE_LOC_COUNT) {
                continue;
            }
 
            if (isBetterCrnCandidate(crnTaskCount, spareLocCount, offset, bestTaskCount, bestSpareLocCount, bestOffset)) {
                bestInfo = new CrnRowInfo(crnNo, nearRow, scanCurRow, rowCount, attempt);
                bestTaskCount = crnTaskCount;
                bestSpareLocCount = spareLocCount;
                bestOffset = offset;
            }
        }
        if (bestInfo != null) {
            return Optional.of(bestInfo);
        }
        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;
        }
 
        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;
    }
 
    private Integer getCrnRowSpan(Integer typeId) {
        if (typeId == null) {
            return null;
        }
        switch (typeId) {
            case 1:
                return 4;
            case 2:
                return 2;
            default:
                return null;
        }
    }
 
    private void addSearchRow(List<Integer> searchRows, Integer row, RowLastno rowLastno) {
        if (row == null) {
            return;
        }
        if (row < rowLastno.getsRow() || row > rowLastno.geteRow()) {
            return;
        }
        if (!searchRows.contains(row)) {
            searchRows.add(row);
        }
    }
 
    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;
    }
 
    private LocTypeDto buildUpwardCompatibleLocTypeDto(LocTypeDto locTypeDto) {
        if (locTypeDto == null || locTypeDto.getLocType1() == null || locTypeDto.getLocType1() >= 2) {
            return null;
        }
        LocTypeDto compatibleLocTypeDto = new LocTypeDto();
        compatibleLocTypeDto.setLocType1((short) (locTypeDto.getLocType1() + 1));
        compatibleLocTypeDto.setLocType2(locTypeDto.getLocType2());
        compatibleLocTypeDto.setLocType3(locTypeDto.getLocType3());
        compatibleLocTypeDto.setSiteId(locTypeDto.getSiteId());
        return compatibleLocTypeDto;
    }
 
    /**
     * 空托盘兼容回退规则:
     * 当首轮 loc_type2=1 没有命中空库位时,允许退化到高位空库位 loc_type1=2。
     *
     * 注意这里不会继续保留 locType2=1。
     * 也就是说第二轮是“高位优先兜底”,而不是“高位窄库位兜底”。
     * 这是按照现场最新口径实现的:窄库位优先,窄库位没有时再找高位空库位。
     */
    private LocTypeDto buildEmptyPalletCompatibleLocTypeDto(LocTypeDto locTypeDto) {
        if (locTypeDto == null || locTypeDto.getLocType2() == null || locTypeDto.getLocType2() != 1) {
            return null;
        }
        LocTypeDto compatibleLocTypeDto = new LocTypeDto();
        compatibleLocTypeDto.setLocType1((short) 2);
        compatibleLocTypeDto.setLocType3(locTypeDto.getLocType3());
        compatibleLocTypeDto.setSiteId(locTypeDto.getSiteId());
        return compatibleLocTypeDto;
    }
 
    /**
     * 统一封装找库位失败后的兼容重试顺序。
     *
     * 空托盘:
     * 先按 loc_type2=1 查找,失败后退到 loc_type1=2。
     *
     * 非空托盘:
     * 维持原规则,低位失败后再向高位兼容。
     */
    private LocTypeDto buildRetryCompatibleLocTypeDto(Integer staDescId, FindLocNoAttributeVo findLocNoAttributeVo, LocTypeDto locTypeDto) {
        if (isEmptyPalletRequest(staDescId, findLocNoAttributeVo)) {
            LocTypeDto emptyPalletCompatibleLocTypeDto = buildEmptyPalletCompatibleLocTypeDto(locTypeDto);
            if (emptyPalletCompatibleLocTypeDto != null) {
                return emptyPalletCompatibleLocTypeDto;
            }
        }
        return buildUpwardCompatibleLocTypeDto(locTypeDto);
    }
 
 
 
    /**
     * 检索库位号
     *
     * @param whsType              类型 1:双深式货架
     * @param staDescId            路径ID
     * @param sourceStaNo          源站
     * @param findLocNoAttributeVo 属性
     * @param moveCrnNo            源
     * @param locTypeDto           类型
     * @param times                轮询次数
     * @return locNo 检索到的库位号
     */
    @Transactional
    public StartupDto getLocNoRun(Integer whsType, Integer staDescId, Integer sourceStaNo, FindLocNoAttributeVo findLocNoAttributeVo, Integer moveCrnNo, LocTypeDto locTypeDto, int times) {
 
        // 初始化参数
        int crnNo = 0;      //堆垛机号
        int nearRow = 0;    //最浅库位排
        int curRow = 0;     //最深库位排
        int rowCount = 0;   //轮询轮次
        LocMast locMast = null;     // 目标库位
 
        StartupDto startupDto = new StartupDto();
        RowLastno rowLastno = rowLastnoService.selectById(whsType);
        if (Cools.isEmpty(rowLastno)) {
            throw new CoolException("数据异常,请联系管理员===>库位规则未知");
        }
        RowLastnoType rowLastnoType = rowLastnoTypeService.selectById(rowLastno.getTypeId());
        if (Cools.isEmpty(rowLastnoType)) {
            throw new CoolException("数据异常,请联系管理员===》库位规则类型未知");
        }
        int sRow = rowLastno.getsRow();
        int eRow = rowLastno.geteRow();
        int crnNumber = rowLastno.getCrnQty();
 
 
        // ===============>>>> 开始执行
        curRow = rowLastno.getCurrentRow();
 
        if (!Cools.isEmpty(moveCrnNo) && moveCrnNo != 0) {
            crnNumber = moveCrnNo;
            if (times == 0) {
                curRow = moveCrnNo * 4 - 1;
            } else {
                curRow = moveCrnNo * 4 - 2;
            }
        }
 
        //此程序用于优化堆垛机异常时的运行时间
        Optional<CrnRowInfo> infoOpt = findBalancedCrnAndNearRow(rowLastno, curRow, crnNumber, times, findLocNoAttributeVo, locTypeDto, rowLastnoType);
        if (!infoOpt.isPresent()) {
            infoOpt = findAvailableCrnAndNearRow(rowLastno, curRow, crnNumber, times, findLocNoAttributeVo, locTypeDto, rowLastnoType);
        }
        if (!infoOpt.isPresent()) {
            throw new CoolException("无可用堆垛机");
        }
        CrnRowInfo info = infoOpt.get();
        crnNo = info.getCrnNo();
        nearRow = info.getNearRow();
        curRow = info.getCurRow();
        rowCount = info.getRowCount();
        times = info.getTimes();
 
 
        boolean signRule1 = false;
        boolean signRule2 = false;
 
 
        if (Utils.BooleanWhsTypeStaIoType(rowLastno)) {
            // 靠近摆放规则 --- 同天同规格物料 //分离版
            if (!Cools.isEmpty(findLocNoAttributeVo.getMatnr()) && staDescId == 1) {
                signRule1 = true;
            }
            // 靠近摆放规则 --- 同天同规格物料 //互通版
            if (!Cools.isEmpty(findLocNoAttributeVo.getMatnr()) && staDescId == 1) {
                signRule2 = true;
            }
 
            if (!Cools.isEmpty(findLocNoAttributeVo.getMatnr()) && (staDescId == 11 || staDescId == 111)) {
                signRule1 = true;
            }
        }
 
        if (signRule1) {
            if (nearRow != curRow) {
                List<LocMast> locMasts = locMastService.selectList(new EntityWrapper<LocMast>()
                        .eq("row1", nearRow).eq("loc_sts", "O").eq("whs_type", rowLastnoType.getType().longValue()));
                for (LocMast locMast1 : locMasts) {
                    //获取巷道
//                    List<String> groupOutsideLocCrn = Utils.getGroupOutLocCrn(curRow,nearRow,locMast1.getLocNo(), curRow>nearRow);
//                    LocMast locMastGro = locMastService.selectById(wrkMast.getLocNo());
                    //获取目标库位所在巷道最浅非空库位
                    LocMast locMastF = locMastService.selectLocByLocStsPakInF(curRow, nearRow, locMast1, rowLastnoType.getType().longValue());
                    if (!Cools.isEmpty(locMastF) && locMastF.getLocSts().equals("F")) {
                        LocDetl locDetl = locDetlService.selectOne(new EntityWrapper<LocDetl>().eq("loc_no", locMastF.getLocNo()));
                        if (!Cools.isEmpty(locDetl) && findLocNoAttributeVo.beSimilar(locDetl)) {
                            //获取目标库位所在巷道最深空库位
                            locMast = locMastService.selectLocByLocStsPakInO(curRow, nearRow, locMast1, rowLastnoType.getType().longValue());
                            break;
                        }
                    }
                }
            }
        } else if (signRule2) {
            List<String> locNos = locDetlService.getSameDetlToday(findLocNoAttributeVo.getMatnr(), sRow, eRow);
            for (String locNo : locNos) {
                if (Utils.isShallowLoc(slaveProperties, locNo)) {
                    continue;
                }
                String shallowLocNo = Utils.getShallowLoc(slaveProperties, locNo);
                // 检测目标库位是否为空库位
                LocMast shallowLoc = locMastService.selectById(shallowLocNo);
                if (shallowLoc != null && shallowLoc.getLocSts().equals("O")) {
                    if (VersionUtils.locMoveCheckLocTypeComplete(shallowLoc, locTypeDto)) {
                        if (basCrnpService.checkSiteError(shallowLoc.getCrnNo(), true)) {
                            locMast = shallowLoc;
                            crnNo = locMast.getCrnNo();
                            break;
                        }
                    }
                }
            }
        }
 
 
        // 靠近摆放规则 --- 空托 //互通版
        if (staDescId == 10 && Utils.BooleanWhsTypeStaIoType(rowLastno)) {
            List<LocMast> locMasts = locMastService.selectList(new EntityWrapper<LocMast>()
                    .eq("loc_sts", "D").ge("row1", sRow).le("row1", eRow).eq("whs_type", rowLastnoType.getType().longValue()));
            if (!locMasts.isEmpty()) {
                for (LocMast loc : locMasts) {
                    if (Utils.isShallowLoc(slaveProperties, loc.getLocNo())) {
                        continue;
                    }
                    String shallowLocNo = Utils.getShallowLoc(slaveProperties, loc.getLocNo());
                    // 检测目标库位是否为空库位
                    LocMast shallowLoc = locMastService.selectById(shallowLocNo);
                    if (shallowLoc != null && shallowLoc.getLocSts().equals("O")) {
                        if (VersionUtils.locMoveCheckLocTypeComplete(shallowLoc, locTypeDto)) {
                            if (basCrnpService.checkSiteError(shallowLoc.getCrnNo(), true)) {
                                locMast = shallowLoc;
                                crnNo = locMast.getCrnNo();
                                break;
                            }
                        }
                    }
                }
            }
        }
 
        Wrapper<StaDesc> wrapper = null;
        StaDesc staDesc = null;
        BasDevp staNo = null;
 
        if (Utils.BooleanWhsTypeSta(rowLastno, staDescId)) {
            // 获取目标站
            wrapper = new EntityWrapper<StaDesc>()
                    .eq("type_no", staDescId)
                    .eq("stn_no", sourceStaNo)
                    .eq("crn_no", crnNo);
            staDesc = staDescService.selectOne(wrapper);
            if (Cools.isEmpty(staDesc)) {
                log.error("type_no={},stn_no={},crn_no={}", staDescId, sourceStaNo, crnNo);
//                throw new CoolException("入库路径不存在");
                crnNo = 0;
            } else {
                staNo = basDevpService.selectById(staDesc.getCrnStn());
                if (!staNo.getAutoing().equals("Y")) {
                    log.error("目标站" + staDesc.getCrnStn() + "不可用");
//                throw new CoolException("目标站"+staDesc.getCrnStn()+"不可用");
                    crnNo = 0;
                }
                startupDto.setStaNo(staNo.getDevNo());
            }
            // 更新库位排号
            if (Cools.isEmpty(locMast)) {
                rowLastno.setCurrentRow(curRow);
                rowLastnoService.updateById(rowLastno);
            }
        }
 
        // Search empty location ==============================>>
        if (staDescId == 10 && Cools.isEmpty(locMast) && crnNo != 0) {
            locMast = findStandardEmptyLoc(rowLastno, rowLastnoType, crnNo, nearRow, locTypeDto);
        }
 
 
 
        if (Cools.isEmpty(locMast) && crnNo != 0) {
            locMast = findStandardEmptyLoc(rowLastno, rowLastnoType, crnNo, nearRow, locTypeDto);
        }
 
        if (!Cools.isEmpty(locMast) && !basCrnpService.checkSiteError(crnNo, true)) {
            locMast = null;
        }
 
        // Retry search
        if (Cools.isEmpty(locMast) || !locMast.getLocSts().equals("O")) {
            // Scan next aisle first, then retry with upward-compatible locType1.
            if (times < rowCount * 2) {
                times = times + 1;
                return getLocNoRun(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, locTypeDto, times);
            }
            LocTypeDto compatibleLocTypeDto = buildRetryCompatibleLocTypeDto(staDescId, findLocNoAttributeVo, locTypeDto);
            if (compatibleLocTypeDto != null) {
                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);
            throw new CoolException("\u6ca1\u6709\u7a7a\u5e93\u4f4d");
        }
        String locNo = locMast.getLocNo();
 
        // 生成工作号
        int workNo = getWorkNo(0);
        // 返回dto
        startupDto.setWorkNo(workNo);
        startupDto.setCrnNo(crnNo);
        startupDto.setSourceStaNo(sourceStaNo);
        startupDto.setLocNo(locNo);
        return startupDto;
    }
 
    public StartupDto getLocNoRun2(Integer whsType, Integer staDescId, Integer sourceStaNo, FindLocNoAttributeVo findLocNoAttributeVo, Integer moveCrnNo, LocTypeDto locTypeDto, int times) {
        return getLocNoRun2(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, locTypeDto, null, times);
    }
 
    /**
     * run2 入库找位主流程。
     *
     * 当前方法只保留“组织流程”和“统一收口”的职责,具体策略拆成独立方法:
     * 1. 普通物料:推荐排优先 -> 站点优先库区/堆垛机 -> 其它库区。
     * 2. 空托盘:优先库区 loc_type2=1 -> 其它库区 loc_type2=1 -> loc_type1=2 兼容。
     * 3. 命中库位后分别回写普通物料游标或空托盘库区游标。
     */
    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();
        RowLastno rowLastno = rowLastnoService.selectById(whsType);
 
        if (Cools.isEmpty(rowLastno)) {
            throw new CoolException("数据异常,请联系管理员===>库位规则未知");
        }
        RowLastnoType rowLastnoType = rowLastnoTypeService.selectById(rowLastno.getTypeId());
        if (Cools.isEmpty(rowLastnoType)) {
            throw new CoolException("数据异常,请联系管理员===》库位规则类型未知");
        }
        int crnNumber = rowLastno.getCrnQty();
        rowCount = crnNumber;
 
        curRow = rowLastno.getCurrentRow();
        crnNo = resolveRun2CrnNo(rowLastno);
        Integer preferredArea = findLocNoAttributeVo.getOutArea();
        boolean emptyPalletRequest = isEmptyPalletRequest(staDescId, findLocNoAttributeVo);
        Run2AreaSearchResult emptyPalletAreaSearchResult = null;
 
        List<Integer> orderedCrnNos = getOrderedCrnNos(rowLastno, crnNo);
        List<Integer> triedCrnNos = new ArrayList<>();
        locMast = findRun2RecommendLoc(rowLastno, rowLastnoType, emptyPalletRequest, recommendRows, locTypeDto,
                staDescId, sourceStaNo, startupDto, preferredArea, triedCrnNos);
        if (Cools.isEmpty(locMast)) {
            if (emptyPalletRequest) {
                // 空托盘单独按库区轮询:
                // 1. 当前库区先找 loc_type2=1
                // 2. 当前库区没有,再找其他库区 loc_type2=1
                // 3. 全部 narrow 都没有时,再退到 loc_type1=2
                emptyPalletAreaSearchResult = findEmptyPalletRun2AreaLoc(rowLastno, staDescId, sourceStaNo, startupDto, preferredArea, locTypeDto);
                if (!Cools.isEmpty(emptyPalletAreaSearchResult)) {
                    locMast = emptyPalletAreaSearchResult.locMast;
                }
            } else {
                locMast = findNormalRun2Loc(rowLastno, rowLastnoType, sourceStaNo, staDescId, findLocNoAttributeVo,
                        locTypeDto, startupDto, preferredArea, orderedCrnNos, triedCrnNos);
            }
        }
 
        if (!Cools.isEmpty(locMast)) {
            crnNo = locMast.getCrnNo();
            nearRow = locMast.getRow1();
        }
        if (emptyPalletRequest) {
            advanceEmptyPalletRun2Cursor(emptyPalletAreaSearchResult, locMast);
        } else {
            advanceNormalRun2Cursor(rowLastno, curRow);
        }
 
        if (Cools.isEmpty(locMast) || !locMast.getLocSts().equals("O")) {
            if (!emptyPalletRequest && times < rowCount * 2) {
                times = times + 1;
                return getLocNoRun2(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, locTypeDto, recommendRows, times);
            }
            LocTypeDto compatibleLocTypeDto = buildRetryCompatibleLocTypeDto(staDescId, findLocNoAttributeVo, locTypeDto);
            if (compatibleLocTypeDto != null) {
                // 第一轮全部堆垛机都没找到时,再进入规格兼容重试,不在单个堆垛机内局部退化。
                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);
            throw new CoolException("没有空库位");
        }
 
        int workNo = getWorkNo(0);
        startupDto.setWorkNo(workNo);
        startupDto.setCrnNo(crnNo);
        startupDto.setSourceStaNo(sourceStaNo);
        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;
    }
 
    public StartupDto getLocNoRun4(Integer whsType, Integer staDescId, Integer sourceStaNo, FindLocNoAttributeVo findLocNoAttributeVo, Integer moveCrnNo, LocTypeDto locTypeDto, int times) {
 
        // 初始化参数
        int crnNo = 0;      //堆垛机号
        int nearRow = 0;    //最浅库位排
        int curRow = 0;     //最深库位排
        int rowCount = 0;   //轮询轮次
        LocMast locMast = null;     // 目标库位
 
        StartupDto startupDto = new StartupDto();
        RowLastno rowLastno = rowLastnoService.selectById(whsType);
        if (Cools.isEmpty(rowLastno)) {
            throw new CoolException("数据异常,请联系管理员===>库位规则未知");
        }
        RowLastnoType rowLastnoType = rowLastnoTypeService.selectById(rowLastno.getTypeId());
        if (Cools.isEmpty(rowLastnoType)) {
            throw new CoolException("数据异常,请联系管理员===》库位规则类型未知");
        }
        int sRow = rowLastno.getsRow();
        int eRow = rowLastno.geteRow();
        int crnNumber = rowLastno.getCrnQty();
 
        // ===============>>>> 开始执行
        curRow = rowLastno.getCurrentRow();
 
        if (!Cools.isEmpty(moveCrnNo) && moveCrnNo != 0) {
            crnNumber = moveCrnNo;
//            if (times==0){
//                curRow = moveCrnNo*4-1;
//            }else {
//                curRow = moveCrnNo*4-2;
//            }
        }
 
        //此程序用于优化堆垛机异常时的运行时间
        for (int i = times; i < crnNumber * 2; i++) {
            int[] locNecessaryParameters = Utils.LocNecessaryParameters(rowLastno, curRow, crnNumber);
            rowCount = locNecessaryParameters[0];
            curRow = locNecessaryParameters[1];
            crnNo = locNecessaryParameters[2];
            nearRow = locNecessaryParameters[3];
            List<LocMast> locMasts = locMastService.selectList(new EntityWrapper<LocMast>()
                    .eq("crn_no", crnNo).eq("loc_sts", "O").eq("whs_type", rowLastnoType.getType().longValue()));
            if (locMasts.size() <= 5) {
                nearRow = 0;
                times++;
                continue;
            }
            break;
 
        }
        if (crnNo == 0) {
            throw new CoolException("无可用库位");
        }
 
 
        // 相似工作档案 --- 同天同规格物料
        if (!Cools.isEmpty(findLocNoAttributeVo.getMatnr()) && (staDescId == 1 || staDescId == 11 || staDescId == 111)) {
            //查询相似工作档案
            List<WrkMast> wrkMasts = wrkMastService.selectWrkMastWrkDetl(staDescId, findLocNoAttributeVo, crnNo);
            int nearbay = 0;    //相似工作档案 目标库位列
            int nearlev = 0;    //相似工作档案 目标库位层
            for (WrkMast wrkMast : wrkMasts) {
                int curRowW = curRow;    //相似工作档案 最深库位排
                int nearRowW = nearRow;    //相似工作档案 最浅库位排
                if (Cools.isEmpty(wrkMast.getLocNo())) {
                    continue;
                }
                //目标排为最外层排
                if (Utils.getRow(wrkMast.getLocNo()) == nearRow) {
                    continue;
                }
                //起始站不一致
                if (!wrkMast.getSourceStaNo().equals(sourceStaNo)) {
                    continue;
                }
                //相同列、层过滤
                if (Utils.getBay(wrkMast.getLocNo()) == nearbay && Utils.getLev(wrkMast.getLocNo()) == nearlev) {
                    continue;
                } else {
                    nearbay = Utils.getBay(wrkMast.getLocNo());
                    nearlev = Utils.getLev(wrkMast.getLocNo());
                }
 
                //获取目标库位所在巷道并排序
//                List<String> groupOutsideLocCrn = Utils.getGroupOutLocCrn(curRow,nearRow,wrkMast.getLocNo(), curRow>nearRow);
                LocMast locMastGro = locMastService.selectById(wrkMast.getLocNo());
 
                for (int i = 0; i < crnNumber * 2; i++) {
                    if (!(Utils.getRow(locMastGro.getLocNo()) > nearRowW && Utils.getRow(locMastGro.getLocNo()) <= curRowW) && !(Utils.getRow(locMastGro.getLocNo()) < nearRowW && Utils.getRow(locMastGro.getLocNo()) >= curRowW)) {
                        int[] locNecessaryParameters = Utils.LocNecessaryParameters(rowLastno, curRowW, crnNumber);
                        curRowW = locNecessaryParameters[1];
                        nearRowW = locNecessaryParameters[3];
                    } else {
                        break;
                    }
                }
 
                //获取目标库位所在巷道最浅非空库位
                LocMast locMast2 = locMastService.selectLocByLocStsPakInF(curRowW, nearRowW, locMastGro, rowLastnoType.getType().longValue());
 
                //目标库位所在巷道最浅非空库位存在&&非最外侧库位&&入库状态
                if (!Cools.isEmpty(locMast2) && Utils.getRow(locMast2.getLocNo()) != nearRowW && (locMast2.getLocSts().equals("S") || locMast2.getLocSts().equals("Q"))) {
                    //获取库存明细
                    WrkDetl wrkDetl = wrkDetlService.selectOne(new EntityWrapper<WrkDetl>().eq("wrk_no", wrkMast.getWrkNo()));
                    //判断同规格物料
                    if (!Cools.isEmpty(wrkDetl) && findLocNoAttributeVo.beSimilar(wrkDetl)) {
                        int row2 = 0;
                        if (Utils.getRow(locMast2.getLocNo()) > nearRowW) {
                            row2 = Utils.getRow(locMast2.getLocNo()) - 1;
                        } else {
                            row2 = Utils.getRow(locMast2.getLocNo()) + 1;
                        }
                        String targetLocNo = zerofill(String.valueOf(row2), 2) + locMast2.getLocNo().substring(2);
                        locMast = locMastService.selectOne(new EntityWrapper<LocMast>().eq("loc_no", targetLocNo).eq("loc_sts", "O"));
                        if (Cools.isEmpty(locMast)) {
                            continue;
                        }
                        break;
                    }
                }
            }
 
        }
 
        // 相似工作档 --- 空托
        if (Cools.isEmpty(locMast) && staDescId == 10) {
            List<WrkMast> wrkMasts = wrkMastService.selectList(new EntityWrapper<WrkMast>().eq("io_type", 10).eq("crn_no", crnNo).eq("whs_type", rowLastnoType.getType().longValue()));
            int nearbay = 0;
            int nearlev = 0;
            for (WrkMast wrkMast : wrkMasts) {
                int curRowW = curRow;    //相似工作档案 最深库位排
                int nearRowW = nearRow;    //相似工作档案 最浅库位排
                if (Cools.isEmpty(wrkMast.getLocNo())) {
                    continue;
                }
                if (Utils.getRow(wrkMast.getLocNo()) == nearRow) {
                    continue;
                }
                //起始站不一致
                if (!wrkMast.getSourceStaNo().equals(sourceStaNo)) {
                    continue;
                }
                if (Utils.getBay(wrkMast.getLocNo()) == nearbay && Utils.getLev(wrkMast.getLocNo()) == nearlev) {
                    continue;
                } else {
                    nearbay = Utils.getBay(wrkMast.getLocNo());
                    nearlev = Utils.getLev(wrkMast.getLocNo());
                }
//                List<String> groupOutsideLocCrn = Utils.getGroupOutLocCrn(curRow,nearRow,wrkMast.getLocNo(), curRow>nearRow);
                LocMast locMastGro = locMastService.selectById(wrkMast.getLocNo());
 
                for (int i = 0; i < crnNumber * 2; i++) {
                    if (!(Utils.getRow(locMastGro.getLocNo()) > nearRowW && Utils.getRow(locMastGro.getLocNo()) <= curRowW) && !(Utils.getRow(locMastGro.getLocNo()) < nearRowW && Utils.getRow(locMastGro.getLocNo()) >= curRowW)) {
                        int[] locNecessaryParameters = Utils.LocNecessaryParameters(rowLastno, curRowW, crnNumber);
                        curRowW = locNecessaryParameters[1];
                        nearRowW = locNecessaryParameters[3];
                    } else {
                        break;
                    }
                }
 
                LocMast locMast2 = locMastService.selectLocByLocStsPakInF(curRowW, nearRowW, locMastGro, rowLastnoType.getType().longValue());
 
                if (!Cools.isEmpty(locMast2) && Utils.getRow(locMast2.getLocNo()) != nearRowW && locMast2.getLocSts().equals("S")) {
                    int row2 = 0;
                    if (Utils.getRow(locMast2.getLocNo()) > nearRowW) {
                        row2 = Utils.getRow(locMast2.getLocNo()) - 1;
                    } else {
                        row2 = Utils.getRow(locMast2.getLocNo()) + 1;
                    }
                    String targetLocNo = zerofill(String.valueOf(row2), 2) + locMast2.getLocNo().substring(2);
                    locMast = locMastService.selectOne(new EntityWrapper<LocMast>().eq("loc_no", targetLocNo).eq("loc_sts", "O"));
                    if (Cools.isEmpty(locMast)) {
                        continue;
                    }
                    break;
                }
            }
        }
 
        boolean signRule1 = false;
        boolean signRule2 = false;
 
 
        if (Utils.BooleanWhsTypeStaIoType(rowLastno)) {
            // 靠近摆放规则 --- 同天同规格物料 //分离版
            if (!Cools.isEmpty(findLocNoAttributeVo.getMatnr()) && staDescId == 1) {
//                signRule1 = true;
            }
            // 靠近摆放规则 --- 同天同规格物料 //互通版
            if (!Cools.isEmpty(findLocNoAttributeVo.getMatnr()) && staDescId == 1) {
                signRule2 = true;
            }
 
            if (!Cools.isEmpty(findLocNoAttributeVo.getMatnr()) && (staDescId == 11 || staDescId == 111)) {
                signRule1 = true;
            }
        }
 
        if (signRule1) {
            if (nearRow != curRow) {
                List<LocMast> locMasts = locMastService.selectList(new EntityWrapper<LocMast>()
                        .eq("row1", nearRow).eq("loc_sts", "O").eq("whs_type", rowLastnoType.getType().longValue()));
                for (LocMast locMast1 : locMasts) {
                    //获取巷道
//                    List<String> groupOutsideLocCrn = Utils.getGroupOutLocCrn(curRow,nearRow,locMast1.getLocNo(), curRow>nearRow);
                    //获取目标库位所在巷道最浅非空库位
                    LocMast locMastF = locMastService.selectLocByLocStsPakInF(curRow, nearRow, locMast1, rowLastnoType.getType().longValue());
                    if (!Cools.isEmpty(locMastF) && locMastF.getLocSts().equals("F")) {
                        LocDetl locDetl = locDetlService.selectOne(new EntityWrapper<LocDetl>().eq("loc_no", locMastF.getLocNo()));
                        if (!Cools.isEmpty(locDetl) && findLocNoAttributeVo.beSimilar(locDetl)) {
                            //获取目标库位所在巷道最深空库位
                            locMast = locMastService.selectLocByLocStsPakInO(curRow, nearRow, locMast1, rowLastnoType.getType().longValue());
                            break;
                        }
                    }
                }
            }
        } else if (signRule2) {
            List<String> locNos = locDetlService.getSameDetlToday(findLocNoAttributeVo.getMatnr(), sRow, eRow);
            int nearbay = 0;
            int nearlev = 0;
            for (String locNo : locNos) {
                int curRowW = curRow;    //相似工作档案 最深库位排
                int nearRowW = nearRow;    //相似工作档案 最浅库位排
                if (Cools.isEmpty(locNo)) {
                    continue;
                }
                if (Utils.getRow(locNo) == nearRow) {
                    continue;
                }
                if (Utils.getBay(locNo) == nearbay && Utils.getLev(locNo) == nearlev) {
                    continue;
                } else {
                    nearbay = Utils.getBay(locNo);
                    nearlev = Utils.getLev(locNo);
                }
//                List<String> groupOutsideLocCrn = Utils.getGroupOutLocCrn(curRow,nearRow,wrkMast.getLocNo(), curRow>nearRow);
                LocMast locMastGro = locMastService.selectById(locNo);
 
                for (int i = 0; i < crnNumber * 2; i++) {
                    if (!(Utils.getRow(locMastGro.getLocNo()) > nearRowW && Utils.getRow(locMastGro.getLocNo()) <= curRowW) && !(Utils.getRow(locMastGro.getLocNo()) < nearRowW && Utils.getRow(locMastGro.getLocNo()) >= curRowW)) {
                        int[] locNecessaryParameters = Utils.LocNecessaryParameters(rowLastno, curRowW, crnNumber);
                        curRowW = locNecessaryParameters[1];
                        nearRowW = locNecessaryParameters[3];
                    } else {
                        break;
                    }
                }
 
                LocMast locMast2 = locMastService.selectLocByLocStsPakInF(curRowW, nearRowW, locMastGro, rowLastnoType.getType().longValue());
 
                if (!Cools.isEmpty(locMast2) && Utils.getRow(locMast2.getLocNo()) != nearRowW && locMast2.getLocSts().equals("S")) {
                    int row2 = 0;
                    if (Utils.getRow(locMast2.getLocNo()) > nearRowW) {
                        row2 = Utils.getRow(locMast2.getLocNo()) - 1;
                    } else {
                        row2 = Utils.getRow(locMast2.getLocNo()) + 1;
                    }
                    String targetLocNo = zerofill(String.valueOf(row2), 2) + locMast2.getLocNo().substring(2);
                    locMast = locMastService.selectOne(new EntityWrapper<LocMast>().eq("loc_no", targetLocNo).eq("loc_sts", "O"));
                    if (Cools.isEmpty(locMast)) {
                        continue;
                    }
                    break;
                }
            }
        }
 
//        // 靠近摆放规则 --- 空托  //分离版
//        if (staDescId == 10 && Utils.BooleanWhsTypeStaIoType(rowLastno)) {
//            List<LocMast> locMasts = locMastService.selectList(new EntityWrapper<LocMast>().eq("row1", nearRow).eq("loc_sts", "O"));
//            for (LocMast locMast1:locMasts){
//                //获取巷道
////                List<String> groupOutsideLocCrn = Utils.getGroupOutLocCrn(curRow,nearRow,locMast1.getLocNo(), curRow>nearRow);
//                //获取目标库位所在巷道最浅非空库位
//                LocMast locMastF = locMastService.selectLocByLocStsPakInF(curRow,nearRow,locMast1,rowLastnoType.getType().longValue());
//                if (!Cools.isEmpty(locMastF) && locMastF.getLocSts().equals("D")){
//                    //获取目标库位所在巷道最浅非空库位
//                    locMast = locMastService.selectLocByLocStsPakInO(curRow,nearRow,locMast1,rowLastnoType.getType().longValue());
//                    break;
//                }
//            }
//        }
 
        // 靠近摆放规则 --- 空托 //互通版
        if (staDescId == 10 && Utils.BooleanWhsTypeStaIoType(rowLastno)) {
            List<LocMast> locMasts = locMastService.selectList(new EntityWrapper<LocMast>().eq("loc_sts", "D").ge("row1", sRow).le("row1", eRow));
            int nearbay = 0;
            int nearlev = 0;
            for (LocMast locMastSign : locMasts) {
                int curRowW = curRow;    //相似工作档案 最深库位排
                int nearRowW = nearRow;    //相似工作档案 最浅库位排
                if (Cools.isEmpty(locMastSign.getLocNo())) {
                    continue;
                }
                if (Utils.getRow(locMastSign.getLocNo()) == nearRow) {
                    continue;
                }
                if (Utils.getBay(locMastSign.getLocNo()) == nearbay && Utils.getLev(locMastSign.getLocNo()) == nearlev) {
                    continue;
                } else {
                    nearbay = Utils.getBay(locMastSign.getLocNo());
                    nearlev = Utils.getLev(locMastSign.getLocNo());
                }
//                List<String> groupOutsideLocCrn = Utils.getGroupOutLocCrn(curRow,nearRow,wrkMast.getLocNo(), curRow>nearRow);
                LocMast locMastGro = locMastService.selectById(locMastSign.getLocNo());
 
                for (int i = 0; i < crnNumber * 2; i++) {
                    if (!(Utils.getRow(locMastGro.getLocNo()) > nearRowW && Utils.getRow(locMastGro.getLocNo()) <= curRowW) && !(Utils.getRow(locMastGro.getLocNo()) < nearRowW && Utils.getRow(locMastGro.getLocNo()) >= curRowW)) {
                        int[] locNecessaryParameters = Utils.LocNecessaryParameters(rowLastno, curRowW, crnNumber);
                        curRowW = locNecessaryParameters[1];
                        nearRowW = locNecessaryParameters[3];
                    } else {
                        break;
                    }
                }
 
                LocMast locMast2 = locMastService.selectLocByLocStsPakInF(curRowW, nearRowW, locMastGro, rowLastnoType.getType().longValue());
 
                if (!Cools.isEmpty(locMast2) && Utils.getRow(locMast2.getLocNo()) != nearRowW && locMast2.getLocSts().equals("S")) {
                    int row2 = 0;
                    if (Utils.getRow(locMast2.getLocNo()) > nearRowW) {
                        row2 = Utils.getRow(locMast2.getLocNo()) - 1;
                    } else {
                        row2 = Utils.getRow(locMast2.getLocNo()) + 1;
                    }
                    String targetLocNo = zerofill(String.valueOf(row2), 2) + locMast2.getLocNo().substring(2);
                    locMast = locMastService.selectOne(new EntityWrapper<LocMast>().eq("loc_no", targetLocNo).eq("loc_sts", "O"));
                    if (Cools.isEmpty(locMast)) {
                        continue;
                    }
                    break;
                }
            }
        }
 
        Wrapper<StaDesc> wrapper = null;
        StaDesc staDesc = null;
        BasDevp staNo = null;
 
        if (Utils.BooleanWhsTypeSta(rowLastno, staDescId)) {
            // 获取目标站
            wrapper = new EntityWrapper<StaDesc>()
                    .eq("type_no", staDescId)
                    .eq("stn_no", sourceStaNo)
                    .eq("crn_no", crnNo);
            staDesc = staDescService.selectOne(wrapper);
            if (Cools.isEmpty(staDesc)) {
                log.error("入库路径不存在:type_no={},stn_no={},crn_no={}", staDescId, sourceStaNo, crnNo);
                crnNo = 0;
            } else {
                staNo = basDevpService.selectById(staDesc.getCrnStn());
                if (!staNo.getAutoing().equals("Y")) {
                    log.error("目标站" + staDesc.getCrnStn() + "不可用");
                    crnNo = 0;
                }
                startupDto.setStaNo(staNo.getDevNo());
            }
        }
 
        // 更新库位排号
        if (Utils.BooleanWhsTypeSta(rowLastno, staDescId) && Cools.isEmpty(locMast)) {
            rowLastno.setCurrentRow(curRow);
            rowLastnoService.updateById(rowLastno);
        }
 
        // 开始查找库位 ==============================>>
 
        // 1.按规则查找库位
        if (Cools.isEmpty(locMast) && crnNo != 0) {
            List<LocMast> locMasts = locMastService.selectList(new EntityWrapper<LocMast>()
                    .eq("row1", nearRow)
                    .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)) {
                    //获取目标库位所在巷道最深空库位
                    LocMast locMast2 = locMastService.selectLocByLocStsPakInO(curRow, nearRow, locMast1, rowLastnoType.getType().longValue());
                    if (!Cools.isEmpty(locMast2) && locMast2.getBay1() == curRow) {
                        locMast = locMast2;
                        break;
                    }
 
                }
            }
 
            //未找到  允许混料
            if (Cools.isEmpty(locMast) && Utils.BooleanWhsTypeStaIoType(rowLastno)) {
                for (LocMast locMast1 : locMasts) {
                    if (!VersionUtils.locMoveCheckLocTypeComplete(locMast1, locTypeDto)) {
                        continue;
                    }
                    if (Utils.BooleanWhsTypeStaIoType(rowLastno)) {
                        // ?????????????
//                        List<String> groupOutsideLocCrn = Utils.getGroupOutLocCrn(curRow,nearRow,locMast1.getLocNo(), curRow>nearRow);
 
                        // ????????????????
                        LocMast locMast2 = locMastService.selectLocByLocStsPakInF(curRow, nearRow, locMast1, rowLastnoType.getType().longValue());
                        if (Cools.isEmpty(locMast2)) {
                            LocMast locMast3 = locMastService.selectLocByLocStsPakInO(curRow, nearRow, locMast1, rowLastnoType.getType().longValue());
                            if (!Cools.isEmpty(locMast3)) {
                                locMast = locMast3;
                                break;
                            }
                        } else {
                            if ((locMast2.getLocSts().equals("F") && staDescId == 1) || (locMast2.getLocSts().equals("D") && staDescId == 10)) {
                                LocMast locMast3 = locMastService.selectLocByLocStsPakInO(curRow, nearRow, locMast1, rowLastnoType.getType().longValue());
                                if (!Cools.isEmpty(locMast3)) {
                                    locMast = locMast3;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
 
        // Retry search
        if (Cools.isEmpty(locMast) || !locMast.getLocSts().equals("O")) {
            // Scan next aisle first, then retry with upward-compatible locType1.
            if (times < rowCount * 2) {
                times = times + 1;
                return getLocNoRun4(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, locTypeDto, times);
            }
            LocTypeDto compatibleLocTypeDto = buildRetryCompatibleLocTypeDto(staDescId, findLocNoAttributeVo, locTypeDto);
            if (compatibleLocTypeDto != null) {
                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);
            throw new CoolException("\u6ca1\u6709\u7a7a\u5e93\u4f4d");
        }
        String locNo = locMast.getLocNo();
 
        // 生成工作号
        int workNo = getWorkNo(0);
        // 返回dto
        startupDto.setWorkNo(workNo);
        startupDto.setCrnNo(crnNo);
        startupDto.setSourceStaNo(sourceStaNo);
        startupDto.setLocNo(locNo);
        return startupDto;
    }
 
    public StartupDto getLocNoRun5(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();
        RowLastno rowLastno = rowLastnoService.selectById(whsType);
        if (Cools.isEmpty(rowLastno)) {
            throw new CoolException("数据异常,请联系管理员===>库位规则未知");
        }
        RowLastnoType rowLastnoType = rowLastnoTypeService.selectById(rowLastno.getTypeId());
        if (Cools.isEmpty(rowLastnoType)) {
            throw new CoolException("数据异常,请联系管理员===》库位规则类型未知");
        }
        int sRow = rowLastno.getsRow();
        int eRow = rowLastno.geteRow();
        int crnNumber = eRow - sRow + 1;
 
        // ===============>>>> 开始执行
        curRow = rowLastno.getCurrentRow();
 
        if (!Cools.isEmpty(moveCrnNo) && moveCrnNo != 0) {
            crnNumber = moveCrnNo;
        }
 
        //此程序用于优化堆垛机异常时的运行时间
        int[] locNecessaryParameters = Utils.LocNecessaryParameters(rowLastno, curRow, crnNumber);
        curRow = locNecessaryParameters[1];
        crnNo = 6;
        rowCount = locNecessaryParameters[0];
        nearRow = locNecessaryParameters[3];
 
        Wrapper<StaDesc> wrapper = null;
        StaDesc staDesc = null;
        BasDevp staNo = null;
 
//        if (Utils.BooleanWhsTypeSta(rowLastno, staDescId)) {
            // 获取目标站
//            wrapper = new EntityWrapper<StaDesc>()
//                    .eq("type_no", staDescId)
//                    .eq("stn_no", sourceStaNo)
//                    .eq("crn_no", crnNo);
//            staDesc = staDescService.selectOne(wrapper);
//            if (Cools.isEmpty(staDesc)) {
//                log.error("type_no={},stn_no={},crn_no={}", staDescId, sourceStaNo, crnNo);
////                throw new CoolException("入库路径不存在");
//                crnNo = 0;
//            }
//            else {
//                staNo = basDevpService.selectById(staDesc.getCrnStn());
//                if (!staNo.getAutoing().equals("Y")) {
//                    log.error("目标站" + staDesc.getCrnStn() + "不可用");
////                throw new CoolException("目标站"+staDesc.getCrnStn()+"不可用");
//                    crnNo = 0;
//                }
//                startupDto.setStaNo(staNo.getDevNo());
//            }
//        }
 
        // 更新库位排号
        if (Utils.BooleanWhsTypeSta(rowLastno, staDescId) && Cools.isEmpty(locMast)) {
            rowLastno.setCurrentRow(curRow);
            rowLastnoService.updateById(rowLastno);
        }
 
        // 开始查找库位 ==============================>>
 
        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) {
            List<LocMast> locMasts = locMastService.selectList(new EntityWrapper<LocMast>()
                    .eq("row1", nearRow)
                    .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)) {
                    // 获取目标库位所在巷道最深空库位
                    LocMast locMast2 = locMastService.selectLocByLocStsPakInO(curRow, nearRow, locMast1, rowLastnoType.getType().longValue());
                    if (!Cools.isEmpty(locMast2) && locMast2.getRow1() == curRow) {
                        locMast = locMast2;
                        break;
                    }
                }
            }
        } else if (Cools.isEmpty(locMast)) {
            int[] bayRange = getAgvAreaBayRange(preferredArea);
            locMast = findAgvLocByRows(rowLastno, rowLastnoType, getAgvAreaRows(preferredArea, rowLastno),
                    bayRange[0], bayRange[1], curRow, nearRow, locTypeDto, false);
            if (!Cools.isEmpty(locMast)) {
                crnNo = locMast.getCrnNo();
            }
            if (Cools.isEmpty(locMast)) {
                locMast = findAgvLocByRows(rowLastno, rowLastnoType, getAgvFallbackRows(rowLastno),
                        1, 19, curRow, nearRow, locTypeDto, true);
                if (!Cools.isEmpty(locMast)) {
                    crnNo = locMast.getCrnNo();
                }
            }
        }
        // Retry search
        if (Cools.isEmpty(locMast) || !locMast.getLocSts().equals("O")) {
            // Scan next aisle first, then retry with upward-compatible locType1.
            if (times < rowCount * 2) {
                times = times + 1;
                return getLocNoRun5(whsType, staDescId, sourceStaNo, findLocNoAttributeVo, moveCrnNo, locTypeDto, recommendRows, times);
            }
            LocTypeDto compatibleLocTypeDto = buildRetryCompatibleLocTypeDto(staDescId, findLocNoAttributeVo, locTypeDto);
            if (compatibleLocTypeDto != null) {
                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);
            throw new CoolException("\u6ca1\u6709\u7a7a\u5e93\u4f4d");
        }
        String locNo = locMast.getLocNo();
 
        // 生成工作号
        int workNo = getWorkNo(0);
        // 返回dto
        startupDto.setWorkNo(workNo);
        startupDto.setCrnNo(crnNo);
        startupDto.setSourceStaNo(sourceStaNo);
        startupDto.setLocNo(locNo);
        return startupDto;
    }
 
    public static String zerofill(String msg, Integer count) {
        if (msg.length() == count) {
            return msg;
        } else if (msg.length() > count) {
            return msg.substring(0, 16);
        } else {
            StringBuilder msgBuilder = new StringBuilder(msg);
            for (int i = 0; i < count - msg.length(); ++i) {
                msgBuilder.insert(0, "0");
            }
            return msgBuilder.toString();
        }
    }
 
}