李林
2023-10-07 658d4927d468c47208fd012d9128b09249c07eff
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
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
package com.chinaztt.mes.plan.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.chinaztt.ifs.api.feign.IfsFeignClient;
import com.chinaztt.mes.basic.entity.IfsLog;
import com.chinaztt.mes.basic.entity.Part;
import com.chinaztt.mes.basic.mapper.IfsLogMapper;
import com.chinaztt.mes.basic.mapper.PartMapper;
import com.chinaztt.mes.basic.service.IfsLogService;
import com.chinaztt.mes.common.constant.Constant;
import com.chinaztt.mes.common.handler.StateMachineHandler;
import com.chinaztt.mes.common.numgen.NumberGenerator;
import com.chinaztt.mes.common.util.StateResult;
import com.chinaztt.mes.plan.dto.*;
import com.chinaztt.mes.plan.entity.*;
import com.chinaztt.mes.plan.excel.ManufacturingOderUploadData;
import com.chinaztt.mes.plan.excel.ManufacturingOrderData;
import com.chinaztt.mes.plan.mapper.*;
import com.chinaztt.mes.plan.service.ManufacturingOrderService;
import com.chinaztt.mes.plan.service.MasterProductionScheduleService;
import com.chinaztt.mes.plan.service.MoRoutingService;
import com.chinaztt.mes.plan.state.auditstate.constant.AuditStateStringValues;
import com.chinaztt.mes.plan.state.manufacturing.ManufacturingOrderStateMachineConfig;
import com.chinaztt.mes.plan.state.manufacturing.constant.ManufacturingOrderEvents;
import com.chinaztt.mes.plan.state.manufacturing.constant.ManufacturingOrderStateStringValues;
import com.chinaztt.mes.plan.state.manufacturing.constant.ManufacturingOrderStates;
import com.chinaztt.mes.plan.state.masterproductionschedule.constant.MasterProductionScheduleStateStringValues;
import com.chinaztt.mes.plan.util.ManufacturingOrderUtils;
import com.chinaztt.mes.quality.entity.TestStandard;
import com.chinaztt.mes.quality.entity.TestStandardBinding;
import com.chinaztt.mes.quality.mapper.TestStandardBindingMapper;
import com.chinaztt.mes.quality.mapper.TestStandardMapper;
import com.chinaztt.mes.technology.dto.*;
import com.chinaztt.mes.technology.entity.*;
import com.chinaztt.mes.technology.mapper.*;
import com.chinaztt.mes.technology.service.BomService;
import com.chinaztt.mes.technology.service.RoutingService;
import com.chinaztt.mes.technology.state.bom.constant.BomStateStringValues;
import com.chinaztt.mes.technology.state.routing.constant.RoutingStateStringValues;
import com.chinaztt.ztt.admin.api.feign.RemoteParamService;
import com.chinaztt.ztt.common.core.constant.SecurityConstants;
import com.chinaztt.ztt.common.core.util.R;
import com.chinaztt.ztt.common.sequence.sequence.Sequence;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
 
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
 
/**
 * 制造订单表
 *
 * @author cxf
 * @date 2020-09-24 14:26:01
 */
@Slf4j
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class ManufacturingOrderServiceImpl extends ServiceImpl<ManufacturingOrderMapper, ManufacturingOrder> implements ManufacturingOrderService {
 
    private BomMapper bomMapper;
    private BomService bomService;
    private CustomerOrderMapper customerOrderMapper;
    private IfsFeignClient ifsFeignClient;
    private JoinModelCustomerMapper joinModelCustomerMapper;
    private MasterProductionScheduleService masterProductionScheduleService;
    private ManufacturingOrderOperationTemplateMapper manufacturingOrderOperationTemplateMapper;
    private ManufacturingOrderOperationParamMapper manufacturingOrderOperationParamMapper;
    private MoTestStandardMapper moTestStandardMapper;
    private MoRoutingService moRoutingService;
    private MoOutBatchMapper moOutBatchMapper;
    private MoStructureComponentMapper moStructureComponentMapper;
    private MoTestStandardParamMapper moTestStandardParamMapper;
    private MoRoutingMapper moRoutingMapper;
    private MoRoutingOperationMapper moRoutingOperationMapper;
    private MasterProductionScheduleMapper masterProductionScheduleMapper;
    private MpsStructureComponentMapper mpsStructureComponentMapper;
    private ManufacturingOrderMatIssueMapper manufacturingOrderMatIssueMapper;
    private ManufacturingOrderConcatMapper manufacturingOrderConcatMapper;
    private NumberGenerator<ManufacturingOrder> manufacturingOrderNumberGenerator;
    private NumberGenerator<ManufacturingOrderOperationTemplate> numberGenerator;
    private OrderParamMapper orderParamMapper;
    private OperationTaskProduceMapper operationTaskProduceMapper;
    private PartMapper partMapper;
    private RoutingMapper routingMapper;
    private RemoteParamService remoteParamService;
    private RoutingOperationMapper routingOperationMapper;
    private RoutingOperationTemplateMapper routingOperationTemplateMapper;
    private RoutingOperationParamMapper routingOperationParamMapper;
    private RoutingService routingService;
    private StateMachineFactory<ManufacturingOrderStates, ManufacturingOrderEvents> manufacturingOrderStateMachineFactory;
    private StateMachinePersister<ManufacturingOrderStates, ManufacturingOrderEvents, ManufacturingOrder> persister;
    private TestStandardBindingMapper testStandardBindingMapper;
    private TestStandardMapper testStandardMapper;
    private ManufacturingOrderUtils manufacturingOrderUtils;
    private DocumentMapper documentMapper;
    private ManufacturingOrderSnGenerateMapper manufacturingOrderSnGenerateMapper;
    private MasterProductionScheduleTheoryQuantityMapper masterProductionScheduleTheoryQuantityMapper;
    private ManufacturingOrderMapper manufacturingOrderMapper;
    private JoinDocumentBomRoutingMapper joinDocumentBomRoutingMapper;
    private CustomerOrderProduceTaskMapper customerOrderProduceTaskMapper;
 
    private IfsLogService ifsLogService;
 
    private IfsLogMapper ifsLogMapper;
 
    private Sequence sequence;
 
    private final List<String> orderInterfaceNames = Arrays.asList("IMPORT_SHOP_ORDER_STD", "IMPORT_SO_SMA_SOPER_STD",
            "IMPORT_SHOP_MATERIAL_ALLOC_STD", "MODIFY_SHOP_MATERIAL_ALLOC_STD", "REMOVE_SHOP_MATERIAL_ALLOC_STD",
            "MODIFY_SHOP_OPERATION_STD", "MODIFY_SO_PRE_CLOSE_STD", "IMPORT_SO_MATERIAL_ISSUE_STD",
            "IMPORT_SO_MATERIAL_UNISSUE_STD", "IMPORT_SO_OPER_REPORT_STD", "IMPORT_SO_RECEIVE_STD", "IMPORT_SO_UNRECEIVE_STD",
            "IMPORT_SO_OPER_SCRAP_STD", "IMPORT_SO_OPER_UNSCRAP_STD", "MODIFY_SO_STATE_STD");
 
    private Map<String, BiFunction<List<IfsLog>, Map<String, ManufacturingOrder>, List<IfsLog>>> replaceParamMap =
            new ConcurrentHashMap<>();
 
    @PostConstruct
    public void init() {
        replaceParamMap.put("IMPORT_SHOP_ORDER_STD", this::replaceImportShopOrderSTDIfsParam);
        replaceParamMap.put("IMPORT_SO_SMA_SOPER_STD", this::replaceImportSoSmaSoperSTDParam);
        replaceParamMap.put("IMPORT_SHOP_MATERIAL_ALLOC_STD", this::replaceImportShopMaterialAllocSTDParam);
        replaceParamMap.put("MODIFY_SHOP_MATERIAL_ALLOC_STD", this::replaceModifyShopMaterialAllocSTDParam);
        replaceParamMap.put("REMOVE_SHOP_MATERIAL_ALLOC_STD", this::replaceRemoveShopMaterialAllocSTDParam);
        replaceParamMap.put("MODIFY_SHOP_OPERATION_STD", this::replaceModifyShopOperationSTDParam);
        replaceParamMap.put("MODIFY_SO_PRE_CLOSE_STD", this::replaceModifySoPreCloseSTDParam);
        replaceParamMap.put("IMPORT_SO_MATERIAL_ISSUE_STD", this::replaceImportSoMaterialIssueSTDParam);
        replaceParamMap.put("IMPORT_SO_MATERIAL_UNISSUE_STD", this::replaceImportSoMaterialUnissueSTDParam);
        replaceParamMap.put("IMPORT_SO_OPER_REPORT_STD", this::replaceImportSoOperReportSTDParam);
        replaceParamMap.put("IMPORT_SO_RECEIVE_STD", this::replaceImportSoReceiveSTDParam);
        replaceParamMap.put("IMPORT_SO_UNRECEIVE_STD", this::replaceImportSoUnreceiveSTDParam);
        replaceParamMap.put("IMPORT_SO_OPER_SCRAP_STD", this::replaceImportSoOperScrapSTDParam);
        replaceParamMap.put("IMPORT_SO_OPER_UNSCRAP_STD", this::replaceImportSoOperUnscrapSTDParam);
        replaceParamMap.put("MODIFY_SO_STATE_STD", this::replaceModifySoStateSTDParam);
    }
 
 
    @Override
    public IPage<List<ManufacturingOrder>> getManufacturingOrderPage(Page page, QueryWrapper<ManufacturingOrderDTO> query, List<Long> list) {
        IPage<List<ManufacturingOrder>> manufacturingOrderPageList;
        if (CollectionUtil.isNotEmpty(list)) {
            manufacturingOrderPageList = baseMapper.getManufacturingOrderPageByCustomer(page, query, list);
        } else {
            // 拼接crosstab所需要的验证数据
            OrderParam orderParam = orderParamMapper.getParam();
            manufacturingOrderPageList = baseMapper.getManufacturingOrderPage(page, query, orderParam);
        }
        return manufacturingOrderPageList;
    }
 
    @Override
    public ManufacturingOrderDTO selectById(Long id) {
        ManufacturingOrderDTO manufacturingOrderDTO = baseMapper.selectDtoById(id);
        // 1.根据产品查对应的所有工艺
        manufacturingOrderDTO.setRoutingList(routingMapper.selectList(Wrappers.<Routing>query().lambda().eq(Routing::getPartId, manufacturingOrderDTO.getPartId())
                .eq(Routing::getState, RoutingStateStringValues.ACCEPTED).eq(Routing::getBomTypeDb,
                        manufacturingOrderDTO.getWorkshopTypeCode()).orderByDesc(Routing::getRoutingNo)));
        // 2.根据产品查对应的所有BOM结构
        manufacturingOrderDTO.setBomList(bomMapper.selectList(Wrappers.<Bom>query().lambda()
                .eq(Bom::getPartId, manufacturingOrderDTO.getPartId())
                .eq(Bom::getState, BomStateStringValues.ACCEPTED)
                .eq(Bom::getBomTypeDb, manufacturingOrderDTO.getWorkshopTypeCode()).orderByDesc(Bom::getNumber)));
        // 3.查询对应的产出批次信息
        manufacturingOrderDTO.setOutBatchList(moOutBatchMapper.selectMoOutBatchByManufacturingOrderId(id));
        // 4.如果挂上产品结构id,取这边备份的产品结构组件
        manufacturingOrderDTO.setBomRoot(buildTree(moStructureComponentMapper.selectListByManufacturingOrderId(id)));
        // 5.添加出料表
        manufacturingOrderDTO.setManufacturingOrderMatIssueList(manufacturingOrderMatIssueMapper.selectList(Wrappers.<ManufacturingOrderMatIssue>lambdaQuery()
                .eq(ManufacturingOrderMatIssue::getMoId, manufacturingOrderDTO.getId())));
        // 6.添加车间订单对应工序
        manufacturingOrderDTO.setMoRoutingOperationDTOList(moRoutingMapper.getMoRoutinOptionDtoByMoId(id));
        // 7.添加段长批次数据
        manufacturingOrderDTO.setOutPutBatchList(operationTaskProduceMapper.selectList(Wrappers.<OperationTaskProduce>lambdaQuery()
                .eq(OperationTaskProduce::getMoId, manufacturingOrderDTO.getId())));
        return manufacturingOrderDTO;
    }
 
 
    private MoStructureComponentDTO buildTree(List<MoStructureComponentDTO> list) {
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        List<MoStructureComponentDTO> roots = list.stream().filter(e -> e.getParent() == null || e.getParent() == 0).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(roots)) {
            return null;
        }
        if (roots.size() > 1) {
            throw new RuntimeException("BOM数据异常,存在多个根节点");
        }
        MoStructureComponentDTO root = roots.get(0);
        this.setChildren(root, list);
        return root;
    }
 
 
    private void setChildren(MoStructureComponentDTO node, List<MoStructureComponentDTO> list) {
        List<MoStructureComponentDTO> children = list.stream().filter(e -> e.getParent() != null
                && e.getParent().equals(node.getId())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(children)) {
            return;
        }
        node.setChildren(children);
        children.forEach(e -> {
            setChildren(e, list);
        });
 
    }
 
    /**
     * @param technologyRoutingId 工艺路线id
     * @param moId                制造订单id
     */
    private void addOperationTemplate(Long technologyRoutingId, Long moId) {
        if (null == technologyRoutingId || null == moId) {
            return;
        }
        // 查询出此工艺路线下的所有工序
        RoutingDTO routingDTO = routingService.getRoutingById(technologyRoutingId);
        List<RoutingOperationDTO> operations;
        if (CollectionUtils.isEmpty(operations = routingDTO.getOperations())) {
            return;
        }
        for (RoutingOperationDTO routingOperationDTO : operations) {
            // 根据工序找出工序下配置的参数模板
            fillParamByOperation(moId, null, routingOperationDTO);
            // 根据零件找出绑定的检测标准
            long routingOperationId = routingOperationDTO.getId(); // 工艺路线绑定的工序id
 
            fillStandardByOperation(moId, null, routingOperationDTO);
        }
    }
 
    /**
     * @param moId                 车间订单id
     * @param moRoutingOperationId 车间订单工艺路线工序id
     * @param routingOperationDTO
     */
    private void fillStandardByOperation(Long moId, Long moRoutingOperationId, RoutingOperationDTO routingOperationDTO) {
        List<TestStandardBinding> testStandardBindingList = testStandardBindingMapper.selectList(Wrappers.<TestStandardBinding>lambdaQuery().eq(TestStandardBinding::getPartId, routingOperationDTO.getPartId()).eq(TestStandardBinding::getOperationId, routingOperationDTO.getOperationId()));
        for (TestStandardBinding testStandardBinding : testStandardBindingList) {
            Long standardId = null;
            if (null == (standardId = testStandardBinding.getStandardId())) {
                continue;
            }
            TestStandard testStandard = testStandardMapper.selectById(standardId);
            if (null != testStandard) {
                MoTestStandard moTestStandard = new MoTestStandard();
                moTestStandard.setMoRoutingOperationId(moRoutingOperationId);
                moTestStandard.setStandardNo(testStandard.getStandardNo());
                moTestStandard.setStandardName(testStandard.getStandardName());
                moTestStandard.setInspectionType(testStandard.getInspectionType());
                moTestStandard.setJudgeFormula(testStandard.getJudgeFormula());
                moTestStandard.setVersion(testStandard.getVersion());
                moTestStandard.setRemark(testStandard.getRemark());
                moTestStandard.setMoId(moId);
                moTestStandard.setRoutingOperationId(routingOperationDTO.getId());
                moTestStandardMapper.insert(moTestStandard);
                // 备份检测标准参数
                moTestStandardMapper.copyParamByTestStandardId(moTestStandard.getId(), testStandard.getId());
            }
        }
 
    }
 
    /**
     * @param moId                 车间订单id
     * @param moRoutingOperationId 车间订单工艺路线工序id
     * @param routingOperationDTO  工艺路线
     */
    private void fillParamByOperation(Long moId, Long moRoutingOperationId, RoutingOperationDTO routingOperationDTO) {
        // 查询模板List
        List<RoutingOperationTemplate> routingOperationTemplateList = routingOperationTemplateMapper.selectList(Wrappers.<RoutingOperationTemplate>lambdaQuery()
                .eq(RoutingOperationTemplate::getRoutingOperationId, routingOperationDTO.getId()));
        for (RoutingOperationTemplate routingOperationTemplate : routingOperationTemplateList) {
            ManufacturingOrderOperationTemplate newManufacturingOrderOperationTemplate = insertManufacturingOrderOperationTemplate(
                    routingOperationTemplate, routingOperationDTO.getId(), moRoutingOperationId, moId);
            List<RoutingOperationParam> paramList = routingOperationParamMapper.selectList(Wrappers.<RoutingOperationParam>lambdaQuery()
                    .eq(RoutingOperationParam::getOperationTemplateId, routingOperationTemplate.getId()).orderByAsc(RoutingOperationParam::getId));
            for (RoutingOperationParam param : paramList) {
                ManufacturingOrderOperationParam manufacturingOrderOperationParam = new ManufacturingOrderOperationParam();
                manufacturingOrderOperationParam.setCode(param.getCode());
                manufacturingOrderOperationParam.setParameterItem(param.getParameterItem());
                manufacturingOrderOperationParam.setType(param.getType());
                manufacturingOrderOperationParam.setUnit(param.getUnit());
                manufacturingOrderOperationParam.setParamValue(param.getParamValue());
                manufacturingOrderOperationParam.setRoutingId(routingOperationDTO.getRoutingId());
                manufacturingOrderOperationParam.setOperationId(routingOperationDTO.getOperationId());
                manufacturingOrderOperationParam.setMoRoutingOperationId(moRoutingOperationId);
                manufacturingOrderOperationParam.setRoutingOperationId(routingOperationDTO.getId());
                manufacturingOrderOperationParam.setOperationTemplateId(newManufacturingOrderOperationTemplate.getId());
                manufacturingOrderOperationParamMapper.insert(manufacturingOrderOperationParam);
            }
        }
 
    }
 
    private MoStructureComponentDTO transferBomToMoStructureComponentDTO(BomDTO bomDTO) {
        if (null == bomDTO) {
            return null;
        }
        MoStructureComponentDTO result = new MoStructureComponentDTO();
        StructureTree structureTree = bomDTO.getTree();
        result.setId(structureTree.getId());
        result.setPartId(structureTree.getPartId());
        // 消耗工序 和 工艺路线里面那个工序不是一个意义
        result.setOperationId(bomDTO.getOperationId());
        result.setPartName(structureTree.getPartName());
        result.setPartNo(structureTree.getPartNo());
        result.setQpa(structureTree.getQpa());
        result.setDiscNum(structureTree.getDiscNum());
        List<StructureTree> structureTreeList = structureTree.getChildren();
        List<MoStructureComponentDTO> resultChildren = new ArrayList<>();
        transferBomDeep(structureTreeList, resultChildren, structureTree.getId());
        result.setChildren(resultChildren);
        return result;
    }
 
    private void transferBomDeep(List<StructureTree> listOri, List<MoStructureComponentDTO> listTarget, long parerntId) {
        if (CollectionUtils.isEmpty(listOri)) {
            return;
        }
        for (StructureTree structureTree : listOri) {
            MoStructureComponentDTO moStructureComponentDTO = new MoStructureComponentDTO();
            moStructureComponentDTO.setId(structureTree.getId());
            // 这个工序是消耗工序
            moStructureComponentDTO.setOperationId(structureTree.getOperationId());
            moStructureComponentDTO.setPartId(structureTree.getPartId());
            moStructureComponentDTO.setPartName(structureTree.getPartName());
            moStructureComponentDTO.setPartNo(structureTree.getPartNo());
            moStructureComponentDTO.setQpa(structureTree.getQpa());
            moStructureComponentDTO.setDiscNum(structureTree.getDiscNum());
            moStructureComponentDTO.setParent(parerntId);
            List<StructureTree> children = null;
            if (!CollectionUtils.isEmpty(children = structureTree.getChildren())) {
                List<MoStructureComponentDTO> childrenTarget = new ArrayList<>();
                transferBomDeep(children, childrenTarget, structureTree.getId());
                moStructureComponentDTO.setChildren(childrenTarget);
            }
            listTarget.add(moStructureComponentDTO);
        }
    }
 
    @Override
    public R saveDto(ManufacturingOrderDTO manufacturingOrderDTO) {
        try {
            // 如果是从主生产计划那边创建的制造订单 需要校验需求数量  不能大于销售订单的数量- 库存预留的数量 - 委外订单的数量
            // - 此主生产计划下已经创建的制造订单的需求数量
            Long mpsId = null;
            BigDecimal qtyRequired = null;
            if (null != (mpsId = manufacturingOrderDTO.getMpsId()) && null != (qtyRequired = manufacturingOrderDTO.getQtyRequired())) {
                MasterProductionScheduleDTO masterProductionScheduleDTO = masterProductionScheduleService.getByIdExt(mpsId);
                BigDecimal qtyRequiredSchedule = masterProductionScheduleDTO.getQtyRequired();
                BigDecimal inventoryReservedQuantity = masterProductionScheduleDTO.getInventoryReservedQuantity();
                BigDecimal outsourcingNumber = masterProductionScheduleDTO.getOutsourcingNumber();
                BigDecimal manufacturingQuantity = masterProductionScheduleDTO.getManufacturingQuantity();
                if (inventoryReservedQuantity.add(outsourcingNumber).add(manufacturingQuantity).add(qtyRequired).compareTo(qtyRequiredSchedule) > 0) {
                    return R.failed("制造订单需求数量超过销售订单可下发的数量,请确认!");
                }
            }
            List<CustomerOrder> customerOrderList = new ArrayList<>();
            // 如果从主计划过来的,增加对应的bom下发数量
            if (manufacturingOrderDTO.getMpsStructureComponentId() != null) {
                MpsStructureComponent mpsStructureComponent = mpsStructureComponentMapper.selectById(manufacturingOrderDTO.getMpsStructureComponentId());
                mpsStructureComponent.setManufacturingOrderQuantity(mpsStructureComponent.getManufacturingOrderQuantity().add(manufacturingOrderDTO.getQtyRequired()));
                mpsStructureComponentMapper.updateById(mpsStructureComponent);
                MasterProductionSchedule masterProductionSchedule = masterProductionScheduleMapper.selectById(mpsStructureComponent.getMpsId());
                masterProductionSchedule.setIssued(true);
                masterProductionScheduleMapper.updateById(masterProductionSchedule);
                // 根据主计划去查询客户订单
                customerOrderList = customerOrderMapper.getCustomerOrder(masterProductionSchedule.getId());
            }
            // 主计划 带过来的制造订单 上面的可以是其他版本代码
            if (CollectionUtils.isEmpty(customerOrderList) && null != mpsId) {
                MasterProductionSchedule masterProductionSchedule = masterProductionScheduleMapper.selectById(manufacturingOrderDTO.getMpsId());
                masterProductionSchedule.setIssued(true);
                masterProductionScheduleMapper.updateById(masterProductionSchedule);
                // 根据主计划去查询客户订单
                customerOrderList = customerOrderMapper.getCustomerOrderBySchedule(masterProductionSchedule.getId());
 
            }
            manufacturingOrderDTO.setMoNo(manufacturingOrderNumberGenerator.generateNumberWithPrefix(ManufacturingOrder.DIGIT, ManufacturingOrder.PREFIX, ManufacturingOrder::getMoNo));
            // 1.保存主表
            baseMapper.insert(manufacturingOrderDTO);
            // 查出零件是否配置了工艺路线 有的话 进行保存
            long partId = manufacturingOrderDTO.getPartId();
            // 1.根据产品查对应的所有工艺
            List<Routing> routingList = routingMapper.selectList(Wrappers.<Routing>query().lambda().eq(Routing::getPartId, partId)
                    .eq(Routing::getState, RoutingStateStringValues.ACCEPTED).orderByDesc(Routing::getRoutingNo));
            if (!CollectionUtils.isEmpty(routingList)) {
                manufacturingOrderDTO.setTechnologyRoutingId(routingList.get(0).getId());
                manufacturingOrderDTO.setRoutingList(routingList);
                baseMapper.updateById(manufacturingOrderDTO);
            }
            // 2.根据产品查对应的BOM
            List<Bom> bomList = bomMapper.selectList(Wrappers.<Bom>query().lambda().eq(Bom::getPartId, partId)
                    .eq(Bom::getState, BomStateStringValues.ACCEPTED).orderByDesc(Bom::getNumber));
            if (!CollectionUtils.isEmpty(bomList)) {
                long bomId = bomList.get(0).getId();
                manufacturingOrderDTO.setBomId(bomId);
 
                manufacturingOrderDTO.setBomList(bomList);
                BomDTO bomDTO = bomService.getBomDtoById(bomId);
                MoStructureComponentDTO moStructureComponentDTO = transferBomToMoStructureComponentDTO(bomDTO);
                manufacturingOrderDTO.setBomRoot(moStructureComponentDTO);
                baseMapper.updateById(manufacturingOrderDTO);
            }
            // 如果默认保存时候选了工艺路线号 默认为首次添加工序 自动补充每个工序的工序参数  参数集 及 参数
            addOperationTemplate(manufacturingOrderDTO.getTechnologyRoutingId(), manufacturingOrderDTO.getId());
            // 保存制造订单与客户订单的关系表
            if (CollectionUtil.isNotEmpty(customerOrderList)) {
                for (CustomerOrder customerOrder : customerOrderList) {
                    JoinModelCustomer joinModelCustomer = new JoinModelCustomer();
                    joinModelCustomer.setCustomerOrderId(customerOrder.getId());
                    joinModelCustomer.setModel("plan_manufacturing_order");
                    joinModelCustomer.setModelId(manufacturingOrderDTO.getId());
                    joinModelCustomerMapper.insert(joinModelCustomer);
                }
            }
            // 2.保存结构
            if (manufacturingOrderDTO.getBomRoot() != null) {
                cycleSave(manufacturingOrderDTO.getId(), null, manufacturingOrderDTO.getBomRoot());
            }
            // copyTemplateParam(manufacturingOrderDTO);
            if (manufacturingOrderDTO.getId() != null) {
                ManufacturingOrder manufacturingOrder = baseMapper.selectById(manufacturingOrderDTO.getId());
                manufacturingOrderDTO.setState(manufacturingOrder.getState());
            }
        } catch (Exception e) {
            log.error("制造订单创建失败", e);
            return R.failed("制造订单创建失败");
        }
        return R.ok(manufacturingOrderDTO);
    }
 
 
    public void copyTemplateParam(ManufacturingOrderDTO manufacturingOrderDTO) {
        List<RoutingOperation> routingOperationList = routingOperationMapper.selectList(Wrappers.<RoutingOperation>lambdaQuery().eq(RoutingOperation::getRoutingId, manufacturingOrderDTO.getTechnologyRoutingId()));
        if (CollectionUtil.isNotEmpty(routingOperationList)) {
            for (RoutingOperation routingOperation : routingOperationList) {
                List<RoutingOperationTemplate> routingOperationTemplateList = routingOperationTemplateMapper.selectList(Wrappers.<RoutingOperationTemplate>lambdaQuery().eq(RoutingOperationTemplate::getRoutingOperationId, routingOperation.getId()));
                if (CollectionUtil.isNotEmpty(routingOperationTemplateList)) {
                    for (RoutingOperationTemplate routingOperationTemplate : routingOperationTemplateList) {
                        // 根据工序模板复制对应的工序模板
                        manufacturingOrderOperationTemplateMapper.copy(routingOperationTemplate.getId(), manufacturingOrderDTO.getId(), numberGenerator.generateNumberWithPrefix(ManufacturingOrderOperationTemplate.DIGIT, ManufacturingOrderOperationTemplate.PREFIX, ManufacturingOrderOperationTemplate::getSystemNo));
                        ManufacturingOrderOperationTemplate manufacturingOrderOperationTemplate = manufacturingOrderOperationTemplateMapper.selectOne(Wrappers.<ManufacturingOrderOperationTemplate>lambdaQuery().eq(ManufacturingOrderOperationTemplate::getRoutingOperationId, routingOperation.getId())
                                .eq(ManufacturingOrderOperationTemplate::getOperationTemplateNo, routingOperationTemplate.getOperationTemplateNo()).eq(ManufacturingOrderOperationTemplate::getMoId, manufacturingOrderDTO.getId()));
                        // 根据工序模板复制对应的工序参数
                        manufacturingOrderOperationParamMapper.copy(manufacturingOrderOperationTemplate.getId(), routingOperationTemplate.getRoutingOperationId(), routingOperationTemplate.getId());
                    }
                }
            }
        }
    }
 
    @Override
    public R updateDtoById(ManufacturingOrderDTO manufacturingOrder) {
        try {
            // 先修改
            manufacturingOrder.setIfsSync(false);
            /**
             *  下面内容是原先逻辑针对 车间订单工艺路线被修改后执行的操作
             *  当前车间订单暂时不支持工艺路线修改,如果要修改工艺路线需要调用IFS工艺路线和材料删除接口
             */
            MoRouting moRouting = moRoutingMapper.selectOne(Wrappers.<MoRouting>lambdaQuery().eq(MoRouting::getMoId, manufacturingOrder.getId()));
            // 判断工艺路线有没有被修改
            if (!moRouting.getTechnologyRoutingId().equals(manufacturingOrder.getTechnologyRoutingId())) {
                // 工艺路线被修改了 就将所有的bom工艺路线下面的参数集,检测标准数据全部删掉重新添加
                // 1、删除车间订单BOM
                moStructureComponentMapper.delete(Wrappers.<MoStructureComponent>query().lambda().eq(MoStructureComponent::getPlanManufacturingOrderId, manufacturingOrder.getId()));
                // 2、删除检测标准明细
                moTestStandardParamMapper.delByMoId(manufacturingOrder.getId());
                // 3、删除检测标准主表
                moTestStandardMapper.delete(Wrappers.<MoTestStandard>lambdaQuery().eq(MoTestStandard::getMoId, manufacturingOrder.getId()));
                // 4、删除参数模板机主从表
                manufacturingOrderOperationParamMapper.delByMoId(manufacturingOrder.getId());
                manufacturingOrderOperationTemplateMapper.delete(Wrappers.<ManufacturingOrderOperationTemplate>lambdaQuery().eq(ManufacturingOrderOperationTemplate::getMoId, manufacturingOrder.getId()));
                // 5、删除工艺路线
                moRoutingOperationMapper.delete(Wrappers.<MoRoutingOperation>lambdaQuery().eq(MoRoutingOperation::getMoId, manufacturingOrder.getId()));
                moRoutingMapper.delete(Wrappers.<MoRouting>lambdaQuery().eq(MoRouting::getMoId, manufacturingOrder.getId()));
                // 6、新增工艺路线
                if (manufacturingOrder.getBomId() != null) {
                    BomDTO bomDTO = bomService.getBomDtoById(manufacturingOrder.getBomId());
                    MoStructureComponentDTO moStructureComponentDTO = transferBomToMoStructureComponentDTO(bomDTO);
                    cycleSave(manufacturingOrder.getId(), null, moStructureComponentDTO);
                }
                // 7、新增车间订单检测标准,模板参数和工艺路线
                addMoParams(manufacturingOrder);
            }
            // 没有修改工艺路线 主要将主表的数据保存就行了
            baseMapper.updateById(manufacturingOrder);
            return R.ok();
        } catch (Exception e) {
            return R.failed("修改异常");
        }
    }
 
    /**
     * 递归保存
     *
     * @param manufacturingOrderId
     * @param parentId
     * @param node
     */
    private void cycleSave(Long manufacturingOrderId, Long parentId, MoStructureComponentDTO node) {
        node.setParent(parentId);
        node.setPlanManufacturingOrderId(manufacturingOrderId);
        node.setDiscNum(null == node.getDiscNum() ? 1L : node.getDiscNum());
        moStructureComponentMapper.insert(node);
        if (CollectionUtil.isNotEmpty(node.getChildren())) {
            for (MoStructureComponentDTO child : node.getChildren()) {
                cycleSave(manufacturingOrderId, node.getId(), child);
            }
        }
    }
 
 
    @Override
    public ManufacturingOrderDTO checkPart(Long partId, String workshopTypeCode) {
        ManufacturingOrderDTO manufacturingOrderDTO = new ManufacturingOrderDTO();
        // 1.根据产品查对应的所有工艺
        List<Routing> routingList = routingMapper.selectList(Wrappers.<Routing>query().lambda().eq(Routing::getPartId, partId)
                .eq(Routing::getState, RoutingStateStringValues.ACCEPTED)
                .eq(Routing::getBomTypeDb, workshopTypeCode).orderByDesc(Routing::getId));
        manufacturingOrderDTO.setRoutingList(routingList);
        if (CollectionUtil.isNotEmpty(routingList)) {
            manufacturingOrderDTO.setTechnologyRoutingId(routingList.get(0).getId());
            manufacturingOrderDTO.setBomId(routingList.get(0).getBomId());
        }
        // 2.根据产品查对应的所有产品结构
        List<Bom> bomList = bomMapper.selectList(Wrappers.<Bom>query().lambda().eq(Bom::getPartId, partId)
                .eq(Bom::getState, BomStateStringValues.ACCEPTED)
                .eq(Bom::getBomTypeDb, workshopTypeCode).orderByDesc(Bom::getNumber));
        manufacturingOrderDTO.setBomList(bomList);
        return manufacturingOrderDTO;
    }
 
    @Override
    public boolean changeState(List<Long> ids, String event) {
        for (Long id : ids) {
            ManufacturingOrder manufacturingOrder = baseMapper.selectById(id);
            if ("04canceled".equals(manufacturingOrder.getState())) {
                throw new RuntimeException("不允许更改已取消的车间订单状态");
            }
            if ("CANCEL".equals(event)) {
                List<String> operationState = baseMapper.getAllStateByMoId(id);
                if (!operationState.stream().allMatch("05canceled"::equals)) {
                    throw new RuntimeException("车间订单下所有工单状态为已取消,才可修改车间订单状态为已取消");
                }
            }
            Message<ManufacturingOrderEvents> message = MessageBuilder.withPayload(ManufacturingOrderEvents.valueOf(event)).setHeader("manufacturingOrder", manufacturingOrder).build();
            StateMachineHandler handler = new StateMachineHandler(manufacturingOrderStateMachineFactory, persister, ManufacturingOrderStateMachineConfig.MACHINE_ID, manufacturingOrder);
            StateResult res = handler.sendEvent(message, manufacturingOrder.getId());
            if (!res.isSuccess()) {
                throw new RuntimeException(res.getMsg());
            }
        }
        return true;
    }
 
    @Override
    public Object checkoutManufacturingOrder(ManufacturingOrderDTO manufacturingOrderDTO) {
        int count = baseMapper.selectCount(Wrappers.<ManufacturingOrder>lambdaQuery().eq(ManufacturingOrder::getTechnologyRoutingId, manufacturingOrderDTO.getTechnologyRoutingId()).eq(ManufacturingOrder::getId, manufacturingOrderDTO.getId()));
        JSONObject order = new JSONObject();
        if (count > 0) {
            order.put("status", "1");
        } else {
            order.put("status", "0");
        }
        return order;
    }
 
    @Override
    public List<ManufacturingOrderOperationTemplate> getOperationTemplate(ManufacturingOrderDTO manufacturingOrderDTO) {
        List<ManufacturingOrderOperationTemplate> manufacturingOrderOperationTemplateList = manufacturingOrderOperationTemplateMapper.selectList(Wrappers.<ManufacturingOrderOperationTemplate>lambdaQuery()
                .eq(ManufacturingOrderOperationTemplate::getMoRoutingOperationId, manufacturingOrderDTO.getMoRoutingOperationId())
                .eq(ManufacturingOrderOperationTemplate::getMoId, manufacturingOrderDTO.getId()));
        if (!CollectionUtil.isNotEmpty(manufacturingOrderOperationTemplateList)) {
            manufacturingOrderOperationTemplateList = new ArrayList<>();
        }
        return manufacturingOrderOperationTemplateList;
    }
 
    @Override
    public boolean deleteRoutingTemplate(Long id) {
        ManufacturingOrderOperationTemplate manufacturingOrderOperationTemplate = manufacturingOrderOperationTemplateMapper.selectById(id);
        manufacturingOrderOperationTemplateMapper.deleteById(id);
        manufacturingOrderOperationParamMapper.delete(Wrappers.<ManufacturingOrderOperationParam>lambdaQuery().eq(ManufacturingOrderOperationParam::getOperationTemplateId, id));
        return false;
    }
 
    /**
     * 根据车间订单工序添加模板
     *
     * @param manufacturingOrderDTO
     * @return
     */
    @Override
    public List<ManufacturingOrderOperationTemplate> addOperationTemplate(ManufacturingOrderDTO manufacturingOrderDTO) {
        List<ManufacturingOrderOperationTemplate> manufacturingOrderOperationTemplateList = new ArrayList<>();
        // 查询车间订单工序
        MoRoutingOperation moRoutingOperation = moRoutingOperationMapper.selectById(manufacturingOrderDTO.getMoRoutingOperationId());
        // 查询车间订单工序
        RoutingOperation routingOperation = routingOperationMapper.selectById(moRoutingOperation.getTechnologyRoutingOperationId());
        for (RoutingOperationTemplate routingOperationTemplate : manufacturingOrderDTO.getRoutingOperationTemplateList()) {
            // 添加参数模板集合
            ManufacturingOrderOperationTemplate manufacturingOrderOperationTemplate = insertManufacturingOrderOperationTemplate(routingOperationTemplate, moRoutingOperation.getTechnologyRoutingOperationId(), moRoutingOperation.getId(), manufacturingOrderDTO.getId());
            // 通过工序模板id获取工序参数
            if (routingOperationTemplate.getId() != null) {
                // 根据模板id去查询模板参数
                List<RoutingOperationParam> paramList = routingOperationParamMapper.selectList(Wrappers.<RoutingOperationParam>lambdaQuery()
                        .eq(RoutingOperationParam::getOperationTemplateId, routingOperationTemplate.getId())
                        .orderByAsc(RoutingOperationParam::getId));
                if (CollectionUtil.isNotEmpty(paramList)) {
                    for (RoutingOperationParam param : paramList) {
                        ManufacturingOrderOperationParam manufacturingOrderOperationParam = new ManufacturingOrderOperationParam();
                        manufacturingOrderOperationParam.setCode(param.getCode());
                        manufacturingOrderOperationParam.setParameterItem(param.getParameterItem());
                        manufacturingOrderOperationParam.setRoutingId(routingOperation.getRoutingId());
                        manufacturingOrderOperationParam.setOperationId(moRoutingOperation.getOperationId());
                        manufacturingOrderOperationParam.setType(param.getType());
                        manufacturingOrderOperationParam.setUnit(param.getUnit());
                        manufacturingOrderOperationParam.setParamValue(param.getParamValue());
                        manufacturingOrderOperationParam.setMoRoutingOperationId(moRoutingOperation.getId());
                        manufacturingOrderOperationParam.setRoutingOperationId(moRoutingOperation.getTechnologyRoutingOperationId());
                        manufacturingOrderOperationParam.setOperationTemplateId(manufacturingOrderOperationTemplate.getId());
                        manufacturingOrderOperationParamMapper.insert(manufacturingOrderOperationParam);
                    }
                }
            }
            manufacturingOrderOperationTemplateList.add(manufacturingOrderOperationTemplate);
        }
        return manufacturingOrderOperationTemplateList;
    }
 
    /**
     * @param routingOperationTemplate 模板
     * @param routingOperationId       工艺工序id
     * @param moRoutingOperationId     车间订单工艺工序id
     * @param moId                     车间订单id
     * @return
     */
    private ManufacturingOrderOperationTemplate insertManufacturingOrderOperationTemplate(RoutingOperationTemplate routingOperationTemplate, Long routingOperationId, Long moRoutingOperationId, Long moId) {
        ManufacturingOrderOperationTemplate manufacturingOrderOperationTemplate = new ManufacturingOrderOperationTemplate();
        manufacturingOrderOperationTemplate.setRoutingOperationId(routingOperationId);
        manufacturingOrderOperationTemplate.setOperationTemplateType(routingOperationTemplate.getOperationTemplateType());
        manufacturingOrderOperationTemplate.setOperationTemplateNo(routingOperationTemplate.getOperationTemplateNo());
        manufacturingOrderOperationTemplate.setMoRoutingOperationId(moRoutingOperationId);
        manufacturingOrderOperationTemplate.setOperationTemplateName(routingOperationTemplate.getOperationTemplateName());
        manufacturingOrderOperationTemplate.setRemark(routingOperationTemplate.getRemark());
        manufacturingOrderOperationTemplate.setMoId(moId);
        manufacturingOrderOperationTemplate.setDataType(routingOperationTemplate.getDataType());
        manufacturingOrderOperationTemplate.setSystemNo(numberGenerator.generateNumberWithPrefix(ManufacturingOrderOperationTemplate.DIGIT, ManufacturingOrderOperationTemplate.PREFIX, ManufacturingOrderOperationTemplate::getSystemNo));
        manufacturingOrderOperationTemplateMapper.insert(manufacturingOrderOperationTemplate);
        return manufacturingOrderOperationTemplate;
    }
 
    @Override
    public List<ManufacturingOrderOperationParam> getOperationTemplateParam(ManufacturingOrderDTO manufacturingOrderDTO) {
        List<ManufacturingOrderOperationParam> manufacturingOrderOperationParamList = manufacturingOrderOperationParamMapper.selectList(Wrappers.<ManufacturingOrderOperationParam>lambdaQuery()
                .eq(ManufacturingOrderOperationParam::getOperationTemplateId, manufacturingOrderDTO.getOperationTemplateId())
                .orderByAsc(ManufacturingOrderOperationParam::getId));
        if (!CollectionUtil.isNotEmpty(manufacturingOrderOperationParamList)) {
            manufacturingOrderOperationParamList = new ArrayList<>();
        }
        return manufacturingOrderOperationParamList;
    }
 
    @Override
    public boolean deleteRoutingTemplateParam(Long id) {
        manufacturingOrderOperationParamMapper.deleteById(id);
        return false;
    }
 
    @Override
    public List<ManufacturingOrderOperationParam> addOperationTemplateParam(ManufacturingOrderDTO manufacturingOrderDTO) {
        List<ManufacturingOrderOperationParam> manufacturingOrderOperationParamList = new ArrayList<>();
        // 查询车间订单工序
        MoRoutingOperation moRoutingOperation = moRoutingOperationMapper.selectById(manufacturingOrderDTO.getMoRoutingOperationId());
        // 根据工序id查询工艺工序
        RoutingOperation routingOperation = routingOperationMapper.selectById(moRoutingOperation.getTechnologyRoutingOperationId());
        for (ManufacturingOrderOperationParam manufacturingOrderOperationParam : manufacturingOrderDTO.getRoutingOperationParam()) {
            int count = manufacturingOrderOperationParamMapper.selectCount(Wrappers.<ManufacturingOrderOperationParam>lambdaQuery()
                    .eq(ManufacturingOrderOperationParam::getRoutingOperationId, manufacturingOrderDTO.getRoutingOperationId())
                    .eq(ManufacturingOrderOperationParam::getOperationTemplateId, manufacturingOrderDTO.getOperationTemplateId())
                    .eq(ManufacturingOrderOperationParam::getCode, manufacturingOrderOperationParam.getCode()));
            if (count > 0) {
                continue;
            }
            manufacturingOrderOperationParam.setMoRoutingOperationId(moRoutingOperation.getId());
            manufacturingOrderOperationParam.setRoutingOperationId(manufacturingOrderDTO.getRoutingOperationId());
            manufacturingOrderOperationParam.setOperationTemplateId(manufacturingOrderDTO.getOperationTemplateId());
            manufacturingOrderOperationParam.setRoutingId(routingOperation.getRoutingId());
            manufacturingOrderOperationParam.setOperationId(routingOperation.getOperationId());
            manufacturingOrderOperationParamMapper.insert(manufacturingOrderOperationParam);
            manufacturingOrderOperationParamList.add(manufacturingOrderOperationParam);
        }
        return manufacturingOrderOperationParamList;
    }
 
    @Override
    public boolean updateRoutingTemplateParamById(ManufacturingOrderDTO manufacturingOrderDTO) {
        for (ManufacturingOrderOperationParam manufacturingOrderOperationParam : manufacturingOrderDTO.getRoutingOperationParam()) {
            manufacturingOrderOperationParamMapper.updateById(manufacturingOrderOperationParam);
        }
        return true;
    }
 
    @Override
    public ManufacturingOrderOperationTemplate updateTemplate(ManufacturingOrderOperationTemplate manufacturingOrderOperationTemplate) {
        manufacturingOrderOperationTemplateMapper.updateById(manufacturingOrderOperationTemplate);
        return manufacturingOrderOperationTemplate;
    }
 
    @Override
    public MoStructureComponentDTO bomSelectChange(Long bomId) {
        List<MoStructureComponentDTO> bomNodes = moStructureComponentMapper.selectBomComponents(bomId);
        return buildTree(bomNodes);
    }
 
    @Override
    public List<CustomerOrder> getCustomer(Long id) {
        return customerOrderMapper.getCustomerOrderByOrder(id);
    }
 
    @Override
    public IPage<ManufacturingOrderDTO> getStatementPage(Page page, QueryWrapper<ManufacturingOrderDTO> gen) {
 
        IPage<ManufacturingOrderDTO> manufacturingOrderDTOIPage = baseMapper.getStatementPage(page, gen);
        // 进行按照工序名称 排序
        /*List<ManufacturingOrderDTO> manufacturingOrderDTOList = manufacturingOrderDTOIPage.getRecords();
        Set<Long> technologyRoutingIdSet = manufacturingOrderDTOList.stream().filter(e -> null != e.getTechnologyRoutingId())
                .map(ManufacturingOrderDTO::getTechnologyRoutingId).sorted()
                .collect(Collectors.toCollection(TreeSet::new));
        List<ManufacturingOrderDTO> result = new ArrayList<>();
        for (long technologyRoutingId : technologyRoutingIdSet) {
            RoutingDTO routingDTO = routingService.getRoutingById(technologyRoutingId);
            if (null == routingDTO) {
                continue;
            }
            List<String> operationNameList = routingDTO.getOperations().stream().map(RoutingOperationDTO::getOperationName)
                    .collect(Collectors.toList());
            for (String operationName : operationNameList) {
                Optional<ManufacturingOrderDTO> opt = manufacturingOrderDTOList.stream()
                        .filter(e -> null != e.getTechnologyRoutingId() && technologyRoutingId == e.getTechnologyRoutingId()
                                && null != e.getName() && e.getName().equals(operationName))
                        .findFirst();
                if (opt.isPresent()) {
                    result.add(opt.get());
                }
            }
        }
        manufacturingOrderDTOIPage.setRecords(result);*/
        return manufacturingOrderDTOIPage;
    }
 
    private void mulDisnum(MoStructureComponentDTO moStructureComponentDTO, Long parentId) {
        if (null != parentId) {
            MoStructureComponent moStructureComponent = moStructureComponentMapper.selectOne(Wrappers.<MoStructureComponent>lambdaQuery()
                    .eq(MoStructureComponent::getId, parentId));
            Long parentDisNum = null == moStructureComponent.getDiscNum() ? 1L : moStructureComponent.getDiscNum();
            moStructureComponentDTO.setDiscNum(moStructureComponentDTO.getDiscNum() * parentDisNum);
 
            mulDisnum(moStructureComponentDTO, moStructureComponent.getParent());
        }
 
    }
 
    @Override
    public List<MoStructureComponentDTO> getQpaNumber(Long id, Long partId) {
        List<MoStructureComponentDTO> moStructureComponentDTOS = moStructureComponentMapper.selectQpaByManufacturingOrderIdAndPartId(id, partId);
        for (MoStructureComponentDTO moStructureComponentDTO : moStructureComponentDTOS
        ) {
            Long parent = moStructureComponentDTO.getParent();
            mulDisnum(moStructureComponentDTO, parent);
        }
        return moStructureComponentDTOS;
    }
 
    /**
     * 批量添加
     *
     * @param manufacturingOrderDTOS
     * @return
     */
    @Override
    public R addBatch(List<ManufacturingOrderDTO> manufacturingOrderDTOS) {
        try {
            batchSaveDto(manufacturingOrderDTOS);
            return R.ok();
        } catch (Exception e) {
            log.error("制造订单创建失败", e);
            return R.failed("制造订单创建失败" + e.getMessage());
        }
    }
 
    /**
     * 批量添加
     *
     * @param manufacturingOrderDTOS
     * @return
     */
    @Override
    public List<ManufacturingOrderDTO> addAll(List<ManufacturingOrderDTO> manufacturingOrderDTOS) throws Exception {
        return batchSaveDto(manufacturingOrderDTOS);
    }
 
 
    @Override
    public void addBatchForMerge(List<ManufacturingOrderDTO> manufacturingOrderList, List<RoutingOperationDTO> routingOperations, Boolean isGenerateSn) {
        // 理论产量id , ManufacturingOrderDTO 的 map
        Map<Long, ManufacturingOrderDTO> map = new HashMap<>();
        // 成品车间订单
        List<ManufacturingOrderDTO> finishedMos = new ArrayList<>();
        // 首先得将所有的车间订单全部保存
        for (ManufacturingOrderDTO manufacturingOrderDTO : manufacturingOrderList) {
            // 保存
            ManufacturingOrderDTO manufacturingOrder = saveSingle(manufacturingOrderDTO);
            // 理论产量id  : 车间订单
            map.put(manufacturingOrder.getPartId(), manufacturingOrder);
            // 如果是成品车间订单
            if (BooleanUtil.isTrue(manufacturingOrder.getIsFinishedProduct())) {
                finishedMos.add(manufacturingOrder);
            }
        }
        // 执行关联操作
        for (ManufacturingOrderDTO manufacturingOrderDTO : finishedMos) {
            addOperationTackProduce(manufacturingOrderDTO, map, routingOperations, isGenerateSn);
        }
    }
 
 
    /**
     * 新的保存接口,原先的保存接口先放那里 不用了
     *
     * @param manufacturingOrderDTO
     * @return
     */
    @Override
    public R fullSave(ManufacturingOrderDTO manufacturingOrderDTO) {
        try {
            return R.ok(saveSingleDto(manufacturingOrderDTO));
        } catch (Exception e) {
            log.error("制造订单创建失败", e);
            return R.failed("制造订单创建失败" + e.getMessage());
        }
    }
 
 
    /**
     * 单个新增车间订单
     *
     * @param manufacturingOrderDTO
     * @return
     * @throws Exception
     */
    private ManufacturingOrderDTO saveSingleDto(ManufacturingOrderDTO manufacturingOrderDTO) throws Exception {
        // 理论产量id , ManufacturingOrderDTO 的 map
        Map<Long, ManufacturingOrderDTO> map = new HashMap<>();
        // 成品车间订单
        List<ManufacturingOrderDTO> finishedMos = new ArrayList<>();
        // 保存
        ManufacturingOrderDTO manufacturingOrder = saveSingle(manufacturingOrderDTO);
        // 理论产量id  : 车间订单
        map.put(manufacturingOrder.getScheduleTheoryQuantityId(), manufacturingOrder);
        // 如果是成品车间订单
        if (BooleanUtil.isTrue(manufacturingOrder.getIsFinishedProduct())) {
            finishedMos.add(manufacturingOrder);
        }
        // 执行关联操作
        // if (CollectionUtil.isNotEmpty(finishedMos)) {
        //     addOperationTackProduce(manufacturingOrder, map);
        // }
        return manufacturingOrder;
    }
 
    /**
     * 批量新增车间订单
     *
     * @param manufacturingOrderList
     * @return
     * @throws Exception
     */
    private List<ManufacturingOrderDTO> batchSaveDto(List<ManufacturingOrderDTO> manufacturingOrderList) throws Exception {
        // 理论产量id , ManufacturingOrderDTO 的 map
        Map<Long, ManufacturingOrderDTO> map = new HashMap<>();
        // 成品车间订单
        List<ManufacturingOrderDTO> finishedMos = new ArrayList<>();
        // 首先得将所有的车间订单全部保存
        for (ManufacturingOrderDTO manufacturingOrderDTO : manufacturingOrderList) {
            // 保存
            ManufacturingOrderDTO manufacturingOrder = saveSingle(manufacturingOrderDTO);
            // 理论产量id  : 车间订单
            map.put(manufacturingOrder.getScheduleTheoryQuantityId(), manufacturingOrder);
            // 如果是成品车间订单
            if (BooleanUtil.isTrue(manufacturingOrder.getIsFinishedProduct())) {
                finishedMos.add(manufacturingOrder);
            }
        }
        // 执行关联操作
        // for (ManufacturingOrderDTO manufacturingOrderDTO : finishedMos) {
        //     addOperationTackProduce(manufacturingOrderDTO, map);
        // }
        return manufacturingOrderList;
    }
 
    /**
     * 保存车间订单
     *
     * @param manufacturingOrderDTO
     * @return
     */
    private ManufacturingOrderDTO saveSingle(ManufacturingOrderDTO manufacturingOrderDTO) {
        // 修改生产计划的状态
        if (manufacturingOrderDTO.getMpsId() != null) {
            MasterProductionSchedule masterProductionSchedule = masterProductionScheduleMapper.selectById(manufacturingOrderDTO.getMpsId());
            if (!masterProductionSchedule.getIsAudit().equals(AuditStateStringValues.ACCEPTED)) {
                throw new RuntimeException(masterProductionSchedule.getMpsNo() + "未通过审核");
            }
            // 修改主计划的状态
            if (masterProductionSchedule.getState().equals(MasterProductionScheduleStateStringValues.PENDING)) {
                masterProductionSchedule.setState(MasterProductionScheduleStateStringValues.PROCESSED);
            }
            masterProductionSchedule.setIssued(true);
            masterProductionScheduleMapper.updateById(masterProductionSchedule);
        }
        // 如果前台没有传工艺路线id 就说明是从车间订单页面新增的 那根据车间订单的零件查询工艺路线和BOM 如果传了说明是从生产计划那边生成的车间订单就不要查询了
        LambdaQueryWrapper lambdaQueryWrapper;
        if (manufacturingOrderDTO.getTechnologyRoutingId() == null) {
            lambdaQueryWrapper = Wrappers.<Routing>lambdaQuery()
                    .eq(Routing::getPartId, manufacturingOrderDTO.getPartId())
                    .eq(Routing::getState, RoutingStateStringValues.ACCEPTED).orderByAsc(Routing::getId);
        } else {
            lambdaQueryWrapper = Wrappers.<Routing>lambdaQuery()
                    .eq(Routing::getId, manufacturingOrderDTO.getTechnologyRoutingId());
        }
        List<Routing> routingList = routingMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(routingList)) {
            manufacturingOrderDTO.setBomId(routingList.get(0).getBomId());
            manufacturingOrderDTO.setTechnologyRoutingId(routingList.get(0).getId());
        }
        // 将零件对应的所有bom传给前台
        manufacturingOrderDTO.setBomList(bomMapper.selectList(Wrappers.<Bom>lambdaQuery()
                .eq(Bom::getPartId, manufacturingOrderDTO.getPartId())
                .eq(Bom::getState, BomStateStringValues.ACCEPTED).orderByDesc(Bom::getNumber)));
        manufacturingOrderDTO.setRoutingList(routingList);
        manufacturingOrderDTO.setIfsSync(false);
        manufacturingOrderDTO.setMoNo(manufacturingOrderNumberGenerator.generateNumberWithPrefix(ManufacturingOrder.DIGIT, ManufacturingOrder.PREFIX, ManufacturingOrder::getMoNo));
        manufacturingOrderDTO.setState(ManufacturingOrderStates.PLANNED.getValue());
        // 1.保存主表
        baseMapper.insert(manufacturingOrderDTO);
        // 2、生成车间订单BOM
        if (manufacturingOrderDTO.getBomId() != null) {
            BomDTO bomDTO = bomService.getBomDtoById(manufacturingOrderDTO.getBomId());
            MoStructureComponentDTO moStructureComponentDTO = transferBomToMoStructureComponentDTO(bomDTO);
            manufacturingOrderDTO.setBomRoot(moStructureComponentDTO);
            cycleSave(manufacturingOrderDTO.getId(), null, manufacturingOrderDTO.getBomRoot());
        }
        // 3、新增车间订单工艺路线,车间订单工艺路线工序,参数集模板,车间订单对应检测标准
        addMoParams(manufacturingOrderDTO);
        // 4、新增关联关系
        if (manufacturingOrderDTO.getMpsId() != null) {
            JoinModelCustomer joinModelCustomer = joinModelCustomerMapper.selectOne(Wrappers.<JoinModelCustomer>lambdaQuery()
                    .eq(JoinModelCustomer::getModel, "plan_master_production_schedule")
                    .eq(JoinModelCustomer::getModelId, manufacturingOrderDTO.getMpsId()));
            // 新增关联关系
            if (null != joinModelCustomer) {
                if (null != joinModelCustomer.getCustomerOrderId()) {
                    JoinModelCustomer joinModelCustomersave = new JoinModelCustomer();
                    joinModelCustomersave.setCustomerOrderId(joinModelCustomer.getCustomerOrderId());
                    joinModelCustomersave.setModel("plan_manufacturing_order");
                    joinModelCustomersave.setModelId(manufacturingOrderDTO.getId());
                    joinModelCustomerMapper.insert(joinModelCustomersave);
                    // 查询客户订单
                    CustomerOrder customerOrder = customerOrderMapper.selectById(joinModelCustomer.getCustomerOrderId());
                    if (customerOrder != null) {
                        // 判断你是不是成品车间订单
                        if (customerOrder.getPartNo().equals(manufacturingOrderDTO.getPartNo())) {
                            manufacturingOrderDTO.setIsFinishedProduct(true);
                        }
                    }
                }
 
            }
        }
        return manufacturingOrderDTO;
    }
 
    /**
     * 关联段长和生成SN号码
     *
     * @param manufacturingOrderDTO 车间订单
     * @param map                   理论产量id , ManufacturingOrderDTO 的 map
     */
    private void addOperationTackProduce(ManufacturingOrderDTO manufacturingOrderDTO, Map<Long, ManufacturingOrderDTO> map, List<RoutingOperationDTO> routingOperations, Boolean isGenerateSn) {
        // 获取段长数据
        // List<OperationTaskProduce> operationTaskProduceList = manufacturingOrderDTO.getOutPutBatchList();
        // if (CollectionUtil.isEmpty(operationTaskProduceList)) {
        //     return;
        // }
        // 查询关联关系
        JoinModelCustomer joinModelCustomer = joinModelCustomerMapper.selectOne(Wrappers.<JoinModelCustomer>lambdaQuery()
                .eq(JoinModelCustomer::getModel, "plan_manufacturing_order")
                .eq(JoinModelCustomer::getModelId, manufacturingOrderDTO.getId()));
        if (joinModelCustomer == null) {
            return;
        }
        if (null == joinModelCustomer.getCustomerOrderId()) {
            return;
        }
        // 查询客户订单
        CustomerOrder customerOrder = customerOrderMapper.selectById(joinModelCustomer.getCustomerOrderId());
        if (customerOrder == null) {
            return;
        }
        // 判断你是不是成品车间订单
        if (!customerOrder.getPartNo().equals(manufacturingOrderDTO.getPartNo())) {
            return;
        }
        // 更新段长数据
        // for (OperationTaskProduce operationTaskProduce : operationTaskProduceList) {
        //     operationTaskProduce.setMoId(manufacturingOrderDTO.getId());
        //     operationTaskProduceMapper.updateById(operationTaskProduce);
        // }
        if (manufacturingOrderDTO.getMpsId() == null) {
            return;
        }
        // 查询主计划
        MasterProductionSchedule masterProductionSchedule = masterProductionScheduleMapper.selectById(manufacturingOrderDTO.getMpsId());
        if (masterProductionSchedule == null) {
            return;
        }
        // 生成段长系统号
        generateDocumentSN(customerOrder.getCustomerOrderNo(), masterProductionSchedule, manufacturingOrderDTO, masterProductionSchedule.getManufactureAttr(), map, routingOperations, isGenerateSn);
    }
 
    /**
     * @param customerOrderNo          客户订单编号
     * @param masterProductionSchedule 主计划
     * @param manufacturingOrderDTO    车间订单
     * @param manufactureAttr          制造属性
     */
    public void generateDocumentSN(String customerOrderNo, MasterProductionSchedule masterProductionSchedule,
                                   ManufacturingOrderDTO manufacturingOrderDTO, String manufactureAttr,
                                   Map<Long, ManufacturingOrderDTO> map, List<RoutingOperationDTO> routingOperations, Boolean isGenerateSn) {
        // 根据车间订单查询段长
        List<OperationTaskProduce> operationTaskProduces = operationTaskProduceMapper.selectList(
                Wrappers.<OperationTaskProduce>lambdaQuery()
                        .eq(OperationTaskProduce::getMoId, manufacturingOrderDTO.getId()));
        // 根据id 拼接 成品SN号码
        String productSns = org.apache.commons.lang3.StringUtils.join(
                operationTaskProduces.stream().filter(p -> StringUtils.isNotBlank(p.getSnNo()))
                        .sorted(Comparator.comparing(OperationTaskProduce::getId))
                        .map(OperationTaskProduce::getSnNo).collect(Collectors.toList()), ",");
        // 查询库存件
        List<JoinDocumentBomRoutingDTO> joinDocBomRoutingList = documentMapper.getBomRoutingDtoPartByDocId(masterProductionSchedule.getTechnologyDocumentId());
        // 查询根节点
        JoinDocumentBomRoutingDTO joinDocumentBomRoutingRoot = documentMapper.getRootBomRoutingDtoPartByDocId(masterProductionSchedule.getTechnologyDocumentId());
        // 生成SN号
        if (CollectionUtil.isNotEmpty(joinDocBomRoutingList) && joinDocumentBomRoutingRoot != null) {
            // 找出所有开始的节点
            List<JoinDocumentBomRouting> startRoutings = joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery()
                    .eq(JoinDocumentBomRouting::getDocumentId, masterProductionSchedule.getTechnologyDocumentId())
                    .in(JoinDocumentBomRouting::getRoutingId, routingOperations.stream().map(RoutingOperation::getRoutingId).collect(Collectors.toList())));
 
            List<JoinDocumentBomRoutingDTO> totalRoutings = new ArrayList<>();
            // 递归找出所有的节点
            for (JoinDocumentBomRouting startRouting : startRoutings) {
                RoutingOperationDTO routingOperationDTO = routingOperations.stream().filter(p -> p.getRoutingId().equals(startRouting.getRoutingId())).findFirst().get();
                List<JoinDocumentBomRouting> routings = joinDocumentBomRoutingMapper.findAllParentBomRoutingsById(startRouting.getId());
                for (JoinDocumentBomRouting routing : routings) {
                    JoinDocumentBomRoutingDTO joinDocumentBomRoutingDTO = new JoinDocumentBomRoutingDTO();
                    BeanUtil.copyProperties(routing, joinDocumentBomRoutingDTO);
                    joinDocumentBomRoutingDTO.setIsGenerateSn(routingOperationDTO.getIsGenerateSn());
                    totalRoutings.add(joinDocumentBomRoutingDTO);
                }
            }
            // 去重
            List<JoinDocumentBomRoutingDTO> collect = totalRoutings.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(JoinDocumentBomRouting::getId))), ArrayList::new));
            // 排序
            List<JoinDocumentBomRoutingDTO> results = collect.stream().sorted(Comparator.comparing(JoinDocumentBomRouting::getId).reversed()).collect(Collectors.toList());
 
            // 生成 SN 号码
            generateSN(customerOrderNo, masterProductionSchedule.getId(), manufacturingOrderDTO, map, productSns, results, routingOperations, isGenerateSn);
        }
    }
 
    private void generateSN(String customerOrderNo, Long mpsId, ManufacturingOrderDTO manufacturingOrderDTO,
                            Map<Long, ManufacturingOrderDTO> map, String productSns, List<JoinDocumentBomRoutingDTO> routingList,
                            List<RoutingOperationDTO> startRoutingOperations, Boolean isGenerateSn) {
        int routingNumber = 0;
        for (int i = 0; i < routingList.size(); i++) {
            // 查询工艺路线
            List<RoutingOperation> routingOperations = routingOperationMapper.selectList(
                    Wrappers.<RoutingOperation>lambdaQuery()
                            .eq(RoutingOperation::getRoutingId, routingList.get(i).getRoutingId())
                            .orderByAsc(RoutingOperation::getOperationOrder));
 
            // 找出所有的段长任务单
            List<CustomerOrderProduceTask> customerOrderProduceTasks = this.customerOrderProduceTaskMapper.selectList(Wrappers.<CustomerOrderProduceTask>lambdaQuery()
                    .eq(CustomerOrderProduceTask::getMpsId, mpsId));
 
            // 查询主计划的理论产量数据
            // MasterProductionScheduleTheoryQuantity masterProductionScheduleTheoryQuantity = masterProductionScheduleTheoryQuantityMapper.selectOne(
            //         Wrappers.<MasterProductionScheduleTheoryQuantity>lambdaQuery()
            //                 .eq(MasterProductionScheduleTheoryQuantity::getMid, manufacturingOrderDTO.getMpsId())
            //                 .eq(MasterProductionScheduleTheoryQuantity::getJoinDocBomRoutingId, routingList.get(i).getId())
            // );
            // 根据理论产量的id 查询当前车间订单
            ManufacturingOrderDTO current = map.get(routingList.get(i).getPartId());
 
            int operationNumber = 0;
 
            for (int j = 0; j < routingOperations.size(); j++) {
                boolean flag = false;
                boolean operationProduceQtyFlag = false;
                BigDecimal operationProduceQty = null;
                for (RoutingOperationDTO startRoutingOperation : startRoutingOperations) {
                    if (routingList.get(i).getRoutingId().equals(startRoutingOperation.getRoutingId())) {
                        if (routingOperations.get(j).getOperationOrder() < startRoutingOperation.getOperationOrder()) {
                            flag = true;
                            break;
                        } else if (routingOperations.get(j).getOperationOrder() == startRoutingOperation.getOperationOrder()) {
                            operationProduceQtyFlag = true;
                            if (startRoutingOperation.getOperationProduceQty() != null) {
                                if (startRoutingOperation.getOperationProduceQty() != null) {
                                    operationProduceQty = startRoutingOperation.getOperationProduceQty();
                                }
                            }
                        }
                        break;
                    }
                }
                if (flag) {
                    continue;
                }
 
                if (j == routingOperations.size() - 1 && routingList.get(i).getParentId() == null) {
                    // 如果是最后一条工艺路线,最后一个工序
                    for (CustomerOrderProduceTask customerOrderProduceTask : customerOrderProduceTasks) {
                        ManufacturingOrderSnGenerate generate = new ManufacturingOrderSnGenerate();
                        generate.setOperationId(routingOperations.get(j).getOperationId());
                        generate.setParentId(null);
                        generate.setOriginalSn(customerOrderProduceTask.getSnNo());
                        generate.setSn(customerOrderProduceTask.getSnNo());
                        generate.setMergeSnNo(customerOrderProduceTask.getMergeSnNo());
                        generate.setProductSn(customerOrderProduceTask.getSnNo());
                        generate.setMoId(manufacturingOrderDTO.getId());
                        generate.setCurrentMoId(manufacturingOrderDTO.getId());
                        generate.setCustomerOrderNo(customerOrderNo);
                        generate.setJoinDocBomRoutingId(routingList.get(i).getId());
                        generate.setMpsId(mpsId);
                        generate.setPartId(manufacturingOrderDTO.getPartId());
                        // 根据合并缆号找出任务单用来生成备注
                        List<CustomerOrderProduceTask> remarkTasks = customerOrderProduceTaskMapper.selectList(Wrappers.<CustomerOrderProduceTask>lambdaQuery()
                                .eq(CustomerOrderProduceTask::getMergeSnNo, customerOrderProduceTask.getMergeSnNo()));
                        generate.setRemark(StrUtil.join("+", remarkTasks.stream().map(CustomerOrderProduceTask::getSnNo).distinct().collect(Collectors.toList())) + "+一起生产");
                        manufacturingOrderSnGenerateMapper.insert(generate);
                    }
                } else {
                    // 根据合并缆号分组
                    Map<String, List<CustomerOrderProduceTask>> taskByMergeNoMap = customerOrderProduceTasks.stream().collect(Collectors.groupingBy(CustomerOrderProduceTask::getMergeSnNo));
                    for (Map.Entry<String, List<CustomerOrderProduceTask>> taskByMergeNoEntry : taskByMergeNoMap.entrySet()) {
                        ManufacturingOrderSnGenerate generate = new ManufacturingOrderSnGenerate();
                        generate.setOperationId(routingOperations.get(j).getOperationId());
                        generate.setParentId(null);
                        if (routingList.get(i).getIsGenerateSn()) {
                            generate.setSn(taskByMergeNoEntry.getKey() + alphabetStr(routingNumber) + alphabetStr(operationNumber));
                            generate.setOriginalSn(generate.getSn());
                            generate.setIsGenerateSn(true);
                        }
                        generate.setMergeSnNo(taskByMergeNoEntry.getKey());
                        generate.setProductSn(null);
                        generate.setMoId(manufacturingOrderDTO.getId());
                        generate.setCurrentMoId(current.getId());
                        generate.setPartId(routingOperations.get(j).getPartId());
                        generate.setCustomerOrderNo(customerOrderNo);
                        generate.setJoinDocBomRoutingId(routingList.get(i).getId());
                        generate.setMpsId(mpsId);
                        if (operationProduceQtyFlag && operationProduceQty != null) {
                            generate.setOperationProduceQty(operationProduceQty);
                        }
                        generate.setRemark(StrUtil.join("+", taskByMergeNoEntry.getValue().stream().map(CustomerOrderProduceTask::getSnNo).distinct().collect(Collectors.toList())) + "+一起生产");
                        manufacturingOrderSnGenerateMapper.insert(generate);
                    }
                }
                operationNumber++;
            }
            routingNumber++;
        }
    }
 
    static String alphabetStr(int i) {
        return i < 0 ? "" : alphabetStr((i / 26) - 1) + (char) (65 + i % 26);
    }
 
    /**
     * 递归插入
     *
     * @param customerOrderNo         客户订单编号
     * @param joinDocBomRoutingList   库存件list
     * @param parentJoinDocBomRouting 父节点
     * @param parent                  父SN号
     * @param manufacturingOrderDTO   车间订单
     * @param productSN               SN集合
     * @param manufactureAttr         制造属性
     * @param map                     理论产量id , ManufacturingOrderDTO 的 map
     */
    public void recursionGenerateDocumentSN(String customerOrderNo, List<JoinDocumentBomRoutingDTO> joinDocBomRoutingList, JoinDocumentBomRoutingDTO parentJoinDocBomRouting,
                                            ManufacturingOrderSnGenerate parent, ManufacturingOrderDTO manufacturingOrderDTO, String productSN, String manufactureAttr,
                                            Map<Long, ManufacturingOrderDTO> map) {
        DateTimeFormatter snFormat = DateTimeFormatter.ofPattern("yyMMdd");
        String snDate = snFormat.format(LocalDateTime.now());
        // 查询工艺路线
        List<RoutingOperation> routingOperations = routingOperationMapper.selectList(
                Wrappers.<RoutingOperation>lambdaQuery()
                        .eq(RoutingOperation::getRoutingId, parentJoinDocBomRouting.getRoutingId())
                        .orderByDesc(RoutingOperation::getOperationOrder));
        // 查询主计划的理论产量数据
        MasterProductionScheduleTheoryQuantity masterProductionScheduleTheoryQuantity = masterProductionScheduleTheoryQuantityMapper.selectOne(
                Wrappers.<MasterProductionScheduleTheoryQuantity>lambdaQuery()
                        .eq(MasterProductionScheduleTheoryQuantity::getMid, manufacturingOrderDTO.getMpsId())
                        .eq(MasterProductionScheduleTheoryQuantity::getJoinDocBomRoutingId, parentJoinDocBomRouting.getId())
        );
        //根据理论产量的id 查询当前车间订单
        ManufacturingOrderDTO current = map.get(masterProductionScheduleTheoryQuantity.getId());
        ManufacturingOrderSnGenerate previous = new ManufacturingOrderSnGenerate();
        for (int i = 0; i < routingOperations.size(); i++) {
/*            //查询最新的SN号码
            List<String> snNos = operationTaskProduceMapper.getSnNumbers(snDate + "%");
            //号码的处理
            int num = 0;
            if (CollectionUtil.isNotEmpty(snNos)) {
                String soNo = snNos.get(0);
                num = Integer.parseInt(soNo.substring(6, soNo.length() - 1));
            }*/
            String manufatureAttr = StringUtils.isBlank(manufactureAttr) ? "N" : manufactureAttr;
            int num = Integer.parseInt(sequence.nextNo().substring(8));
            String snno = snDate + String.format("%06d", num) + manufatureAttr;
            ManufacturingOrderSnGenerate generate = new ManufacturingOrderSnGenerate();
            //只有当工艺路线工序id 和 车间订单产出id 相同的时候才将当前车间订单插入
            if (null != current && routingOperations.get(i).getPartId().equals(current.getPartId())) {
                generate.setCurrentMoId(current.getId());
            }
            generate.setOperationId(routingOperations.get(i).getOperationId());
            generate.setParentId(i == 0 ? parent.getId() : previous.getId());
            generate.setMoId(manufacturingOrderDTO.getId());
            generate.setCustomerOrderNo(customerOrderNo);
            if (i == 0 && parentJoinDocBomRouting.getParentId() == null) {
                generate.setSn(null);
            } else {
                generate.setSn(snno);
            }
            generate.setProductSn(productSN);
            manufacturingOrderSnGenerateMapper.insert(generate);
            previous = generate;
            // 如果最后一个则,找出子工艺继续递归生成
            if (i == routingOperations.size() - 1) {
                List<JoinDocumentBomRoutingDTO> children = joinDocBomRoutingList.stream().filter(o -> o.getParentId() != null && o.getParentId()
                        .equals(parentJoinDocBomRouting.getId()))
                        .collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(children)) {
                    for (JoinDocumentBomRoutingDTO child : children) {
                        recursionGenerateDocumentSN(customerOrderNo, joinDocBomRoutingList, child, generate, manufacturingOrderDTO, productSN, manufactureAttr, map);
                    }
                }
            }
        }
    }
 
 
    /**
     * 根据工艺路线插入检测标准,参数集和车间订单对应工艺路线
     *
     * @param manufacturingOrderDTO
     */
    private void addMoParams(ManufacturingOrderDTO manufacturingOrderDTO) {
        if (null == manufacturingOrderDTO.getTechnologyRoutingId() || null == manufacturingOrderDTO.getId()) {
            return;
        }
        // 查询出此工艺路线下的所有工序
        RoutingDTO routingDTO = routingService.getRoutingById(manufacturingOrderDTO.getTechnologyRoutingId());
        // 用于返回车间订单工序
        List<MoRoutingOperationDTO> moRoutingOperationDTOList = new ArrayList<>();
        // 新增工艺路线
        MoRouting moRouting = moRoutingService.addMoRouting(routingDTO, manufacturingOrderDTO.getId());
        // 添加工序对应其他数据
        if (routingDTO.getOperations() != null) {
            for (RoutingOperationDTO routingOperationDTO : routingDTO.getOperations()) {
                // 车间订单对应工艺路线
                MoRoutingOperationDTO moRoutingOperationDTO = moRoutingService.fillMoRoutingOperation(routingOperationDTO, moRouting.getId(), manufacturingOrderDTO.getId());
                // 将数据返回
                moRoutingOperationDTOList.add(moRoutingOperationDTO);
                // 新增模板参数
                fillParamByOperation(manufacturingOrderDTO.getId(), moRoutingOperationDTO.getId(), routingOperationDTO);
                // 新增检测标准
                // fillStandardByOperation(manufacturingOrderDTO.getId(), moRoutingOperationDTO.getId(), routingOperationDTO);
                // 从工艺文件的检测标准表中引入数据
                if (manufacturingOrderDTO.getMpsId() != null) {
                    manufacturingOrderUtils.fillStandardByOperationDoc(manufacturingOrderDTO.getId(), moRoutingOperationDTO.getId(), routingOperationDTO, manufacturingOrderDTO.getPartId());
                }
            }
        }
        manufacturingOrderDTO.setMoRoutingOperationDTOList(moRoutingOperationDTOList);
    }
 
    /**
     * 修改车间订单BOM
     *
     * @param moStructureComponentDTO
     * @return
     */
    @Override
    public boolean updateMoBom(MoStructureComponentDTO moStructureComponentDTO) {
        MoStructureComponent moStructureComponent = moStructureComponentMapper.selectById(moStructureComponentDTO.getId());
        updateIfsMat(moStructureComponent.getPlanManufacturingOrderId(), false);
        return SqlHelper.retBool(moStructureComponentMapper.updateById(moStructureComponentDTO));
    }
 
    /**
     * 根据车间订单BOM的id删除节点
     *
     * @param id
     * @return
     */
    @Override
    public boolean delMoBom(Long id) throws RuntimeException {
        MoStructureComponent root = moStructureComponentMapper.selectById(id);
        ManufacturingOrder manufacturingOrder = baseMapper.selectById(root.getPlanManufacturingOrderId());
        List<MoStructureComponent> moStructureComponents = new ArrayList<>();
        getMoBomTreeByParentId(root, moStructureComponents);
        delFromIfs(moStructureComponents, manufacturingOrder);
        return true;
    }
 
    /**
     * 删除时需要同步ids删除
     *
     * @param moStructureComponents
     * @param manufacturingOrder
     */
    private void delFromIfs(List<MoStructureComponent> moStructureComponents, ManufacturingOrder manufacturingOrder) {
        JSONArray jsonArray = new JSONArray();
        List<Long> delIds = new ArrayList<>();
        for (MoStructureComponent moStructureComponent : moStructureComponents) {
            delIds.add(moStructureComponent.getId());
            if (StringUtils.isNotBlank(moStructureComponent.getIfsLineItemNo())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("ORDER_NO", manufacturingOrder.getIfsOrderNo());// 订单编号
                jsonObject.put("RELEASE_NO", manufacturingOrder.getIfsReleaseNo());// 下达号
                jsonObject.put("SEQUENCE_NO", manufacturingOrder.getIfsSequenceNo());// 序列号
                jsonObject.put("LINE_ITEM_NO", Integer.valueOf(moStructureComponent.getIfsLineItemNo()));// 序列号
                jsonArray.add(jsonObject);
            }
        }
        if (CollectionUtil.isNotEmpty(jsonArray)) {
            JSONObject param = headMake("车间订单物料删除");
            param.put("BATCH_INFO", jsonArray);
            R result = ifsFeignClient.removeShopMaterialAllocStd(param, true);
            if (result.getCode() == 0) {
                moStructureComponentMapper.deleteBatchIds(delIds);
            } else {
                throw new RuntimeException("IFS错误—— 删除错误:" + result.getMsg());
            }
        } else {
            moStructureComponentMapper.deleteBatchIds(delIds);
        }
    }
 
    /**
     * 新增车间订单bom节点
     *
     * @param moStructureComponentDTO bom节点
     * @return
     */
    @Override
    public MoStructureComponentDTO addMoBomCompont(MoStructureComponentDTO moStructureComponentDTO) throws RuntimeException {
        ManufacturingOrder manufacturingOrder = baseMapper.selectById(moStructureComponentDTO.getPlanManufacturingOrderId());
        manufacturingOrder.setIfsMatSync(false);
        baseMapper.updateById(manufacturingOrder);
        moStructureComponentMapper.insert(moStructureComponentDTO);
        return moStructureComponentDTO;
    }
 
    /**
     * 将零件物料是否同步改为false
     *
     * @param id
     * @param b
     */
    private void updateIfsMat(Long id, boolean b) {
        ManufacturingOrder manufacturingOrder = baseMapper.selectById(id);
        manufacturingOrder.setIfsMatSync(b);
        baseMapper.updateById(manufacturingOrder);
    }
 
 
    /**
     * 父id查询车间订单BOM树
     *
     * @param father 父节点
     * @param list   总结点List
     */
    private void getMoBomTreeByParentId(MoStructureComponent father, List<MoStructureComponent> list) {
        list.add(father);
        List<MoStructureComponent> childs = moStructureComponentMapper.selectList(Wrappers.<MoStructureComponent>lambdaQuery().eq(MoStructureComponent::getParent, father.getId()));
        for (MoStructureComponent moStructureComponent : childs) {
            getMoBomTreeByParentId(moStructureComponent, list);
        }
    }
 
    /**
     * 查询IFS车间订单申请
     *
     * @param manufacturingOrderDTO
     * @return
     */
    @Override
    public R queryShopOrderReqStd(ManufacturingOrderDTO manufacturingOrderDTO) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotBlank(manufacturingOrderDTO.getPartName())) {// 零件描述
            jsonObject.put("PART_DESC", manufacturingOrderDTO.getPartName());
        }
        if (StringUtils.isNotBlank(manufacturingOrderDTO.getPartNo())) {// 零件编号
            jsonObject.put("PART_NO", manufacturingOrderDTO.getPartNo());
        }
        if (StringUtils.isNotBlank(manufacturingOrderDTO.getWorkshopTypeCode())) {    // 车间订单类型
            jsonObject.put("SO_REQ_TYPE_DB", manufacturingOrderDTO.getWorkshopTypeCode());
        }
        if (StringUtils.isNotBlank(manufacturingOrderDTO.getState())) {// 状态
            jsonObject.put("STATE_DB", manufacturingOrderDTO.getState());
        }
        if (StringUtils.isNotBlank(manufacturingOrderDTO.getCreateUser())) {    // 计划人
            jsonObject.put("PLANNER_BUYER", manufacturingOrderDTO.getCreateUser());
        }
        R result = ifsFeignClient.queryShopOrderReqStd(jsonObject, true);
        if (result.getCode() == 0) {
            JSONObject data = (JSONObject) JSON.toJSON(result.getData());
            return R.ok(data.getJSONArray("LIST_INFO"), "OK");
        } else {
            return R.failed("IFS错误——" + result.getMsg());
        }
    }
 
    private JSONObject headMake(String business) {
        return new JSONObject()
                .fluentPut("RECORD_ID", UUID.randomUUID().toString())
                .fluentPut("SYSCODE", "LMES")
                .fluentPut("SYSMODEL", business);
    }
 
    /**
     * IFS车间订单物料工序创建更新
     *
     * @param ids
     * @return
     */
    @Override
    public R importShopOrderStd(List<Long> ids) {
        String moIfsNeedSync = remoteParamService.getByKey(Constant.MO_IFS_NEED_SYNC, SecurityConstants.FROM_IN).getData();
        if ("false".equals(moIfsNeedSync)) {
            return R.ok();
        }
        try {
            JSONArray jsonArrayAdd = new JSONArray();
            JSONArray jsonArrayUpdate = new JSONArray();
            List<ManufacturingOrder> updateMo = new ArrayList<>();
            for (Long id : ids) {
                ManufacturingOrder manufacturingOrder = baseMapper.selectById(id);
                Part part = partMapper.selectById(manufacturingOrder.getPartId());
                MoRoutingDTO moRoutingDTO = moRoutingMapper.getMoRoutinDtoByMoid(id);// 查询车间订单对应工艺路线
                MasterProductionSchedule masterProductionSchedule = masterProductionScheduleMapper.selectOne(Wrappers.<MasterProductionSchedule>lambdaQuery()
                        .eq(MasterProductionSchedule::getId, manufacturingOrder.getMpsId()));
                CustomerOrder customerOrder = null;
                if (masterProductionSchedule != null) {
                    customerOrder = customerOrderMapper.getCustomerOrderByScheduleId(masterProductionSchedule.getId());
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("ORDER_ID", manufacturingOrder.getId().toString());// 订单编号
                jsonObject.put("ORDER_NO", manufacturingOrder.getIfsOrderNo());// 订单编号
                jsonObject.put("RELEASE_NO", manufacturingOrder.getIfsReleaseNo());// 下达号
                jsonObject.put("SEQUENCE_NO", manufacturingOrder.getIfsSequenceNo());// 序列号
                jsonObject.put("CLOSE_CODE_DB", "N");// 是否自动关闭传 手动关闭
                jsonObject.put("PART_NO", part.getPartNo());// 零件号
                jsonObject.put("NEED_DATE", manufacturingOrder.getRequiredDate());// 需要日期
                jsonObject.put("QTY_ON_ORDER", manufacturingOrder.getQtyRequired());    // 需要数量
                jsonObject.put("ORDER_CODE_DB", manufacturingOrder.getWorkshopTypeCode());// 订单类型
                jsonObject.put("ENG_CHG_LEVEL", part.getEngChgLevel());    // 结构版本号
                if (customerOrder == null) {
                    manufacturingOrder.setRemark(manufacturingOrder.getMpsId() + "");
                } else {
                    manufacturingOrder.setRemark(customerOrder.getCustomerOrderNo());
                }
                jsonObject.put("NOTE_TEXT", manufacturingOrder.getRemark());    // 备注
                jsonObject.put("CLOSE_CODE_DB", "N");// 是否自动关闭车间订单
                jsonObject.put("SCHED_DIRECTION_DB", null);// 排产方向
                jsonObject.put("STRUCTURE_ALT", null);// 结构替代
                jsonObject.put("ROUTING_VERSION", moRoutingDTO.getVersion());// 工艺版本
                jsonObject.put("ROUTING_ALT", moRoutingDTO.getAlternativeNo());// 工艺替代
                if (StringUtils.isBlank(manufacturingOrder.getIfsOrderNo())) {
                    jsonObject.put("OPERATION_INFO", addOptionPara(moRoutingDTO));
                    jsonObject.put("MATERIAL_INFO", addMatPara(manufacturingOrder));
                    jsonArrayAdd.add(jsonObject);
                } else {
                    manufacturingOrder.setIfsSync(true);
                    updateMo.add(manufacturingOrder);
                    jsonArrayUpdate.add(jsonObject);
                }
            }
            if (jsonArrayAdd.size() > 0) {
                JSONObject param = headMake("车间订单物料工序创建更新");
                param.put("BATCH_INFO", jsonArrayAdd);
                R result = ifsFeignClient.importSoSmaSoperStd(param, true);
                if (result.getCode() == 0) {
                    JSONObject data = (JSONObject) JSON.toJSON(result.getData());
                    // 添加这个判断是为了  应付  不对接那种情况
                    if (null != data.get("LIST_INFO")) {
                        moIfsResult(data.getJSONArray("LIST_INFO"));
                    }
                } else {
                    throw new RuntimeException("IFS错误——" + result.getMsg());
                }
            } else if (jsonArrayUpdate.size() > 0) {
                JSONObject param = headMake("车间订单更新");
                param.put("BATCH_INFO", jsonArrayUpdate);
                R result = ifsFeignClient.importShopOrderStd(param, true);
                if (result.getCode() == 0) {
                    saveOrUpdateBatch(updateMo);
                } else {
                    throw new RuntimeException("IFS错误——" + result.getMsg());
                }
            }
        } catch (Exception e) {
            return R.failed(e.getMessage());
        }
        return R.ok();
    }
 
 
    /**
     * 处理对接IFS车间订单更新新增接口后的回写处理
     *
     * @param jsonArray
     */
    @Override
    public void moIfsResult(JSONArray jsonArray) {
        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String moId = jsonObject.getString("ORDER_ID");
                ManufacturingOrder manufacturingOrder = baseMapper.selectById(new Long(moId));
                manufacturingOrder.setIfsOrderNo(jsonObject.getString("ORDER_NO"));
                manufacturingOrder.setIfsReleaseNo(jsonObject.getString("RELEASE_NO"));
                manufacturingOrder.setIfsSequenceNo(jsonObject.getString("SEQUENCE_NO"));
                manufacturingOrder.setIfsSync(true);
                manufacturingOrder.setIfsMatSync(true);
                manufacturingOrder.setIfsRoutingOperationSync(true);
                baseMapper.updateById(manufacturingOrder);
                JSONArray matArray = jsonObject.getJSONArray("MATERIAL_INFO");
                for (int j = 0; j < matArray.size(); j++) {
                    JSONObject matObj = matArray.getJSONObject(j);
                    String matId = matObj.getString("MATERIAL_ID");
                    MoStructureComponent moStructureComponent = moStructureComponentMapper.selectById(new Long(matId));
                    // 设置行项号
                    moStructureComponent.setIfsLineItemNo(matObj.getString("LINE_ITEM_NO"));
                    moStructureComponentMapper.updateById(moStructureComponent);
                }
            }
        }
    }
 
    /**
     * 拼接车间订单工序参数
     *
     * @param moRoutingDTO
     * @return
     */
    private JSONArray addOptionPara(MoRoutingDTO moRoutingDTO) {
        JSONArray jsonArray = new JSONArray();
        List<MoRoutingOperationDTO> moRoutingOperationDTOS = moRoutingDTO.getMoRoutingOperationDTOList();
        for (MoRoutingOperationDTO moRoutingOperationDTO : moRoutingOperationDTOS) {
            JSONObject optionObj = new JSONObject();
            optionObj.put("OPERATION_NO", moRoutingOperationDTO.getOperationOrder() != null
                    ? new BigDecimal(moRoutingOperationDTO.getOperationOrder()).multiply(BigDecimal.TEN)
                    : BigDecimal.TEN);// 工序号 排序
            optionObj.put("OPERATION_DESC", moRoutingOperationDTO.getOperationName());// 工序名称
            optionObj.put("OP_SEQUENCE_NO", null);    // 序列号
            optionObj.put("WORK_CENTER_NO", moRoutingOperationDTO.getWorkCenter());// 工作中心编号
            optionObj.put("MACH_RUN_FACTOR", moRoutingOperationDTO.getMachRunFactor());    // 机器运转因素
            optionObj.put("MACH_SETUP_TIME", moRoutingOperationDTO.getMachSetupTime());// 机器设置时间
            optionObj.put("LABOR_CLASS_NO", moRoutingOperationDTO.getLaborClassNo());    // 人工类别
            optionObj.put("LABOR_RUN_FACTOR", moRoutingOperationDTO.getLaborRunFactor());// 劳力运转因素
            optionObj.put("LABOR_SETUP_TIME", moRoutingOperationDTO.getLaborSetupTime());    // 劳力设置时间
            optionObj.put("CREW_SIZE", moRoutingOperationDTO.getCrewSize());// 班组人员
            optionObj.put("OUTSIDE_OP_ITEM", moRoutingOperationDTO.getOutsideOpItem()); // 外协
            optionObj.put("SETUP_LABOR_CLASS_NO", null);// 设置劳动力类别
            optionObj.put("SETUP_CREW_SIZE", null);    // 安装班组规模
            optionObj.put("RUN_TIME_CODE_DB", moRoutingOperationDTO.getRunTimeCodeDb());// 因素单位
            jsonArray.add(optionObj);
        }
        return jsonArray;
    }
 
    /**
     * 拼接车间订单材料参数
     *
     * @param manufacturingOrder
     * @return
     */
    private JSONArray addMatPara(ManufacturingOrder manufacturingOrder) {
        JSONArray jsonArray = new JSONArray();
        List<MoStructureComponentDTO> structureComponentDTOS = moStructureComponentMapper.selectMoComponents(manufacturingOrder.getId());
        for (MoStructureComponentDTO moStructureComponentDTO : structureComponentDTOS) {
            if (moStructureComponentDTO.getMaterialType().equals("1") || moStructureComponentDTO.getMaterialType().equals("3")) {
                if (!"A".equals(moStructureComponentDTO.getPlanningMethod())) {
                    continue;
                }
                // 本体不传
                if (moStructureComponentDTO.getParent() == null) {
                    continue;
                }
                // 根据当前产出零件和对应的父组件查找
                Integer count =
                        moStructureComponentMapper.selectCount(Wrappers.<MoStructureComponent>lambdaQuery()
                                .eq(MoStructureComponent::getId, moStructureComponentDTO.getParent())
                                .eq(MoStructureComponent::getPartId, moStructureComponentDTO.getPartId()));
                List<MoRoutingOperation> moRoutingOperationList =
                        moRoutingOperationMapper.selectList(Wrappers.<MoRoutingOperation>lambdaQuery()
                                .eq(MoRoutingOperation::getMoId, manufacturingOrder.getId())
                                .eq(MoRoutingOperation::getOperationId, moStructureComponentDTO.getOperationId()));
                if (CollectionUtil.isEmpty(moRoutingOperationList)) {
                    throw new RuntimeException(moStructureComponentDTO.getPartNo() + "的消耗工序在工艺路线中未找到对应工序");
                }
                for (MoRoutingOperation moRoutingOperation : moRoutingOperationList) {
                    // 当前产出零件和父产出零件一样 并且对应的消耗工序不是车间订单的最后一道工序 continue
                    if (count > 0 && BooleanUtil.isFalse(moRoutingOperation.getIsLast())) {
                        continue;
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("MATERIAL_ID", moStructureComponentDTO.getId().toString());// 数据id
                    jsonObject.put("PART_NO", moStructureComponentDTO.getPartNo());// 零件号
                    jsonObject.put("ISSUE_TO_LOC", null);// 下发到库位
                    jsonObject.put("OPERATION_NO", moRoutingOperation.getOperationOrder() != null
                            ? new BigDecimal(moRoutingOperation.getOperationOrder()).multiply(BigDecimal.TEN)
                            : BigDecimal.TEN);// 工序号
                    jsonObject.put("QTY_REQUIRED", moStructureComponentDTO.getQpa().multiply(manufacturingOrder.getQtyRequired()));// 有力需求数量()
                    jsonObject.put("QTY_PER_ASSEMBLY", moStructureComponentDTO.getQpa());    // 每个装配数量
                    jsonObject.put("DATE_REQUIRED", manufacturingOrder.getRequiredDate());// 需求日期
                    jsonObject.put("LEADTIME_OFFSET", null);    // 提前期低消
                    jsonObject.put("SUPPLY_CODE_DB", null);    // 供应类型
                    jsonObject.put("PART_OWNERSHIP_DB", "COMPANY OWNED");// 物料零件号所有标识
                    jsonObject.put("OWNING_CUSTOMER_NO", null);// 零件物料号所有者
                    jsonObject.put("ISSUE_TYPE_DB", null);    // 预留下发方法
                    jsonObject.put("NOTE_TEXT", null);// 物料行备注
                    jsonArray.add(jsonObject);
                }
            }
        }
        return jsonArray;
    }
 
    /**
     * ifs车间订单物料更新
     *
     * @param ids
     * @return
     */
    @Override
    public R modifyShopMaterialAllocStd(List<Long> ids) {
        try {
            if (ids.size() != 1) {
                return R.failed("请选择一条数据");
            }
            Long id = ids.get(0);
            // 存放需要更新的list
            JSONArray jsonArrayUpdate = new JSONArray();
            // 存放需要新增的list
            JSONArray jsonArrayAdd = new JSONArray();
            ManufacturingOrder manufacturingOrder = baseMapper.selectById(id);
            List<MoStructureComponentDTO> structureComponentDTOS = moStructureComponentMapper.selectMoComponents(id);
            for (MoStructureComponentDTO moStructureComponentDTO : structureComponentDTOS) {
                // 已制造和已采购 ,计划方案为A 的材料才对接
                if (moStructureComponentDTO.getMaterialType().equals("1") || moStructureComponentDTO.getMaterialType().equals("3")) {
                    if (!"A".equals(moStructureComponentDTO.getPlanningMethod())) {
                        continue;
                    }
                    // 当前材料不传
                    if (moStructureComponentDTO.getParent() == null) {
                        continue;
                    }
                    // 根据当前产出零件和对应的父组件查找
                    Integer count =
                            moStructureComponentMapper.selectCount(Wrappers.<MoStructureComponent>lambdaQuery()
                                    .eq(MoStructureComponent::getId, moStructureComponentDTO.getParent())
                                    .eq(MoStructureComponent::getPartId, moStructureComponentDTO.getPartId()));
 
                    List<MoRoutingOperation> moRoutingOperationList =
                            moRoutingOperationMapper.selectList(Wrappers.<MoRoutingOperation>lambdaQuery()
                                    .eq(MoRoutingOperation::getMoId, manufacturingOrder.getId())
                                    .eq(MoRoutingOperation::getOperationId, moStructureComponentDTO.getOperationId()));
                    if (CollectionUtils.isEmpty(moRoutingOperationList)) {
                        throw new RuntimeException(moStructureComponentDTO.getPartNo() + "的消耗工序在工艺路线中未找到对应工序");
                    }
                    // 当前产出零件和父产出零件一样 并且对应的消耗工序不是车间订单的最后一道工序 continue
 
                    for (MoRoutingOperation moRoutingOperation : moRoutingOperationList) {
                        if (count > 0 && BooleanUtil.isFalse(moRoutingOperation.getIsLast())) {
                            continue;
                        }
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("ORDER_NO", manufacturingOrder.getIfsOrderNo());
                        jsonObject.put("RELEASE_NO", manufacturingOrder.getIfsReleaseNo());
                        jsonObject.put("SEQUENCE_NO", manufacturingOrder.getIfsSequenceNo());
                        jsonObject.put("MATERIAL_ID", moStructureComponentDTO.getId().toString());// 数据id
                        if (StringUtils.isNotBlank(moStructureComponentDTO.getIfsLineItemNo())) {
                            jsonObject.put("LINE_ITEM_NO", Integer.valueOf(moStructureComponentDTO.getIfsLineItemNo()));// ifs行项号
                        }
                        jsonObject.put("PART_NO", moStructureComponentDTO.getPartNo());// 零件号
                        jsonObject.put("ISSUE_TO_LOC", null);// 下发到库位
                        // jsonObject.put("OPERATION_NO", moRoutingOperation.getOperationOrder() != null
                        //        ? new BigDecimal(moRoutingOperation.getOperationOrder()).multiply(BigDecimal.TEN)
                        //        : BigDecimal.TEN);//工序号
                        jsonObject.put("QTY_REQUIRED", moStructureComponentDTO.getQpa().multiply(manufacturingOrder.getQtyRequired()));// 有力需求数量()
                        jsonObject.put("QTY_PER_ASSEMBLY", moStructureComponentDTO.getQpa());    // 每个装配数量
                        jsonObject.put("DATE_REQUIRED", manufacturingOrder.getRequiredDate());// 需求日期
                        jsonObject.put("LEADTIME_OFFSET", null);    // 提前期低消
                        jsonObject.put("SUPPLY_CODE_DB", null);    // 供应类型
                        jsonObject.put("PART_OWNERSHIP_DB", "COMPANY OWNED");// 物料零件号所有标识
                        jsonObject.put("OWNING_CUSTOMER_NO", null);// 零件物料号所有者
                        jsonObject.put("ISSUE_TYPE_DB", null);    // 预留下发方法
                        jsonObject.put("NOTE_TEXT", null);// 物料行备注
                        if (StringUtils.isBlank(moStructureComponentDTO.getIfsLineItemNo())) {
                            jsonArrayAdd.add(jsonObject);
                        } else {
                            jsonArrayUpdate.add(jsonObject);
                        }
                    }
 
                }
            }
            ifsUpdateOrAdd(jsonArrayUpdate, jsonArrayAdd, manufacturingOrder);
        } catch (Exception e) {
            return R.failed(e.getMessage());
        }
        return R.ok();
    }
 
 
    private void ifsUpdateOrAdd(JSONArray jsonArrayUpdate, JSONArray jsonArrayAdd, ManufacturingOrder manufacturingOrder) throws Exception {
        if (CollectionUtil.isEmpty(jsonArrayUpdate) && CollectionUtil.isEmpty(jsonArrayAdd)) {
            throw new RuntimeException("缺少物料");
        }
        // 已同步物料进行更新
        if (CollectionUtil.isNotEmpty(jsonArrayUpdate)) {
            JSONObject param = headMake("车间订单物料更新");
            param.put("BATCH_INFO", jsonArrayUpdate);
            R result = ifsFeignClient.modifyShopMaterialAllocStd(param, true);
            if (result.getCode() != 0) {
                throw new RuntimeException("IFS错误——" + result.getMsg());
            }
        }
        // 新增物料进行新增
        if (CollectionUtil.isNotEmpty(jsonArrayAdd)) {
            JSONObject param = headMake("车间订单物料更新");
            param.put("BATCH_INFO", jsonArrayAdd);
            R result = ifsFeignClient.importShopMaterialAllocStd(param, true);
            if (result.getCode() == 0) {
                JSONObject data = (JSONObject) JSON.toJSON(result.getData());
                JSONArray jsonArrayResult = data.getJSONArray("LIST_INFO");
                for (int i = 0; i < jsonArrayResult.size(); i++) {
                    JSONObject matObj = jsonArrayResult.getJSONObject(i);
                    String matId = matObj.getString("MATERIAL_ID");
                    MoStructureComponent moStructureComponent = moStructureComponentMapper.selectById(new Long(matId));
                    // 设置行项号
                    moStructureComponent.setIfsLineItemNo(matObj.getString("LINE_ITEM_NO"));
                    moStructureComponentMapper.updateById(moStructureComponent);
                }
            } else {
                throw new RuntimeException("IFS错误——" + result.getMsg());
            }
        }
        manufacturingOrder.setIfsMatSync(true);
        baseMapper.updateById(manufacturingOrder);
    }
 
    /**
     * IFS车间订单工序更新
     *
     * @param ids
     * @return
     */
    @Override
    public R modifyShopOperationStd(List<Long> ids) {
        try {
            JSONObject param = headMake("车间订单工序更新");
            JSONArray jsonArray = new JSONArray();
            List<ManufacturingOrder> manufacturingOrderArrayList = new ArrayList<>();
            for (Long id : ids) {
                ManufacturingOrder manufacturingOrder = baseMapper.selectById(id);
                manufacturingOrder.setIfsRoutingOperationSync(true);
                manufacturingOrderArrayList.add(manufacturingOrder);
                MoRoutingDTO moRoutingDTO = moRoutingMapper.getMoRoutinDtoByMoid(id);// 查询车间订单对应工艺路线
                List<MoRoutingOperationDTO> moRoutingOperationDTOS = moRoutingDTO.getMoRoutingOperationDTOList();
                for (MoRoutingOperationDTO moRoutingOperationDTO : moRoutingOperationDTOS) {
                    JSONObject optionObj = new JSONObject();
                    optionObj.put("ORDER_NO", manufacturingOrder.getIfsOrderNo());
                    optionObj.put("RELEASE_NO", manufacturingOrder.getIfsReleaseNo());
                    optionObj.put("SEQUENCE_NO", manufacturingOrder.getIfsSequenceNo());
                    optionObj.put("OPERATION_NO", moRoutingOperationDTO.getOperationOrder() != null
                            ? new BigDecimal(moRoutingOperationDTO.getOperationOrder()).multiply(BigDecimal.TEN)
                            : BigDecimal.TEN);// 工序号 排序
                    optionObj.put("OPERATION_DESC", moRoutingOperationDTO.getOperationName());// 工序名称
                    optionObj.put("OP_SEQUENCE_NO", null);    // 工序序列号
                    optionObj.put("WORK_CENTER_NO", moRoutingOperationDTO.getWorkCenter());// 工作中心编号
                    optionObj.put("MACH_RUN_FACTOR", moRoutingOperationDTO.getMachRunFactor());    // 机器运转因素
                    optionObj.put("MACH_SETUP_TIME", moRoutingOperationDTO.getMachSetupTime());// 机器设置时间
                    optionObj.put("LABOR_CLASS_NO", moRoutingOperationDTO.getLaborClassNo());    // 人工类别
                    optionObj.put("LABOR_RUN_FACTOR", moRoutingOperationDTO.getLaborRunFactor());// 劳力运转因素
                    optionObj.put("LABOR_SETUP_TIME", moRoutingOperationDTO.getLaborSetupTime());    // 劳力设置时间
                    optionObj.put("CREW_SIZE", moRoutingOperationDTO.getCrewSize());// 班组人员
                    optionObj.put("SETUP_LABOR_CLASS_NO", null);// 设置劳动力类别
                    optionObj.put("SETUP_CREW_SIZE", null);    // 安装班组规模
                    optionObj.put("RUN_TIME_CODE_DB", moRoutingOperationDTO.getRunTimeCodeDb());// 因素单位
                    optionObj.put("OUTSIDE_OP_ITEM", moRoutingOperationDTO.getOutsideOpItem()); // 外协
                    jsonArray.add(optionObj);
                }
            }
            param.put("BATCH_INFO", jsonArray);
            if (CollectionUtils.isEmpty(jsonArray)) {
                return R.failed("缺少工序数据");
            }
            R result = ifsFeignClient.modifyShopOperationStd(param, true);
            if (result.getCode() == 0) {
                manufacturingOrderArrayList.forEach(manufacturingOrder -> {
                    baseMapper.updateById(manufacturingOrder);
                });
                return R.ok().setMsg("成功");
            } else {
                return R.failed("IFS错误——" + result.getMsg());
            }
        } catch (Exception e) {
            return R.failed("同步异常");
        }
    }
 
    @Override
    public boolean mergeCheck(List<Long> ids) {
        boolean b = true;
        if (ids.size() < 2) {
            throw new RuntimeException("请选择超过一条数据");
        }
        List<String> idsList = baseMapper.getMergeCheckData(ids);
        if (idsList.size() != 1) {
            b = false;
        }
        return b;
    }
 
    /**
     * 后台拼接合并车间订单
     *
     * @param id  合并的车间订单id
     * @param ids 被合并的车间订单的ids
     * @return
     */
    @Override
    public ManufacturingOrder mergeOrder(Long id, List<Long> ids) {
        ManufacturingOrderDTO tomanufacturingOrder = baseMapper.selectDtoById(id);
        tomanufacturingOrder.setMergeIds(ids);
        for (Long merId : ids) {
            ManufacturingOrder frommanufacturingOrder = baseMapper.selectById(merId);
            tomanufacturingOrder.setQtyRequired(tomanufacturingOrder.getQtyRequired().add(frommanufacturingOrder.getQtyRequired()));
        }
        return tomanufacturingOrder;
    }
 
    /**
     * 车间订单合并保存
     *
     * @param manufacturingOrderDTO
     * @return
     */
    @Override
    public boolean mergeUpdate(ManufacturingOrderDTO manufacturingOrderDTO) {
        ManufacturingOrder manufacturingOrder = selectById(manufacturingOrderDTO.getId());
        manufacturingOrder.setQtyRequired(manufacturingOrderDTO.getQtyRequired());
        manufacturingOrder.setRequiredDate(manufacturingOrderDTO.getRequiredDate());
        manufacturingOrder.setIfsSync(false);
        baseMapper.updateById(manufacturingOrder);
        List<ManufacturingOrder> changeIfsStates = new ArrayList<>();
        for (Long id : manufacturingOrderDTO.getMergeIds()) {
            ManufacturingOrderConcat manufacturingOrderConcat = new ManufacturingOrderConcat();
            manufacturingOrderConcat.setOriginId(id);
            manufacturingOrderConcat.setConcatId(manufacturingOrderDTO.getId());
            manufacturingOrderConcatMapper.insert(manufacturingOrderConcat);
            if (id.equals(manufacturingOrder.getId())) {
                continue;
            }
            ManufacturingOrder manufacturingOrderOrigin = baseMapper.selectById(id);
            manufacturingOrderOrigin.setState(ManufacturingOrderStateStringValues.CANCELED);
            baseMapper.updateById(manufacturingOrderOrigin);
            changeIfsStates.add(manufacturingOrderOrigin);
        }
        // ifs取消车间订单
        changeStateBatch(changeIfsStates, "CANCEL");
        return true;
    }
 
 
    /**
     * 车间订单预处理
     *
     * @param manufacturingOrder
     * @param b                  true 预关闭 false 取消预关闭
     * @return
     */
    @Override
    public R changeState(ManufacturingOrder manufacturingOrder, Boolean b) {
        try {
            R result = changeStateBatch(Arrays.asList(manufacturingOrder), b);
            if (result.getCode() == 0) {
                return R.ok();
            } else {
                return R.failed("IFS错误——" + result.getMsg());
            }
        } catch (Exception e) {
            return R.failed("IFS车间订单预处理异常");
        }
    }
 
    @Override
    public void refreshIfsOrderNo() {
        // 获取已下达并且原IFS订单号为空的数据
        List<ManufacturingOrder> manufacturingOrders =
                manufacturingOrderMapper.selectList(Wrappers.<ManufacturingOrder>lambdaQuery().eq(ManufacturingOrder::getState, ManufacturingOrderStateStringValues.ISSUED)
                        .isNull(ManufacturingOrder::getOriIfsOrderNo));
        if (CollectionUtil.isEmpty(manufacturingOrders)) {
            return;
        }
        List<ManufacturingOrder> updateOrders = new ArrayList<>();
        List<List<ManufacturingOrder>> splitList = ListUtils.partition(manufacturingOrders, 100);
        for (List<ManufacturingOrder> orders : splitList) {
            List<String> ifsOrderNoList =
                    orders.stream().map(ManufacturingOrder::getIfsOrderNo).collect(Collectors.toList());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("RELEASE_NO", manufacturingOrders.get(0).getIfsReleaseNo());
            jsonObject.put("SEQUENCE_NO", manufacturingOrders.get(0).getIfsSequenceNo());
            jsonObject.put("ORDER_NO", org.apache.commons.lang3.StringUtils.join(ifsOrderNoList, ";"));
            R result = ifsFeignClient.queryShopOrderSplitStd(jsonObject, true);
            Map<String, ManufacturingOrder> manufacturingOrderMap =
                    orders.stream().collect(Collectors.toMap(ManufacturingOrder::getIfsOrderNo, v -> v,
                            (k1, k2) -> k1));
            if (result.getCode() == 0) {
                JSONObject data = (JSONObject) JSON.toJSON(result.getData());
                JSONArray listInfo = data.getJSONArray("LIST_INFO");
                for (int i = 0; i < listInfo.size(); i++) {
                    JSONObject info = listInfo.getJSONObject(i);
                    String oriIfsOrderNo = info.getString("ORDER_NO");
                    if (!manufacturingOrderMap.containsKey(oriIfsOrderNo)) {
                        continue;
                    }
                    JSONArray newSoList = info.getJSONArray("NEW_SO_LIST");
                    if (CollectionUtil.isNotEmpty(newSoList)) {
                        String ifsOrderNo = newSoList.getJSONObject(0).getString("ORDER_NO");
                        ManufacturingOrder manufacturingOrder = manufacturingOrderMap.get(oriIfsOrderNo);
                        manufacturingOrder.setOriIfsOrderNo(oriIfsOrderNo);
                        manufacturingOrder.setIfsOrderNo(ifsOrderNo);
                        updateOrders.add(manufacturingOrder);
                    }
                }
            }
        }
        if (CollectionUtil.isNotEmpty(updateOrders)) {
            updateBatchById(updateOrders);
        }
    }
 
    @Override
    public void refreshIfsLogOrderNo() {
        List<IfsLog> ifsLogs = ifsLogMapper.selectList(Wrappers.<IfsLog>lambdaQuery().eq(IfsLog::getState,
                Boolean.FALSE).in(IfsLog::getProcedureName, orderInterfaceNames));
        if (CollectionUtil.isEmpty(ifsLogs)) {
            return;
        }
        List<IfsLog> updateIfsLogs = new ArrayList<>();
        List<ManufacturingOrder> manufacturingOrders =
                manufacturingOrderMapper.selectList(Wrappers.<ManufacturingOrder>lambdaQuery().isNotNull(ManufacturingOrder::getOriIfsOrderNo));
        Map<String, ManufacturingOrder> manufacturingOrderMap =
                manufacturingOrders.stream().collect(Collectors.toMap(ManufacturingOrder::getOriIfsOrderNo, v -> v,
                        (k1, k2) -> k1));
        Map<String, List<IfsLog>> ifsLogMap = ifsLogs.stream().collect(Collectors.groupingBy(IfsLog::getProcedureName));
        for (Map.Entry<String, List<IfsLog>> entry : ifsLogMap.entrySet()) {
            String procedureName = entry.getKey();
            if (replaceParamMap.containsKey(procedureName)) {
                updateIfsLogs.addAll(replaceParamMap.get(procedureName).apply(entry.getValue(),
                        manufacturingOrderMap));
            }
        }
        if (CollectionUtil.isNotEmpty(updateIfsLogs)) {
            ifsLogService.updateBatchById(updateIfsLogs);
        }
    }
 
    /**
     * 车间订单预处理
     *
     * @param manufacturingOrderList
     * @param b
     * @return
     */
    private R changeStateBatch(List<ManufacturingOrder> manufacturingOrderList, Boolean b) {
        JSONObject param = new JSONObject()
                .fluentPut("RECORD_ID", UUID.randomUUID().toString())
                .fluentPut("SYSCODE", "LMES")
                .fluentPut("SYSMODEL", "车间订单预处理");
        JSONArray jsonArray = new JSONArray();
        JSONArray jparamArray = new JSONArray();
        for (ManufacturingOrder manufacturingOrder : manufacturingOrderList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("ORDER_NO", manufacturingOrder.getIfsOrderNo());// 订单编号
            jsonObject.put("RELEASE_NO", manufacturingOrder.getIfsReleaseNo());// 下达号
            jsonObject.put("SEQUENCE_NO", manufacturingOrder.getIfsSequenceNo());// 序列号
            if (b) {
                jsonObject.put("PRE_CLOSE", "TRUE");// 预关闭
            } else {
                jsonObject.put("PRE_CLOSE", "FALSE");// 取消预关闭
            }
            jsonArray.add(jsonObject);
            jsonObject.put("moId", manufacturingOrder.getId());
            jparamArray.add(jsonObject);
        }
        param.put("BATCH_INFO", jsonArray);
        param.put("mesParams", new JSONObject()
                .fluentPut("manufacturingOrderArr", jparamArray)
                .fluentPut("SYSMODEL", "车间订单预处理"));
        R result = ifsFeignClient.modifySoPreCloseStd(param, true);
        return result;
    }
 
    /**
     * 车间订单状态修改
     *
     * @param manufacturingOrder
     * @param state
     * @return
     */
    @Override
    public R changeState(ManufacturingOrder manufacturingOrder, String state) {
        try {
            R result = changeStateBatch(Arrays.asList(manufacturingOrder), state);
            if (result.getCode() == 0) {
                return R.ok();
            } else {
                return R.failed("IFS错误——" + result.getMsg());
            }
        } catch (Exception e) {
            return R.failed("IFS车间订单状态修改异常");
        }
    }
 
    /**
     * 车间订单状态修改
     *
     * @param manufacturingOrderList
     * @param state
     * @return
     */
    private R changeStateBatch(List<ManufacturingOrder> manufacturingOrderList, String state) {
        JSONObject param = new JSONObject()
                .fluentPut("RECORD_ID", UUID.randomUUID().toString())
                .fluentPut("SYSCODE", "LMES")
                .fluentPut("SYSMODEL", "车间订单状态修改");
        JSONArray jsonArray = new JSONArray();
        JSONArray jparamArray = new JSONArray();
        for (ManufacturingOrder manufacturingOrder : manufacturingOrderList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("ORDER_NO", manufacturingOrder.getIfsOrderNo());// 订单编号
            jsonObject.put("RELEASE_NO", manufacturingOrder.getIfsReleaseNo());// 下达号
            jsonObject.put("SEQUENCE_NO", manufacturingOrder.getIfsSequenceNo());// 序列号
            if (state.equals("CANCEL")) {
                jsonObject.put("CANCEL_REASON", "01");
                jsonObject.put("ACTION_TYPE", "CANCEL");
            } else if (state.equals("COMPLETED")) {
                jsonObject.put("ACTION_TYPE", "CLOSE");
            } else if (state.equals("ISSUED")) {
                jsonObject.put("ACTION_TYPE", "OPEN");
            } else {
                jsonObject.put("ACTION_TYPE", state);
            }
            jsonArray.add(jsonObject);
            jsonObject.put("moId", manufacturingOrder.getId());
            jparamArray.add(jsonObject);
        }
        param.put("BATCH_INFO", jsonArray);
        param.put("mesParams", new JSONObject()
                .fluentPut("manufacturingOrderArr", jparamArray)
                .fluentPut("SYSMODEL", "车间订单状态修改"));
        R result = ifsFeignClient.modifySoStateStd(param, true);
        return result;
    }
 
 
    @Override
    public void export(HttpServletResponse response, QueryWrapper<ManufacturingOrderDTO> wrapper, List<Long> list) throws IOException {
        List<ManufacturingOrderData> manufacturingOrderDataList;
        if (CollectionUtil.isNotEmpty(list)) {
            manufacturingOrderDataList = baseMapper.getExcelDataByList(wrapper, list);
        } else {
            // 拼接crosstab所需要的验证数据
            OrderParam orderParam = orderParamMapper.getParam();
            manufacturingOrderDataList = baseMapper.getExcelDataByParam(wrapper, orderParam);
        }
        for (ManufacturingOrderData manufacturingOrderData : manufacturingOrderDataList) {
            manufacturingOrderData.setState(getStateValue(manufacturingOrderData.getState()));
            manufacturingOrderData.setWorkshopTypeCode(getWorkshopTypeCodeValue(manufacturingOrderData.getWorkshopTypeCode()));
            manufacturingOrderData.setManufactureAttr(getManufactureAttrValue(manufacturingOrderData.getManufactureAttr()));
            manufacturingOrderData.setBomConfirmStatus(getConfirmStatusValue(manufacturingOrderData.getBomConfirmStatus()));
            manufacturingOrderData.setProcessConfirmStatus(getConfirmStatusValue(manufacturingOrderData.getProcessConfirmStatus()));
            manufacturingOrderData.setStandardConfirmStatus(getConfirmStatusValue(manufacturingOrderData.getStandardConfirmStatus()));
            if (StringUtils.isNotBlank(manufacturingOrderData.getIfsSync())) {
                manufacturingOrderData.setIfsSync(getIsSync(manufacturingOrderData.getIfsSync()));
            }
            if (StringUtils.isNotBlank(manufacturingOrderData.getIfsRoutingOperationSync())) {
                manufacturingOrderData.setIfsRoutingOperationSync(getIsSync(manufacturingOrderData.getIfsRoutingOperationSync()));
            }
            if (StringUtils.isNotBlank(manufacturingOrderData.getIfsMatSync())) {
                manufacturingOrderData.setIfsMatSync(getIsSync(manufacturingOrderData.getIfsMatSync()));
            }
 
        }
 
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("车间订单导出", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        try {
            // 新建ExcelWriter
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
            // 获取sheet0对象
            WriteSheet mainSheet = EasyExcel.writerSheet(0, "导出").head(ManufacturingOrderData.class).build();
            excelWriter.write(manufacturingOrderDataList, mainSheet);
            // 关闭流
            excelWriter.finish();
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }
 
 
    private String getStateValue(String key) {
        switch (key) {
            case ManufacturingOrderStateStringValues.PLANNED:
                return "已计划";
            case ManufacturingOrderStateStringValues.ISSUED:
                return "已下达";
            case ManufacturingOrderStateStringValues.COMPLETED:
                return "已完成";
            case ManufacturingOrderStateStringValues.CANCELED:
                return "已取消";
            default:
                return "";
        }
 
    }
 
    private String getWorkshopTypeCodeValue(String key) {
        switch (key) {
            case "M":
                return "制造";
            case "F":
                return "修理";
            default:
                return "";
        }
    }
 
    private String getManufactureAttrValue(String key) {
        switch (key) {
            case "N":
                return "普通";
            case "S":
                return "样品";
            case "D":
                return "研发";
            default:
                return "";
        }
    }
 
    private String getConfirmStatusValue(String key) {
        switch (key) {
            case "t":
                return "已确认";
            case "f":
                return "未确认";
            default:
                return "";
        }
    }
 
 
    private String getIsSync(String key) {
        switch (key) {
            case "t":
                return "是";
            case "f":
                return "否";
            default:
                return "";
        }
    }
 
    /**
     * 更新车间订单更新接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceImportShopOrderSTDIfsParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单及物料工序新增、更新接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
 
    public List<IfsLog> replaceImportSoSmaSoperSTDParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单物料新增接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceImportShopMaterialAllocSTDParam(List<IfsLog> ifsLogs,
                                                               Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单物料更新接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceModifyShopMaterialAllocSTDParam(List<IfsLog> ifsLogs,
                                                               Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单物料删除接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceRemoveShopMaterialAllocSTDParam(List<IfsLog> ifsLogs,
                                                               Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单工序更新接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceModifyShopOperationSTDParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单预开始预关闭接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceModifySoPreCloseSTDParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        return replaceContainMesKeyParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单发料接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceImportSoMaterialIssueSTDParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单取消发料接口参数
     *
     * @param ifslos
     * @param orderMap
     */
    public List<IfsLog> replaceImportSoMaterialUnissueSTDParam(List<IfsLog> ifslos, Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifslos, orderMap);
    }
 
    /**
     * 更新车间订单工序报工接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceImportSoOperReportSTDParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单接收接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceImportSoReceiveSTDParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单取消接收接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceImportSoUnreceiveSTDParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单工序报废接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceImportSoOperScrapSTDParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单取消工序报废接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceImportSoOperUnscrapSTDParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        return commonReplaceParam(ifsLogs, orderMap);
    }
 
    /**
     * 更新车间订单状态修改接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
    public List<IfsLog> replaceModifySoStateSTDParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        return replaceContainMesKeyParam(ifsLogs, orderMap);
    }
 
    public List<IfsLog> commonReplaceParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        List<IfsLog> updateIfsLogs = new ArrayList<>();
        for (IfsLog ifsLog : ifsLogs) {
            Boolean isUpdate = Boolean.FALSE;
            String inArr = ifsLog.getInAttr();
            JSONObject inArrObj = JSONObject.parseObject(inArr);
            JSONArray batchInfo = inArrObj.getJSONArray("BATCH_INFO");
            if (CollectionUtil.isNotEmpty(batchInfo)) {
                for (int i = 0; i < batchInfo.size(); i++) {
                    JSONObject jsonObject = batchInfo.getJSONObject(i);
                    String oriIfsOrderNo = jsonObject.getString("ORDER_NO");
                    if (org.apache.commons.lang3.StringUtils.isBlank(oriIfsOrderNo) || !orderMap.containsKey(oriIfsOrderNo)) {
                        continue;
                    }
                    ManufacturingOrder manufacturingOrder = orderMap.get(oriIfsOrderNo);
                    jsonObject.put("ORDER_NO", manufacturingOrder.getIfsOrderNo());
                    isUpdate = Boolean.TRUE;
                }
            }
            if (BooleanUtil.isTrue(isUpdate)) {
                log.info("原始接口参数:{}", inArr);
                log.info("原始接口参数转换JSONObject:{}", inArrObj);
                log.info("原始接口参数转换JSONArray:{}", batchInfo);
                log.info("更新接口参数:{}", JSON.toJSONString(inArrObj));
                ifsLog.setInAttr(JSON.toJSONString(inArrObj));
                updateIfsLogs.add(ifsLog);
            }
            if (inArrObj.containsKey("mesParams")) {
                ifsLog.setMesParams(JSON.toJSONString(inArrObj.get("mesParams")));
                inArrObj.remove("mesParams");
            }
        }
        return updateIfsLogs;
    }
 
    /**
     * 更新参数中含有mesParams的接口参数
     *
     * @param ifsLogs
     * @param orderMap
     */
 
    public List<IfsLog> replaceContainMesKeyParam(List<IfsLog> ifsLogs, Map<String, ManufacturingOrder> orderMap) {
        List<IfsLog> updateIfsLogs = commonReplaceParam(ifsLogs, orderMap);
        for (IfsLog ifsLog : ifsLogs) {
            String inArr = ifsLog.getInAttr();
            JSONObject inArrObj = JSONObject.parseObject(inArr);
            JSONObject mesParamObj = inArrObj.getJSONObject("mesParams");
            if (null != mesParamObj && mesParamObj.containsKey("manufacturingOrderArr")) {
                JSONArray manufacturingOrderArr = mesParamObj.getJSONArray("manufacturingOrderArr");
                for (int i = 0; i < manufacturingOrderArr.size(); i++) {
                    JSONObject jsonObject = manufacturingOrderArr.getJSONObject(i);
                    String oriIfsOrderNo = jsonObject.getString("ORDER_NO");
                    if (org.apache.commons.lang3.StringUtils.isBlank(oriIfsOrderNo) || !orderMap.containsKey(oriIfsOrderNo)) {
                        continue;
                    }
                    jsonObject.put("ORDER_NO", orderMap.get(oriIfsOrderNo).getIfsOrderNo());
                }
            }
            ifsLog.setInAttr(JSON.toJSONString(inArrObj));
            if (inArrObj.containsKey("mesParams")) {
                ifsLog.setMesParams(JSON.toJSONString(inArrObj.get("mesParams")));
                inArrObj.remove("mesParams");
            }
        }
        return updateIfsLogs;
    }
 
 
    @Override
    public void refreshUploadIfsOrderNo(List<ManufacturingOderUploadData> list,
                                        List<UploadRefreshIfsOrderNoResultDTO> resultDTOList) {
        List<ManufacturingOrder> manufacturingOrders =
                manufacturingOrderMapper.selectList(Wrappers.<ManufacturingOrder>lambdaQuery().isNotNull(ManufacturingOrder::getIfsOrderNo));
        List<ManufacturingOrder> updateList = new ArrayList<>();
        Map<String, ManufacturingOrder> orderMap =
                manufacturingOrders.stream().collect(Collectors.toMap(ManufacturingOrder::getIfsOrderNo, v -> v,
                        (k1, k2) -> k1));
        for (ManufacturingOderUploadData uploadData : list) {
            UploadRefreshIfsOrderNoResultDTO resultDTO = new UploadRefreshIfsOrderNoResultDTO();
            resultDTO.setIfsOrderNo(uploadData.getIfsOrderNo());
            resultDTO.setOriIfsOrderNo(uploadData.getOriIfsOrderNo());
            if (orderMap.containsKey(uploadData.getOriIfsOrderNo())) {
                ManufacturingOrder manufacturingOrder = orderMap.get(uploadData.getOriIfsOrderNo());
                manufacturingOrder.setIfsOrderNo(uploadData.getIfsOrderNo());
                manufacturingOrder.setOriIfsOrderNo(uploadData.getOriIfsOrderNo());
                resultDTO.setOrderUpdateCount(1);
                updateList.add(manufacturingOrder);
            }
            resultDTOList.add(resultDTO);
        }
        updateBatchById(updateList);
    }
}