李林
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
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
package com.chinaztt.mes.production.service.impl;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
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.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.mes.basic.entity.*;
import com.chinaztt.mes.basic.mapper.JoinStepTemplateMapper;
import com.chinaztt.mes.basic.mapper.PartMapper;
import com.chinaztt.mes.basic.mapper.StaffMapper;
import com.chinaztt.mes.basic.mapper.WorkstationLocationMapper;
import com.chinaztt.mes.basic.service.PartService;
import com.chinaztt.mes.basic.service.WorkstationService;
import com.chinaztt.mes.basic.util.BigDecimalUtils;
import com.chinaztt.mes.basic.util.RedisUtils;
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.common.wrapper.QueryWrapperUtil;
import com.chinaztt.mes.plan.dto.ManufacturingOrderDTO;
import com.chinaztt.mes.plan.dto.ManufacturingOrderSnGenerateDTO;
import com.chinaztt.mes.plan.entity.*;
import com.chinaztt.mes.plan.mapper.*;
import com.chinaztt.mes.plan.service.ManufacturingOrderSnGenerateService;
import com.chinaztt.mes.production.dto.*;
import com.chinaztt.mes.production.entity.*;
import com.chinaztt.mes.production.excel.ProductOutPutData;
import com.chinaztt.mes.production.mapper.*;
import com.chinaztt.mes.production.service.ProductMainService;
import com.chinaztt.mes.production.service.ProductOutputService;
import com.chinaztt.mes.production.state.operationtask.constant.OperationTaskStateStringValues;
import com.chinaztt.mes.production.state.productmain.ProductMainStateMachineConfig;
import com.chinaztt.mes.production.state.productmain.constant.ProductMainEvents;
import com.chinaztt.mes.production.state.productmain.constant.ProductMainStateStringValues;
import com.chinaztt.mes.production.state.productmain.constant.ProductMainStates;
import com.chinaztt.mes.production.state.productout.ProductOutStateMachineConfig;
import com.chinaztt.mes.production.state.productout.constant.ProductOutEvents;
import com.chinaztt.mes.production.state.productout.constant.ProductOutStateStringValues;
import com.chinaztt.mes.production.state.productout.constant.ProductOutStates;
import com.chinaztt.mes.production.util.BackUtils;
import com.chinaztt.mes.production.util.FeedingUtils;
import com.chinaztt.mes.production.util.PrintUrlUtils;
import com.chinaztt.mes.production.util.RedisHelper;
import com.chinaztt.mes.quality.dto.ApplyDTO;
import com.chinaztt.mes.quality.dto.ApplyPartDTO;
import com.chinaztt.mes.quality.entity.Apply;
import com.chinaztt.mes.quality.entity.ApplyPart;
import com.chinaztt.mes.quality.entity.Result;
import com.chinaztt.mes.quality.mapper.ApplyMapper;
import com.chinaztt.mes.quality.mapper.ApplyPartMapper;
import com.chinaztt.mes.quality.mapper.ResultMapper;
import com.chinaztt.mes.quality.service.ApplyService;
import com.chinaztt.mes.technology.dto.StepDTO;
import com.chinaztt.mes.technology.entity.OperationJoinStep;
import com.chinaztt.mes.technology.entity.Step;
import com.chinaztt.mes.technology.mapper.OperationJoinStepMapper;
import com.chinaztt.mes.technology.mapper.RoutingOperationMapper;
import com.chinaztt.mes.technology.mapper.StepMapper;
import com.chinaztt.mes.warehouse.dto.StockDTO;
import com.chinaztt.mes.warehouse.entity.Stock;
import com.chinaztt.mes.warehouse.mapper.StockMapper;
import com.chinaztt.mes.warehouse.util.StockUtils;
import com.chinaztt.mes.warehouse.util.TransactionType;
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.security.util.SecurityUtils;
import com.chinaztt.ztt.common.sequence.sequence.Sequence;
import com.google.gson.Gson;
import com.thoughtworks.xstream.core.BaseException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.env.Environment;
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 java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 报工主表
 *
 * @author cxf
 * @date 2020-11-17 10:12:27
 */
@Service
@Slf4j
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class ProductMainServiceImpl extends ServiceImpl<ProductMainMapper, ProductMain> implements ProductMainService {
    private static final String OUTPUT_LENGTH_LIMIT = "OUTPUT_LENGTH_LIMIT";
    private static final String OUTPUT_UNIT_LIMIT = "OUTPUT_UNIT_LIMIT";
    private ArtificialInformationMapper artificialInformationMapper;
    private ApplyPartMapper applyPartMapper;
    private ApplyMapper applyMapper;
    private ApplyService applyService;
    private BackUtils backUtils;
    private DutyRecordMapper dutyRecordMapper;
    private FeedingMapper feedingMapper;
    private FeedingUtils feedingUtils;
    private HandymanTypeMapper handymanTypeMapper;
    private NumberGenerator<ProductMain> productMainNumberGenerator;
    private NumberGenerator<ProductOutput> productOutputNumberGenerator;
    private OperationTaskServiceImpl operationTaskService;
    private OperationTaskMaterialMapper operationTaskMaterialMapper;
    private OperationTaskProduceMapper operationTaskProduceMapper;
    private OperationTaskMapper operationTaskMapper;
    private PartService partService;
    private PersonBoardMapper personBoardMapper;
    private ProductInputMapper productInputMapper;
    private ProductOutputMapper productOutputMapper;
    private ProductOutputStaffMapper productOutputStaffMapper;
    private ProductStepMapper productStepMapper;
    private ProductStepStaffMapper productStepStaffMapper;
    private ResultMapper resultMapper;
    private StateMachineFactory<ProductMainStates, ProductMainEvents> productMainStateMachineFactory;
    private StateMachinePersister<ProductMainStates, ProductMainEvents, ProductMain> persister;
    private StateMachineFactory<ProductOutStates, ProductOutEvents> productOutStateMachineFactory;
    private StateMachinePersister<ProductOutStates, ProductOutEvents, ProductOutput> productOutPersister;
    private StaffMapper staffMapper;
    private StepMapper stepMapper;
    private StockMapper stockMapper;
    private StockUtils stockUtils;
    private WorkstationService workstationService;
    private WorkstationLocationMapper workstationLocationMapper;
    private ManufacturingOrderMapper manufacturingOrderMapper;
    private MoStructureComponentMapper moStructureComponentMapper;
    private RoutingOperationMapper routingOperationMapper;
    private MoRoutingOperationMapper moRoutingOperationMapper;
    private final PrintUrlUtils printUrlUtils;
    private MouldRegisterMapper mouldRegisterMapper;
    private MouldUseRecordMapper mouldUseRecordMapper;
    private OperationJoinStepMapper operationJoinStepMapper;
    private RemoteParamService remoteParamService;
    private JoinStepTemplateMapper joinStepTemplateMapper;
    private OperationTaskRecordMapper operationTaskRecordMapper;
    private MasterProductionScheduleTheoryQuantityMapper theoryQuantityMapper;
    private ManufacturingOrderSnGenerateMapper manufacturingOrderSnGenerateMapper;
 
    private CustomerOrderMapper customerOrderMapper;
 
    private RedisHelper redisHelper;
 
    private ProductMainMapper productMainMapper;
 
    private ExaminerMapper examinerMapper;
 
    private PartMapper partMapper;
 
    private ProductOutputService productOutputService;
 
    private RedisUtils redisUtils;
    private ManufacturingOrderSnGenerateService manufacturingOrderSnGenerateService;
 
    private Sequence sequence;
 
    private final static String WORKBENCH_LABEL_REPRINT = "WORKBENCH_LABEL_REPRINT";
    private Environment environment;
 
 
    @Override
    public ProductMainDTO getProductMainById(Long id) {
        ProductMainDTO productMainDTO = new ProductMainDTO();
        // 1.查投入
        productMainDTO.setProductInputList(productInputMapper.queryList(id, null));
        // 2.查产出
        productMainDTO.setProductOutputList(productOutputMapper.getByMainId(id));
 
        return productMainDTO;
    }
 
    @Override
    public IPage getProductionProgress(Page page, QueryWrapper<ProductOutputDTO> gen) {
        return productOutputMapper.getProductionProgress(page, gen);
    }
 
    @Override
    public R<Boolean> changeState(Long id, String event) {
        synchronized (String.valueOf(id).intern()) {
            ProductMain productMain = baseMapper.selectById(id);
            Boolean lock = redisHelper.lock("productMain:submit:" + productMain.getId());
            if (BooleanUtil.isFalse(lock)) {
                throw new RuntimeException("报工单正在处理中,请稍后再试");
            }
            try {
                log.info("报工单:" + productMain.getProductNo() + "报工单更改状态" + event);
                Message<ProductMainEvents> message = MessageBuilder.withPayload(ProductMainEvents.valueOf(event)).setHeader("productMain", productMain).build();
                StateMachineHandler handler = new StateMachineHandler(productMainStateMachineFactory, persister, ProductMainStateMachineConfig.MACHINE_ID, productMain);
                StateResult res = handler.sendEvent(message, productMain.getId());
                if (res.isSuccess()) {
//                    // 同步ERP 报工单 TODO
//
//                    List<ProductInputDTO> productInputDTOS = productInputMapper.queryList(id, null);
//                    reportWork(productMain,productInputDTOS);
                    return R.ok();
                } else {
                    throw new RuntimeException(res.getMsg());
                }
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            } finally {
                redisHelper.delLock("productMain:submit:" + productMain.getId());
            }
        }
    }
 
    private R reportWork(ProductMain productMain, List<ProductInputDTO> productInputDTOS) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String syncErpUrl = environment.getProperty("reportWork");
        HttpPost httpPost = new HttpPost(syncErpUrl);
        // 将参数转换为JSON字符串
        Map<String, Object> params = new HashMap<>();
        SaveProcedureProgresEntity saveProcedureProgresEntity = new SaveProcedureProgresEntity();
        BigDecimal num = new BigDecimal(0);
        for (ProductInputDTO bean:productInputDTOS
             ) {
//            num.add(bean.get)
        }
//        saveProcedureProgresEntity.setNum();
        String jsonParams = new Gson().toJson(params);
        // 设置请求体为JSON格式
        StringEntity requestEntity = new StringEntity(jsonParams, ContentType.APPLICATION_JSON);
        httpPost.setEntity(requestEntity);
        String responseString = null;
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity, "UTF-8");
            return new Gson().fromJson(responseString, R.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.failed();
    }
 
    @Override
    public List<ProductOutputDTO> getProductOutPutById(Long id) {
        return productOutputMapper.getProductOutPutById(id);
    }
 
    @Override
    public boolean cancelProductMainById(Long id) {
        // 1.查询报工记录
        ProductMain productMain = baseMapper.selectById(id);
 
        // 校验是否存在交班产出,若交班产出被使用无法删除
        List<ProductOutput> shiftList = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery()
                .eq(ProductOutput::getProductMainId, id)
                .eq(ProductOutput::getState, ProductOutStateStringValues.CHANGESHIFT));
        if (!shiftList.isEmpty()) {
            Integer shiftedNumber = this.productOutputMapper.getShiftedNumberByOutputIds(shiftList.stream().map(ProductOutput::getId).collect(Collectors.toList()));
            if (shiftedNumber > 0) {
                throw new RuntimeException("存在交班数据,交班产出已提交无法删除");
            }
        }
 
        // 2.删除投入,先把投料剩余数量加上去再删除
        List<ProductInput> productInputList = productInputMapper.selectList(Wrappers.<ProductInput>query().lambda().eq(ProductInput::getProductMainId, productMain.getId()));
        if (CollectionUtil.isNotEmpty(productInputList)) {
//            for (ProductInput productInput : productInputList) {
//                feedingUtils.update(productMain.getWorkstationId(), productInput, null, productInput.getInputQuantity());
//            }
            productInputMapper.delete(Wrappers.<ProductInput>query().lambda().eq(ProductInput::getProductMainId, productMain.getId()));
        }
        // 3.删除产出
        productOutputMapper.deleteStaffOutByMainId(productMain.getId());
        productOutputMapper.deleteArtificialInformationByMainId(productMain.getId());
        //逻辑删除
        productOutputMapper.delete(Wrappers.<ProductOutput>query().lambda().eq(ProductOutput::getProductMainId, productMain.getId()));
//        List<ProductOutput>  productOutputList= productOutputMapper.selectList(Wrappers.<ProductOutput>query().lambda().eq(ProductOutput::getProductMainId, productMain.getId()));
//        if(!CollectionUtils.isEmpty(productOutputList)){
//            productOutputList.stream().forEach(e->{
//                e.setIsDeleted("1");
//                productOutputMapper.updateById(e);
//            });
//        }
        // 4.删除报工主表
        baseMapper.deleteById(productMain.getId());
        return true;
    }
 
    @Override
    public Long saveProductOutput(ProductMainDTO productMainDTO) {
        if (productMainDTO.getIsChangeShift()) {
            if (null != productMainDTO.getProductOutputList() && productMainDTO.getProductOutputList().size() > 1) {
                //解决按人员接班产出多条SN一样且为草稿状态的产出,提交时会对该两条产出的SN找到的交班记录相同,导致交班产出的投料被重复统计
                throw new RuntimeException("接班生产 -> 若按人员报工 -> 则不支持指定多人");
            }
        }
        ProductMain productMain = new ProductMain();
        String state = "01pending";
        if (productMainDTO.getId() == null) {
            // 1.自动创建报工主表
            productMain.setOperationTaskId(productMainDTO.getOperationTaskId());
            productMain.setWorkstationId(productMainDTO.getWorkstationId());
            productMain.setProductNo(productMainNumberGenerator.generateNumberWithPrefix(ProductMain.DIGIT, ProductMain.PREFIX, ProductMain::getProductNo));
            productMain.setState(ProductMainStateStringValues.DRAFT);
            baseMapper.insert(productMain);
        } else {
            productMain = baseMapper.selectById(productMainDTO.getId());
        }
        if (ProductMainStateStringValues.SUBMITTED.equals(productMain.getState())) {
            throw new RuntimeException("报工记录已提交,无法修改");
        }
        //产出之后如果工单的状态为等待,改成进行中
        OperationTask operationTask = operationTaskMapper.selectById(productMainDTO.getOperationTaskId());
        if (operationTask != null && state.equals(operationTask.getState())) {
            List<Long> ids = new ArrayList<>();
            ids.add(productMainDTO.getOperationTaskId());
            operationTaskService.changeState(ids, "START");
        }
        //新增产出表和人员
        addOutPutNew(productMainDTO.getProductOutputList(), productMain.getId(), productMainDTO.getWorkstationId(), productMainDTO.getIsChangeShift());
 
        List<ProductOutput> outputList = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery()
                .eq(ProductOutput::getProductMainId, productMain.getId()));
        List<Examiner> examinerList = examinerMapper.selectList(Wrappers.<Examiner>lambdaQuery()
                .eq(Examiner::getPartNo, partMapper.selectById(outputList.get(0).getPartId()).getPartNo()));
        if (CollectionUtil.isEmpty(examinerList)) {
            outputList.stream().forEach(
                    a -> a.setOrigPartId(a.getPartId())
            );
        } else {
            outputList.stream().forEach(
                    a -> {
                        a.setOrigPartId(partMapper.selectOne(Wrappers.<Part>lambdaQuery().eq(Part::getPartNo, examinerList.get(0).getPartNo())).getId());
                        a.setPartId(partMapper.selectOne(Wrappers.<Part>lambdaQuery().eq(Part::getPartNo, examinerList.get(0).getPartNoAfter())).getId());
                    }
            );
        }
        productOutputService.updateBatchById(outputList);
 
 
        //新增产出表和人员
        return productMain.getId();
    }
 
 
    @Override
    public Long batchSaveProductOutput(ProductMainDTO productMainDTO) {
        ProductMain productMain = new ProductMain();
        String state = "01pending";
        if (productMainDTO.getId() == null) {
            // 1.自动创建报工主表
            productMain.setOperationTaskId(productMainDTO.getOperationTaskId());
            productMain.setWorkstationId(productMainDTO.getWorkstationId());
            productMain.setProductNo(productMainNumberGenerator.generateNumberWithPrefix(ProductMain.DIGIT, ProductMain.PREFIX, ProductMain::getProductNo));
            productMain.setState(ProductMainStateStringValues.DRAFT);
            baseMapper.insert(productMain);
        } else {
            productMain = baseMapper.selectById(productMainDTO.getId());
        }
        if (ProductMainStateStringValues.SUBMITTED.equals(productMain.getState())) {
            throw new RuntimeException("报工记录已提交,无法修改");
        }
        //产出之后如果工单的状态为等待,改成进行中
        OperationTask operationTask = operationTaskMapper.selectById(productMainDTO.getOperationTaskId());
        if (operationTask != null && state.equals(operationTask.getState())) {
            List<Long> ids = new ArrayList<>();
            ids.add(productMainDTO.getOperationTaskId());
            operationTaskService.changeState(ids, "START");
        }
        //新增产出表和人员
        List<ProductOutputDTO> productOutputDTOList = batchProductOutputDTOMake(productMainDTO.getProductOutputList());
        addOutPutBatch(productOutputDTOList, productMain.getId(), productMain.getWorkstationId());
        return productMain.getId();
    }
 
    @Override
    public synchronized Boolean batchSaveProductMain(List<ProductMainDTO> productMainDTOList) {
        for (ProductMainDTO productMainDTO : productMainDTOList) {
            // 校验分段描述
            checkSegmentDesc(productMainDTO.getProductOutputList().get(0).getSegmentDesc());
            List<ProductMainDTO> mains = new ArrayList<>();
            String state = "01pending";
            String productNo = productMainNumberGenerator.generateNumberWithPrefix(ProductMain.DIGIT, ProductMain.PREFIX, ProductMain::getProductNo);
            int genNum = Integer.parseInt(productNo.substring(2));
            for (int i = 0; i < productMainDTO.getDiscsNumber(); i++) {
                ProductMainDTO productMain = new ProductMainDTO();
                List<ProductOutputDTO> newProductOutputList = new ArrayList<>();
                ProductOutputDTO newProductOutput = new ProductOutputDTO();
                BeanUtils.copyProperties(productMainDTO.getProductOutputList().get(0), newProductOutput);
                if (CollectionUtil.isNotEmpty(productMainDTO.getOrderSnGenerateIdList())) {
                    newProductOutput.setOrderSnGenerateIdList(productMainDTO.getOrderSnGenerateIdList());
                }
 
                // 校验截止米标位数
                checkEndMeterLength(newProductOutput.getEndMeterMark(), newProductOutput.getUnit());
 
                newProductOutputList.add(newProductOutput);
                // 1.自动创建报工主表
                productMain.setOperationTaskId(productMainDTO.getOperationTaskId());
                productMain.setWorkstationId(productMainDTO.getWorkstationId());
                productMain.setProductNo(ProductMain.PREFIX + String.format("%06d", genNum));
                if (StringUtils.isNotBlank(productMainDTO.getMainRemark())) {
                    boolean b = StringUtils.isNumeric(productMainDTO.getMainRemark());
                    Workstation workstation = workstationService.getById(productMainDTO.getWorkstationId());
                    if (b && workstation.getWorkCenter().equals("SP-07")) {
                        for (ProductOutputDTO productOutputDTO : newProductOutputList) {
                            int mainRemarkNum = Integer.parseInt(productMainDTO.getMainRemark());
                            productOutputDTO.setRemark(mainRemarkNum + i + "");
                        }
                    } else {
                        for (ProductOutputDTO productOutputDTO : newProductOutputList) {
                            productOutputDTO.setRemark(productMainDTO.getMainRemark());
                        }
 
                    }
                }
                /*if(productMainDTO.getMainRemark()==null){
                    long incr = redisUtils.incr("taskOperation" + productMainDTO.getOperationTaskId(), "00", 1);
                    for (ProductOutputDTO productOutputDTO : newProductOutputList) {
                        productOutputDTO.setRemark(incr + "");
                    }
                } else{
                    for (ProductOutputDTO productOutputDTO : newProductOutputList) {
                        productOutputDTO.setRemark(productMainDTO.getMainRemark());
                    }
                }*/
                productMain.setProductOutputList(newProductOutputList);
                productMain.setIsChangeShift(productMainDTO.getIsChangeShift());
                productMain.setState(ProductMainStateStringValues.DRAFT);
//                baseMapper.insert(productMain);
                mains.add(productMain);
                genNum++;
            }
            int number = 500;
            if (CollectionUtil.isNotEmpty(mains)) {
                for (int j = 0; j <= mains.size() / number; j++) {
                    if (CollectionUtil.isNotEmpty(mains.stream().skip(j * number).limit(number).collect(Collectors.toList()))) {
                        this.saveBatch(mains.stream().skip(j * number).limit(number).collect(Collectors.toList()));
                    }
                }
            }
            //产出之后如果工单的状态为等待,改成进行中
            OperationTask operationTask = operationTaskMapper.selectById(productMainDTO.getOperationTaskId());
            if (operationTask != null && state.equals(operationTask.getState())) {
                List<Long> ids = new ArrayList<>();
                ids.add(productMainDTO.getOperationTaskId());
                operationTaskService.changeState(ids, "START");
            }
            // 批量新增产出和人员
            addOutPutBatch(mains);
            for (ProductMainDTO main : mains) {
                List<ProductOutput> outputList = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery()
                        .eq(ProductOutput::getProductMainId, main.getId()));
                List<Examiner> examinerList = examinerMapper.selectList(Wrappers.<Examiner>lambdaQuery()
                        .eq(Examiner::getPartNo, partMapper.selectById(outputList.get(0).getPartId()).getPartNo()));
                if (CollectionUtil.isEmpty(examinerList)) {
                    outputList.stream().forEach(
                            a -> a.setOrigPartId(a.getPartId())
                    );
                } else {
                    outputList.stream().forEach(
                            a -> {
                                a.setOrigPartId(partMapper.selectOne(Wrappers.<Part>lambdaQuery().eq(Part::getPartNo, examinerList.get(0).getPartNo())).getId());
                                a.setPartId(partMapper.selectOne(Wrappers.<Part>lambdaQuery().eq(Part::getPartNo, examinerList.get(0).getPartNoAfter())).getId());
                            }
                    );
                }
                productOutputService.updateBatchById(outputList);
            }
//            for (ProductMain main : mains) {
//                //新增产出表和人员
//                addOutPutNew(productMainDTO.getProductOutputList(), main.getId(), productMainDTO.getWorkstationId(), productMainDTO.getIsChangeShift());
//            }
        }
        return true;
    }
 
    private void checkEndMeterLength(BigDecimal endMeterMark, String unit) {
        String lengthLimit = remoteParamService.getByKey(OUTPUT_LENGTH_LIMIT, SecurityConstants.FROM_IN).getData();
        String unitLimit = remoteParamService.getByKey(OUTPUT_UNIT_LIMIT, SecurityConstants.FROM_IN).getData();
        if (StringUtils.isNotBlank(unitLimit)) {
            Boolean isUnit = unitLimit.equals(unit);
            if (StrUtil.isNotBlank(lengthLimit) && NumberUtils.isCreatable(lengthLimit) && isUnit) {
                int limit = Integer.parseInt(lengthLimit);
                BigDecimal checkEndMeterMark = endMeterMark.stripTrailingZeros();
                if (checkEndMeterMark.precision() - checkEndMeterMark.scale() > limit) {
                    throw new RuntimeException("填写的产量为" + endMeterMark + unit + ",不符合实际!");
                }
            }
        }
    }
 
    private void addOutPutBatch(List<ProductMainDTO> mains) {
        // 获取工作站
        Workstation workstation = workstationService.getById(mains.get(0).getWorkstationId());
        // 获取工步
        Step step = stepMapper.getFirstStep(mains.get(0).getOperationTaskId());
        // 获取工序任务
        OperationTask operationTask = operationTaskMapper.selectById(mains.get(0).getOperationTaskId());
        // 是否交班
        Boolean isShift = mains.get(0).getIsChangeShift();
        // 工艺路线
        MoRoutingOperation routingOperation = moRoutingOperationMapper.findByOperationTaskId(operationTask.getId());
 
        List<ProductOutputDTO> saveProductOutputList = new ArrayList<>();
        //根据批次号进行循环
        Set<Long> dutyRecordIds = new HashSet<Long>();
        //检测申请零件
        List<ApplyPartDTO> applyPartList = new ArrayList<>();
        //工单id
        Set<Long> operationTaskIds = new HashSet<>();
        // 工步
        List<ProductStep> productStepList = new ArrayList<>();
        Long staffId = null;
        Staff staff = staffMapper.getStaffByUserId(SecurityUtils.getUser().getId());
        if (staff != null) {
            staffId = staff.getId();
        }
 
        //每次新增人员都是使用同一个标识号
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String systemNo = formatter.format(LocalDateTime.now());
 
        DateTimeFormatter snFormat = DateTimeFormatter.ofPattern("yyMMdd");
        String snDate = snFormat.format(LocalDateTime.now());
 
/*        //查询最新的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 genNumber = productOutputNumberGenerator.generateNumberWithPrefix(ProductOutput.DIGIT, ProductOutput.PREFIX, ProductOutput::getSystemNo);
        int genNum = Integer.parseInt(genNumber.substring(2));
 
        Part part = partService.getById(mains.get(0).getProductOutputList().get(0).getPartId());
        for (ProductMainDTO main : mains) {
            List<String> lotbatchnoList = new ArrayList<>();
 
            String manufatureAttr = StringUtils.isBlank(operationTask.getManufactureAttr()) ? "N" : operationTask.getManufactureAttr();
            List<ProductOutputDTO> productOutputDTOList = main.getProductOutputList();
            for (int i = 0; i < productOutputDTOList.size(); i++) {
                ProductOutputDTO productOutputDTO = new ProductOutputDTO();
                productOutputDTO.setSystemNo(ProductOutput.PREFIX + String.format("%06d", genNum));
                productOutputDTO.setPartId(productOutputDTOList.get(i).getPartId());
                productOutputDTO.setIsSnGenerateOutput(false);
                int num = Integer.parseInt(sequence.nextNo().substring(8));
                String snno = snDate + String.format("%06d", num) + manufatureAttr;
 
                // 判断是否是段长生成的报工
                if (CollectionUtil.isNotEmpty(productOutputDTOList.get(i).getOrderSnGenerateIdList())) {
                    int check = manufacturingOrderSnGenerateService.count(Wrappers.<ManufacturingOrderSnGenerate>lambdaQuery()
                            .in(ManufacturingOrderSnGenerate::getId, productOutputDTOList.get(i).getOrderSnGenerateIdList())
                            .eq(ManufacturingOrderSnGenerate::getProduceStatus, true));
                    if (check > 0) {
                        throw new RuntimeException("该批次号已经报工");
                    }
                    manufacturingOrderSnGenerateService.updateProduceStatus(productOutputDTOList.get(i).getOrderSnGenerateIdList(), true,
                            StringUtils.isNotBlank(productOutputDTOList.get(i).getOutBatchNo()) ? productOutputDTOList.get(i).getOutBatchNo() : snno);
                    productOutputDTO.setIsSnGenerateOutput(true);
                }
 
                if (StringUtils.isBlank(productOutputDTOList.get(i).getOutBatchNo())) {
                    //非交接新增
                    productOutputDTO.setOutBatchNo(snno);
                } else {
                    productOutputDTO.setOutBatchNo(productOutputDTOList.get(i).getOutBatchNo());
                    if (isShift && CollectionUtil.isEmpty(productOutputDTOList.get(i).getOrderSnGenerateIdList())) {
                        // 查询交班产出
                        ProductOutput shift = productOutputMapper.selectOne(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getOutBatchNo, productOutputDTO.getOutBatchNo()).orderByDesc(ProductOutput::getEndMeterMark).last("limit 1"));
                        productOutputDTO.setShiftOutputId(shift.getId());
                    }
                }
                // 获取工步,如果存在工步,则执行跳线工步逻辑,清空产量信息
                if (step != null) {
                    //productOutputDTOList.get(i).setEndMeterMark(BigDecimal.ZERO);
                    //productOutputDTOList.get(i).setStartMeterMark(BigDecimal.ZERO);
                    productStepList.add(generateSteps(main.getId(), main.getOperationTaskId(), step, productOutputDTO));
                }
                if (part.getLotTrackingIfs() != null && part.getLotTrackingIfs()) {
                    productOutputDTO.setIfsBatchNo(StringUtils.isNotBlank(productOutputDTOList.get(i).getIfsBatchNo()) ? productOutputDTOList.get(i).getIfsBatchNo() : productOutputDTO.getOutBatchNo());
                } else {
                    productOutputDTO.setIfsBatchNo("*");
                }
                productOutputDTO.setReelNumber(productOutputDTOList.get(i).getReelNumber());
                productOutputDTO.setProductQty(productOutputDTOList.get(i).getEndMeterMark().subtract(productOutputDTOList.get(i).getStartMeterMark()));
                productOutputDTO.setProductMainId(main.getId());
                productOutputDTO.setSortNo(num);
                productOutputDTO.setStartMeterMark(productOutputDTOList.get(i).getStartMeterMark());
                productOutputDTO.setEndMeterMark(productOutputDTOList.get(i).getEndMeterMark());
                productOutputDTO.setSegmentDesc(productOutputDTOList.get(i).getSegmentDesc());
                productOutputDTO.setScrapQty(productOutputDTOList.get(i).getScrapQty() == null ? BigDecimal.ZERO : productOutputDTOList.get(i).getScrapQty());
                productOutputDTO.setRemark(productOutputDTOList.get(i).getRemark());
                productOutputDTO.setSproductQty(productOutputDTOList.get(i).getSproductQty());
 
                productOutputDTO.setWorkstationId(workstation.getId());
                productOutputDTO.setProductStaffIds(productOutputDTOList.get(i).getProductStaffIds());
                productOutputDTO.setDutyRecordId(productOutputDTOList.get(i).getDutyRecordId());
                productOutputDTO.setPartId(productOutputDTOList.get(i).getPartId());
                productOutputDTO.setStatus(productOutputDTOList.get(i).getStatus());
                productOutputDTO.setGrossWeight(productOutputDTOList.get(i).getGrossWeight());
                productOutputDTO.setReelWeight(productOutputDTOList.get(i).getReelWeight());
                // 盘具重量和毛重都不为空,则计算实际净重
                if (productOutputDTOList.get(i).getReelWeight() != null && productOutputDTOList.get(i).getGrossWeight() != null) {
                    productOutputDTO.setNetWeight(productOutputDTOList.get(i).getGrossWeight().subtract(productOutputDTOList.get(i).getReelWeight()));
                }
                productOutputDTO.setDiscToolMeasurement(productOutputDTOList.get(i).getDiscToolMeasurement());
                saveProductOutputList.add(productOutputDTO);
                dutyRecordIds.add(productOutputDTOList.get(i).getDutyRecordId());
 
                // 自动加投入 (如果有工步,自动投入在工步处理)
                //if (step == null) {
                // 跳线车间,报工单操作提前,不在最后一个工步的时候处理
                autoAddInput(main.getOperationTaskId(), main.getWorkstationId(), main.getId(), productOutputDTO.getProductQty().add(productOutputDTO.getScrapQty() == null ? BigDecimal.ZERO : productOutputDTO.getScrapQty()));
                //}
 
                // 如果工单状态为等待或暂停,则改为开始
                if (operationTask.getState().equals(OperationTaskStateStringValues.PENDING) || operationTask.getState().equals(OperationTaskStateStringValues.INTERRUPTED)) {
                    operationTaskIds.add(main.getOperationTaskId());
                }
 
                // 报工产量为0则生成首检 (去掉限制)
                if (routingOperation.getAutoInspection() != null && routingOperation.getAutoInspection()) {
                    if (!isShift) {
                        if (!lotbatchnoList.contains(snno)) {
                            ApplyPartDTO partDTO = new ApplyPartDTO();
                            partDTO.setId(productOutputDTO.getId());
                            partDTO.setOutBatchNo(productOutputDTO.getOutBatchNo());
                            partDTO.setPartId(productOutputDTO.getPartId());
                            partDTO.setSystemNo(productOutputDTO.getSystemNo());
                            partDTO.setPartName(part.getPartName());
                            partDTO.setPartNo(part.getPartNo());
                            applyPartList.add(partDTO);
                            lotbatchnoList.add(snno);
                        }
                    }
                }
                //num++;
                genNum++;
            }
        }
 
 
        int number = 500;
        if (CollectionUtil.isNotEmpty(saveProductOutputList)) {
            for (int j = 0; j <= saveProductOutputList.size() / number; j++) {
                if (CollectionUtil.isNotEmpty(saveProductOutputList.stream().skip(j * number).limit(number).collect(Collectors.toList()))) {
                    productOutputMapper.batchInsert(saveProductOutputList.stream().skip(j * number).limit(number).collect(Collectors.toList()));
                }
            }
        }
 
        //修改对应的人员数据
        buildOutStaffBatch(saveProductOutputList, systemNo);
//        buildOutStaff(productOutputDTOList.get(i).getProductStaffIds(), productOutputDTO.getId(), productOutputDTOList.get(i).getProductQty(), productOutputDTOList.get(i).getStatus(), systemNo, productOutputDTOList.get(i).getDutyRecordId());
        //根据人员数据自动生成零件对应的人工记录
        autoBuildArtificialInformationBatch(saveProductOutputList);
//        autoBuildArtificialInformation(productOutputDTOList.get(i).getProductStaffIds(), productOutputDTO.getId(), productOutputDTOList.get(i).getProductQty(), productOutputDTOList.get(i).getDutyRecordId(), productOutputDTOList.get(i).getPartId(), productMain.getWorkstationId(), productOutputDTO.getOutBatchNo());
 
        // 更新班次产量
        refreshDutyRecord(dutyRecordIds);
        // 生成首检
        if (!applyPartList.isEmpty()) {
            //ApplyDTO applyDTO = new ApplyDTO();
            //applyDTO.setApplyPartList(applyPartList);
            //applyDTO.setApplyType(Apply.FIRST_APPLY);
            //ThreadUtil.execAsync(() -> applyService.saveDto(applyDTO));
            //工作台产出记录创建时批量生成一个首检申请单改为单独申请首检申请单【2022-09-20】
            for (int i = 0; i < applyPartList.size(); i++) {
                ApplyDTO applyDTO = new ApplyDTO();
                List<ApplyPartDTO> applyPartDTOList = new ArrayList<>();
                applyPartDTOList.add(applyPartList.get(i));
                applyDTO.setApplyPartList(applyPartDTOList);
                applyDTO.setApplyType(Apply.FIRST_APPLY);
                applyDTO.setRemark("自动报检:" + workstation.getName());//新增首检的备注【2022-09-22】
                applyService.saveDto(applyDTO);
            }
        }
        // 将工单状态改为进行中
        if (!operationTaskIds.isEmpty()) {
            operationTaskService.changeState(new ArrayList<>(operationTaskIds), "START");
        }
        // 保存工步
        if (!productStepList.isEmpty()) {
            Long staffId1 = staffId;
            ThreadUtil.execute(() -> addProductOutStep(productStepList, staffId1));
        }
    }
 
    private void autoBuildArtificialInformationBatch(List<ProductOutputDTO> saveProductOutputList) {
        List<ArtificialInformation> saveList = new ArrayList<>();
        for (ProductOutputDTO productOutputDTO : saveProductOutputList) {
            // 1.根据零件/工作站查询对应的人工类型
            HandymanType handymanType = handymanTypeMapper.selectByWorkstationIdAndPartId(productOutputDTO.getWorkstationId(), productOutputDTO.getPartId());
            if (handymanType != null) {
                // 2.再生成对应的人工记录
                if (CollectionUtil.isNotEmpty(productOutputDTO.getProductStaffIds())) {
                    List<Long> ids = new ArrayList<Long>();
                    for (Long staffId : productOutputDTO.getProductStaffIds()) {
                        // 根据人员编号/班次id查出对应的上班人员id
                        PersonBoard personBoard = personBoardMapper.selectByDutyRecordIdAndStaffId(productOutputDTO.getDutyRecordId(), staffId);
                        ArtificialInformation artificialInformation = new ArtificialInformation();
                        artificialInformation.setOutputId(productOutputDTO.getId());
                        artificialInformation.setPersonOutput(productOutputDTO.getProductQty());
                        artificialInformation.setDutyRecordId(productOutputDTO.getDutyRecordId());
                        artificialInformation.setHandymanTypeId(handymanType.getId());
                        artificialInformation.setRemark(productOutputDTO.getRemark());
                        if (personBoard != null) {
                            artificialInformation.setProductionPersonId(personBoard.getId());
                        }
                        saveList.add(artificialInformation);
                        ids.add(artificialInformation.getId());
                    }
                }
            }
        }
        int number = 500;
        if (CollectionUtil.isNotEmpty(saveList)) {
            for (int j = 0; j <= saveList.size() / number; j++) {
                if (CollectionUtil.isNotEmpty(saveList.stream().skip(j * number).limit(number).collect(Collectors.toList()))) {
                    artificialInformationMapper.batchInsert(saveList.stream().skip(j * number).limit(number).collect(Collectors.toList()));
                }
            }
        }
    }
 
    private void buildOutStaffBatch(List<ProductOutputDTO> saveProductOutputList, String systemNo) {
        List<ProductOutputStaff> saveList = new ArrayList<>();
        for (ProductOutputDTO productOutputDTO : saveProductOutputList) {
            if (CollectionUtil.isNotEmpty(productOutputDTO.getProductStaffIds())) {
                List<Staff> staffList = staffMapper.selectListAll();
                for (Long staff : productOutputDTO.getProductStaffIds()) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    ProductOutputStaff outputStaff = new ProductOutputStaff();
                    staffList.forEach(a -> {
                        if (a.getId().equals(staff)) {
                            outputStaff.setStaffNo(a.getStaffNo());
                        }
                    });
                    outputStaff.setStaffId(staff);
                    outputStaff.setProductOutId(productOutputDTO.getId());
                    outputStaff.setSystemNo(systemNo);
                    outputStaff.setDutyRecordId(productOutputDTO.getDutyRecordId());
                    outputStaff.setDate(formatter.format(LocalDateTime.now()));
                    outputStaff.setQuantity(productOutputDTO.getProductQty());
                    outputStaff.setArtificialType(productOutputDTO.getStatus());
                    saveList.add(outputStaff);
                }
            }
        }
        int number = 500;
        if (CollectionUtil.isNotEmpty(saveList)) {
            for (int j = 0; j <= saveList.size() / number; j++) {
                if (CollectionUtil.isNotEmpty(saveList.stream().skip(j * number).limit(number).collect(Collectors.toList()))) {
                    productOutputStaffMapper.batchInsert(saveList.stream().skip(j * number).limit(number).collect(Collectors.toList()));
                }
            }
        }
    }
 
    private ProductStep generateSteps(Long productMainId, Long operationTaskId, Step step, ProductOutputDTO productOutput) {
        //报工的工步
        ProductStep productStep = new ProductStep();
        productStep.setStepId(step.getId());
        productStep.setOperationTaskId(operationTaskId);
        productStep.setNumber(BigDecimal.ZERO);
        productStep.setProductMainId(productMainId);
        productStep.setStepBatchNo(productOutput.getIfsBatchNo());
        productStep.setSystemNo(productOutput.getOutBatchNo());
        return productStep;
    }
 
    @Override
    public Boolean batchUpdateProductMain(List<ProductMainDTO> productMainDTOList) {
        for (ProductMainDTO productMainDTO : productMainDTOList) {
            // 校验分段描述
            checkSegmentDesc(productMainDTO.getProductOutputList().get(0).getSegmentDesc());
            // 校验截止米标位数
            checkEndMeterLength(productMainDTO.getProductOutputList().get(0).getEndMeterMark(), productMainDTO.getProductOutputList().get(0).getUnit());
        }
        for (ProductMainDTO productMainDTO : productMainDTOList) {
            List<ProductOutput> productOutputs = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getProductMainId, productMainDTO.getId()));
            for (ProductOutput productOutput : productOutputs) {
                ProductOutputDTO productOutputDTO = productMainDTO.getProductOutputList().get(0);
                ProductOutput productOutputOriginal = productOutputMapper.selectById(productOutput.getId());
                BigDecimal oldProductQty = productOutputOriginal.getProductQty();
                BigDecimal oldScrapQty = productOutputOriginal.getScrapQty();
                ProductMain productMain = baseMapper.selectById(productOutputOriginal.getProductMainId());
                if (ProductMainStateStringValues.SUBMITTED.equals(productMain.getState())) {
                    throw new RuntimeException("报工记录已提交,无法修改");
                }
                if (StringUtils.equals(ProductMainStateStringValues.PROCESSING, productMain.getState())) {
                    throw new RuntimeException("报工记录处理中,无法修改");
                }
                productOutputOriginal.setReelNumber(productOutputDTO.getReelNumber());
                productOutputOriginal.setStartMeterMark(productOutputDTO.getStartMeterMark());
                productOutputOriginal.setEndMeterMark(productOutputDTO.getEndMeterMark());
                productOutputOriginal.setProductQty(productOutputDTO.getEndMeterMark().subtract(productOutputDTO.getStartMeterMark()));
                productOutputOriginal.setOutBatchNo(productOutputDTO.getOutBatchNo());
                productOutputOriginal.setIfsBatchNo(productOutputDTO.getIfsBatchNo());
                productOutputOriginal.setSegmentDesc(productOutputDTO.getSegmentDesc());
                productOutputOriginal.setScrapQty(productOutputDTO.getScrapQty());
                productOutputOriginal.setRemark(productOutputDTO.getRemark());
                productOutputOriginal.setGrossWeight(productOutputDTO.getGrossWeight());
                productOutputOriginal.setReelWeight(productOutputDTO.getReelWeight());
                if (productOutputOriginal.getGrossWeight() != null && productOutputOriginal.getReelWeight() != null) {
                    productOutputOriginal.setNetWeight(productOutputOriginal.getGrossWeight().subtract(productOutputOriginal.getReelWeight()));
                }
                productOutputMapper.updateById(productOutputOriginal);
                UpdateWrapper<ProductOutputStaff> updateWrapper = new UpdateWrapper();
                updateWrapper.lambda().eq(ProductOutputStaff::getProductOutId, productOutputOriginal.getId()).set(ProductOutputStaff::getQuantity, productOutputOriginal.getProductQty());
                productOutputStaffMapper.update(null, updateWrapper);
 
                //修改投料的数量(投料计算:产出数量+报废数量)
                BigDecimal incrementQty = oldProductQty.add(oldScrapQty).subtract(productOutputOriginal.getProductQty()).subtract(productOutputOriginal.getScrapQty() == null ? BigDecimal.ZERO : productOutputOriginal.getScrapQty());
                if (incrementQty.compareTo(BigDecimal.ZERO) == 1) {
                    // 根据终值去计算投入,不再根据增量去删
                    autoDeleteInputV2(Collections.singletonList(productMain.getId()), TransactionType.OUTPUT_UPDATE.getValue());
                    autoAddInput(productMain.getOperationTaskId(), productMain.getWorkstationId(), productMain.getId(), productOutputOriginal.getProductQty().add(productOutputOriginal.getScrapQty() == null ? BigDecimal.ZERO : productOutputOriginal.getScrapQty()));
                } else if (incrementQty.compareTo(BigDecimal.ZERO) == -1) {
                    // 自动加投入
                    autoAddInput(productMain.getOperationTaskId(), productMain.getWorkstationId(), productMain.getId(), incrementQty.negate());
                }
                // 更新班次产量
                List<ProductOutputStaff> productOutputStaffList = productOutputStaffMapper.selectList(Wrappers.<ProductOutputStaff>lambdaQuery().in(ProductOutputStaff::getProductOutId, productOutput.getId()));
                Set<Long> dutyRecordIds = productOutputStaffList.stream().map(ProductOutputStaff::getDutyRecordId).collect(Collectors.toSet());
                refreshDutyRecord(dutyRecordIds);
                //dutyRecordMapper.refreshDutyOutputById(productOutputDTO.getDutyRecordId());
            }
        }
        return true;
    }
 
    public void checkSegmentDesc(String segmentDesc) {
        if (StringUtils.isNotBlank(segmentDesc)) {
            String[] split = segmentDesc.split("\\+");
            if (split.length > 1) {
                for (String desc : split) {
                    if (!NumberUtils.isCreatable(desc)) {
                        throw new RuntimeException("分段描述只能用数字分段");
                    }
                }
            } else {
                throw new RuntimeException("分段描述格式不正确");
            }
        }
    }
 
    private List<ProductOutputDTO> batchProductOutputDTOMake(List<ProductOutputDTO> productOutputDTOS) {
        List<ProductOutputDTO> productOutputDTOList = new LinkedList<>();
        for (ProductOutputDTO productOutputDTO : productOutputDTOS) {
            for (int i = 0; i < productOutputDTO.getDisNumber(); i++) {
                ProductOutputDTO outputDTO = new ProductOutputDTO();
                outputDTO.setWorkstationId(productOutputDTO.getWorkstationId());
                outputDTO.setOperationTaskId(productOutputDTO.getOperationTaskId());
                outputDTO.setPartId(productOutputDTO.getPartId());
                outputDTO.setStartMeterMark(BigDecimal.ZERO);
                outputDTO.setEndMeterMark(productOutputDTO.getProductQty());
                outputDTO.setProductQty(productOutputDTO.getProductQty());
                outputDTO.setProductStaffs(productOutputDTO.getProductStaffs());
                outputDTO.setProductStaffIds(productOutputDTO.getProductStaffIds());
                outputDTO.setDutyRecordId(productOutputDTO.getDutyRecordId());
                outputDTO.setStatus(productOutputDTO.getStatus());
                outputDTO.setProductMainId(productOutputDTO.getProductMainId());
                outputDTO.setRemark(productOutputDTO.getRemark());
                outputDTO.setIfsBatchNo(productOutputDTO.getIfsBatchNo());
                outputDTO.setReelNumber(productOutputDTO.getReelNumber());
                outputDTO.setScrapQty(productOutputDTO.getScrapQty());
                outputDTO.setSegmentDesc(productOutputDTO.getSegmentDesc());
                productOutputDTOList.add(outputDTO);
            }
        }
        return productOutputDTOList;
    }
 
 
    private void addOutPut(List<ProductOutputDTO> productOutputDTOList, Long id, Long workstationId) {
        //根据产出批号进行分组
        Map<String, List<ProductOutputDTO>> productOutputList = productOutputDTOList.stream().collect(Collectors.groupingBy(ProductOutput::getOutBatchNo));
        //每次新增人员都是使用同一个标识号
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String systemNo = formatter.format(LocalDateTime.now());
        //根据批次号进行循环
        Set<Long> dutyRecordIds = new HashSet<Long>();
        for (String key : productOutputList.keySet()) {
            ProductOutputDTO productOutputDTO = new ProductOutputDTO();
            //查询是否存在相同批次的产出
            ProductOutput dbOutput = productOutputMapper.selectOne(Wrappers.<ProductOutput>lambdaQuery()
                    .eq(ProductOutput::getProductMainId, id).eq(ProductOutput::getOutBatchNo, key));
            //获取当前key下的产出数据
            List<ProductOutputDTO> productOutput = productOutputList.get(key);
            if (dbOutput != null) {
                //如果存在相同批次的产出
                BigDecimal productQty = dbOutput.getProductQty();
                for (ProductOutputDTO newProductOutput : productOutput) {
                    productQty = productQty.add(newProductOutput.getProductQty());
                    productOutputDTO.setPartId(dbOutput.getPartId());
                    productOutputDTO.setOutBatchNo(dbOutput.getOutBatchNo());
                    productOutputDTO.setProductMainId(dbOutput.getProductMainId());
                    productOutputDTO.setSystemNo(dbOutput.getSystemNo());
                    productOutputDTO.setId(dbOutput.getId());
                    dutyRecordIds.add(newProductOutput.getDutyRecordId());
                    //修改对应的人员数据
                    buildOutStaff(newProductOutput.getProductStaffIds(), dbOutput.getId(), newProductOutput.getProductQty(), newProductOutput.getStatus(), systemNo, newProductOutput.getDutyRecordId());
                    //根据人员数据自动生成零件对应的人工记录
                    autoBuildArtificialInformation(newProductOutput.getProductStaffIds(), productOutputDTO.getId(), newProductOutput.getProductQty(), newProductOutput.getDutyRecordId(), newProductOutput.getPartId(), workstationId, key);
                }
                productOutputDTO.setProductQty(productQty);
                productOutputMapper.updateById(productOutputDTO);
            } else {
                BigDecimal productQty = BigDecimal.ZERO;
                for (ProductOutputDTO newProductOutput : productOutput) {
                    productOutputDTO.setSystemNo(productOutputNumberGenerator.generateNumberWithPrefix(ProductOutput.DIGIT, ProductOutput.PREFIX, ProductOutput::getSystemNo));
                    productQty = productQty.add(newProductOutput.getProductQty());
                    productOutputDTO.setPartId(newProductOutput.getPartId());
                    productOutputDTO.setOutBatchNo(newProductOutput.getOutBatchNo());
                }
                productOutputDTO.setProductQty(productQty);
                productOutputDTO.setProductMainId(id);
                productOutputMapper.insert(productOutputDTO);
                for (ProductOutputDTO newProductOutput : productOutput) {
                    dutyRecordIds.add(newProductOutput.getDutyRecordId());
                    //修改对应的人员数据
                    buildOutStaff(newProductOutput.getProductStaffIds(), productOutputDTO.getId(), newProductOutput.getProductQty(), newProductOutput.getStatus(), systemNo, newProductOutput.getDutyRecordId());
                    //根据人员数据自动生成零件对应的人工记录
                    autoBuildArtificialInformation(newProductOutput.getProductStaffIds(), productOutputDTO.getId(), newProductOutput.getProductQty(), newProductOutput.getDutyRecordId(), newProductOutput.getPartId(), workstationId, key);
                }
            }
            ProductMain productMain = baseMapper.selectById(productOutputDTO.getProductMainId());
            if (dbOutput != null) {
                BigDecimal incrementQty = dbOutput.getProductQty().subtract(productOutputDTO.getProductQty());
                if (incrementQty.compareTo(BigDecimal.ZERO) == 1) {
                    // 自动删投入
                    autoDeleteInput(productOutputDTO.getProductMainId(), incrementQty);
                } else if (incrementQty.compareTo(BigDecimal.ZERO) == -1) {
                    // 自动加投入
                    autoAddInput(productMain.getOperationTaskId(), productMain.getWorkstationId(), productMain.getId(), incrementQty.negate());
                }
            } else {
                autoAddInput(productMain.getOperationTaskId(), productMain.getWorkstationId(), productMain.getId(), productOutputDTO.getProductQty());
            }
        }
        // 更新班次产量
        refreshDutyRecord(dutyRecordIds);
    }
 
 
    private synchronized void addOutPutBatch(List<ProductOutputDTO> productOutputDTOList, Long id, Long workstationId) {
        DateTimeFormatter snFormat = DateTimeFormatter.ofPattern("yyMMdd");
        String snDate = snFormat.format(LocalDateTime.now());
        Workstation workstation = workstationService.getById(workstationId);
        // SN码= 2位年 + 2位月 + 2位日 + 六位流水号 + 工单制造类型
        String sn = snDate;
        //每次新增人员都是使用同一个标识号
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        //
        String systemNo = formatter.format(LocalDateTime.now());
        //根据批次号进行循环
        Set<Long> dutyRecordIds = new HashSet<Long>();
        //检测申请零件
        List<ApplyPartDTO> applyPartList = new ArrayList<>();
        //工单id
        Set<Long> operationTaskIds = new HashSet<>();
 
        List<String> snNos = operationTaskProduceMapper.getSnNumbers(snDate + "%");
        int num = 0;
        if (CollectionUtil.isNotEmpty(snNos)) {
            String snNo = snNos.get(0);
            num = Integer.parseInt(snNo.substring(6, snNo.length() - 1));
        }
        // 校验分段描述
        for (ProductOutputDTO productOutputDTO : productOutputDTOList) {
            checkSegmentDesc(productOutputDTO.getSegmentDesc());
        }
        ProductMain productMain = baseMapper.selectById(id);
        OperationTask operationTask = operationTaskMapper.selectById(productMain.getOperationTaskId());
        String manufatureAttr = StringUtils.isBlank(operationTask.getManufactureAttr()) ? "N" : operationTask.getManufactureAttr();
        for (int i = 0; i < productOutputDTOList.size(); i++) {
            ProductOutputDTO productOutputDTO = new ProductOutputDTO();
            productOutputDTO.setSystemNo(productOutputNumberGenerator.generateNumberWithPrefix(ProductOutput.DIGIT, ProductOutput.PREFIX, ProductOutput::getSystemNo));
            productOutputDTO.setPartId(productOutputDTOList.get(i).getPartId());
            //SN号码
            productOutputDTO.setOutBatchNo(sn + String.format("%06d", num + 1) + manufatureAttr);
            //数量
            productOutputDTO.setProductQty(productOutputDTOList.get(i).getProductQty());
            //载具编号
            productOutputDTO.setReelNumber(productOutputDTOList.get(i).getReelNumber());
            //主表id
            productOutputDTO.setProductMainId(id);
            //序号
            productOutputDTO.setSortNo(num + 1);
            //开始计米
            productOutputDTO.setStartMeterMark(productOutputDTOList.get(i).getStartMeterMark());
            //结束计米
            productOutputDTO.setEndMeterMark(productOutputDTOList.get(i).getEndMeterMark());
            //ifs批次号
            productOutputDTO.setIfsBatchNo(StringUtils.isNotBlank(productOutputDTOList.get(i).getIfsBatchNo()) ? productOutputDTOList.get(i).getIfsBatchNo() : productOutputDTO.getOutBatchNo());
            //报废数量
            productOutputDTO.setScrapQty(productOutputDTOList.get(i).getScrapQty());
            //分段描述
            productOutputDTO.setSegmentDesc(productOutputDTOList.get(i).getSegmentDesc());
            //备注
            productOutputDTO.setRemark(productOutputDTOList.get(i).getRemark());
            productOutputMapper.insert(productOutputDTO);
            dutyRecordIds.add(productOutputDTOList.get(i).getDutyRecordId());
            //修改对应的人员数据
            buildOutStaff(productOutputDTOList.get(i).getProductStaffIds(), productOutputDTO.getId(), productOutputDTOList.get(i).getProductQty(), productOutputDTOList.get(i).getStatus(), systemNo, productOutputDTOList.get(i).getDutyRecordId());
            //根据人员数据自动生成零件对应的人工记录
            autoBuildArtificialInformation(productOutputDTOList.get(i).getProductStaffIds(), productOutputDTO.getId(), productOutputDTOList.get(i).getProductQty(), productOutputDTOList.get(i).getDutyRecordId(), productOutputDTOList.get(i).getPartId(), workstationId, productOutputDTO.getOutBatchNo());
            // 自动加投入
            autoAddInput(productMain.getOperationTaskId(), productMain.getWorkstationId(), productMain.getId(), productOutputDTO.getProductQty().add(productOutputDTO.getScrapQty() == null ? BigDecimal.ZERO : productOutputDTO.getScrapQty()));
            // 如果工单状态为等待或暂停,则改为开始
            if (operationTask.getState().equals(OperationTaskStateStringValues.PENDING) || operationTask.getState().equals(OperationTaskStateStringValues.INTERRUPTED)) {
                operationTaskIds.add(productMain.getOperationTaskId());
            }
            ApplyPartDTO partDTO = new ApplyPartDTO();
            partDTO.setId(productOutputDTO.getId());
            partDTO.setOutBatchNo(productOutputDTO.getOutBatchNo());
            partDTO.setPartId(productOutputDTO.getPartId());
            partDTO.setSystemNo(productOutputDTO.getSystemNo());
            Part part = partService.getById(partDTO.getPartId());
            partDTO.setPartName(part.getPartName());
            partDTO.setPartNo(part.getPartNo());
            applyPartList.add(partDTO);
            num += 1;
        }
        // 更新班次产量
        refreshDutyRecord(dutyRecordIds);
        // 生成首检
        if (!applyPartList.isEmpty()) {
            //ApplyDTO applyDTO = new ApplyDTO();
            //applyDTO.setApplyPartList(applyPartList);
            //applyDTO.setApplyType(Apply.FIRST_APPLY);
            //applyService.saveDto(applyDTO);
            //工作台产出记录创建时批量生成一个首检申请单改为单独申请首检申请单【2022-09-20】
            for (int i = 0; i < applyPartList.size(); i++) {
                ApplyDTO applyDTO = new ApplyDTO();
                List<ApplyPartDTO> applyPartDTOList = new ArrayList<>();
                applyPartDTOList.add(applyPartList.get(i));
                applyDTO.setApplyPartList(applyPartDTOList);
                applyDTO.setApplyType(Apply.FIRST_APPLY);
                applyDTO.setRemark("自动报检:" + workstation.getName());//新增首检的备注【2022-09-22】
                applyService.saveDto(applyDTO);
            }
        }
        // 将工单状态改为进行中
        if (!operationTaskIds.isEmpty()) {
            operationTaskService.changeState(new ArrayList<>(operationTaskIds), "START");
        }
    }
 
 
    private synchronized void addOutPutNew(List<ProductOutputDTO> productOutputDTOList, Long id, Long workstationId, Boolean isShift) {
        DateTimeFormatter snFormat = DateTimeFormatter.ofPattern("yyMMdd");
        String snDate = snFormat.format(LocalDateTime.now());
        Workstation workstation = workstationService.getById(workstationId);
        // SN码=2位年+月+机台号+日+俩位数流水
        String sn = snDate.substring(0, 4) + workstation.getWorkstationNo() + snDate.substring(4);
        //每次新增人员都是使用同一个标识号
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        //
        String systemNo = formatter.format(LocalDateTime.now());
        //根据批次号进行循环
        Set<Long> dutyRecordIds = new HashSet<Long>();
        //检测申请零件
        List<ApplyPartDTO> applyPartList = new ArrayList<>();
        //工单id
        Set<Long> operationTaskIds = new HashSet<>();
 
/*        //查询最新的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));
        }*/
        List<String> lotbatchnoList = new ArrayList<>();
        ProductMain productMain = baseMapper.selectById(id);
        // 获取工步
        Step step = stepMapper.getFirstStep(productMain.getOperationTaskId());
        List<ProductStep> productStepList = new ArrayList<>();
        Long staffId = null;
        Staff staff = staffMapper.getStaffByUserId(SecurityUtils.getUser().getId());
        if (staff != null) {
            staffId = staff.getId();
        }
        OperationTask operationTask = operationTaskMapper.selectById(productMain.getOperationTaskId());
        String manufatureAttr = StringUtils.isBlank(operationTask.getManufactureAttr()) ? "N" : operationTask.getManufactureAttr();
        for (int i = 0; i < productOutputDTOList.size(); i++) {
            // 校验截止米标位数
            checkEndMeterLength(productOutputDTOList.get(i).getEndMeterMark(), productOutputDTOList.get(i).getUnit());
            ProductOutputDTO productOutputDTO = new ProductOutputDTO();
            productOutputDTO.setSystemNo(productOutputNumberGenerator.generateNumberWithPrefix(ProductOutput.DIGIT, ProductOutput.PREFIX, ProductOutput::getSystemNo));
            productOutputDTO.setPartId(productOutputDTOList.get(i).getPartId());
            int num = Integer.parseInt(sequence.nextNo().substring(8));
            String snno = snDate + String.format("%06d", num) + manufatureAttr;
            if (StringUtils.isBlank(productOutputDTOList.get(i).getOutBatchNo())) {
                //非交接新增
                productOutputDTO.setOutBatchNo(snno);
            } else {
                productOutputDTO.setOutBatchNo(productOutputDTOList.get(i).getOutBatchNo());
                if (isShift) {
                    // 查询交班产出
                    ProductOutput shift = productOutputMapper.selectOne(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getOutBatchNo, productOutputDTO.getOutBatchNo()).orderByDesc(ProductOutput::getEndMeterMark).last("limit 1"));
                    productOutputDTO.setShiftOutputId(shift.getId());
                }
            }
            // 获取工步,如果存在工步,则执行跳线工步逻辑,清空产量信息
            if (step != null) {
                productOutputDTOList.get(i).setEndMeterMark(BigDecimal.ZERO);
                productOutputDTOList.get(i).setStartMeterMark(BigDecimal.ZERO);
                productStepList.add(generateSteps(productMain.getId(), productMain.getOperationTaskId(), step, productOutputDTO));
            }
            productOutputDTO.setIfsBatchNo(StringUtils.isNotBlank(productOutputDTOList.get(i).getIfsBatchNo()) ? productOutputDTOList.get(i).getIfsBatchNo() : productOutputDTO.getOutBatchNo());
            productOutputDTO.setReelNumber(productOutputDTOList.get(i).getReelNumber());
            productOutputDTO.setProductQty(productOutputDTOList.get(i).getEndMeterMark().subtract(productOutputDTOList.get(i).getStartMeterMark()));
            productOutputDTO.setProductMainId(id);
            productOutputDTO.setSortNo(num);
            productOutputDTO.setStartMeterMark(productOutputDTOList.get(i).getStartMeterMark());
            productOutputDTO.setEndMeterMark(productOutputDTOList.get(i).getEndMeterMark());
            productOutputDTO.setSegmentDesc(productOutputDTOList.get(i).getSegmentDesc());
            productOutputDTO.setScrapQty(productOutputDTOList.get(i).getScrapQty());
            productOutputDTO.setRemark(productOutputDTOList.get(i).getRemark());
            productOutputDTO.setSproductQty(productOutputDTOList.get(i).getSproductQty());
            productOutputMapper.insert(productOutputDTO);
            dutyRecordIds.add(productOutputDTOList.get(i).getDutyRecordId());
            //修改对应的人员数据
            buildOutStaff(productOutputDTOList.get(i).getProductStaffIds(), productOutputDTO.getId(), productOutputDTOList.get(i).getProductQty(), productOutputDTOList.get(i).getStatus(), systemNo, productOutputDTOList.get(i).getDutyRecordId());
            //根据人员数据自动生成零件对应的人工记录
            autoBuildArtificialInformation(productOutputDTOList.get(i).getProductStaffIds(), productOutputDTO.getId(), productOutputDTOList.get(i).getProductQty(), productOutputDTOList.get(i).getDutyRecordId(), productOutputDTOList.get(i).getPartId(), productMain.getWorkstationId(), productOutputDTO.getOutBatchNo());
            // 自动加投入
            autoAddInput(productMain.getOperationTaskId(), productMain.getWorkstationId(), productMain.getId(), productOutputDTO.getProductQty().add(productOutputDTO.getScrapQty() == null ? BigDecimal.ZERO : productOutputDTO.getScrapQty()));
            // 如果工单状态为等待或暂停,则改为开始
            if (operationTask.getState().equals(OperationTaskStateStringValues.PENDING) || operationTask.getState().equals(OperationTaskStateStringValues.INTERRUPTED)) {
                operationTaskIds.add(productMain.getOperationTaskId());
            }
            MoRoutingOperation routingOperation = moRoutingOperationMapper.findByProductMainId(productMain.getId());
            // 报工产量为0则生成首检 (去掉限制)
            if (routingOperation.getAutoInspection() != null && routingOperation.getAutoInspection()) {
                if (!isShift) {
                    if (!lotbatchnoList.contains(snno)) {
                        ApplyPartDTO partDTO = new ApplyPartDTO();
                        partDTO.setId(productOutputDTO.getId());
                        partDTO.setOutBatchNo(productOutputDTO.getOutBatchNo());
                        partDTO.setPartId(productOutputDTO.getPartId());
                        partDTO.setSystemNo(productOutputDTO.getSystemNo());
                        Part part = partService.getById(partDTO.getPartId());
                        partDTO.setPartName(part.getPartName());
                        partDTO.setPartNo(part.getPartNo());
                        applyPartList.add(partDTO);
                        lotbatchnoList.add(snno);
                    }
                }
            }
            //num++;
        }
        // 更新班次产量
        refreshDutyRecord(dutyRecordIds);
        // 生成首检
        if (!applyPartList.isEmpty()) {
            //ApplyDTO applyDTO = new ApplyDTO();
            //applyDTO.setApplyPartList(applyPartList);
            //applyDTO.setApplyType(Apply.FIRST_APPLY);
            //applyService.saveDto(applyDTO);
            //工作台产出记录创建时批量生成一个首检申请单改为单独申请首检申请单【2022-09-20】
            for (int i = 0; i < applyPartList.size(); i++) {
                ApplyDTO applyDTO = new ApplyDTO();
                List<ApplyPartDTO> applyPartDTOList = new ArrayList<>();
                applyPartDTOList.add(applyPartList.get(i));
                applyDTO.setApplyPartList(applyPartDTOList);
                applyDTO.setApplyType(Apply.FIRST_APPLY);
                applyDTO.setRemark("自动报检:" + workstation.getName());//新增首检的备注【2022-09-22】
                applyService.saveDto(applyDTO);
            }
        }
        // 将工单状态改为进行中
        if (!operationTaskIds.isEmpty()) {
            operationTaskService.changeState(new ArrayList<>(operationTaskIds), "START");
        }
        // 保存工步
        if (!productStepList.isEmpty()) {
            Long staffId1 = staffId;
            ThreadUtil.execute(() -> addProductOutStep(productStepList, staffId1));
        }
    }
 
    private void addProductOutStep(List<ProductStep> productStepList, Long id) {
        int number = 500;
        if (CollectionUtil.isNotEmpty(productStepList)) {
            for (int j = 0; j <= productStepList.size() / number; j++) {
                if (CollectionUtil.isNotEmpty(productStepList.stream().skip(j * number).limit(number).collect(Collectors.toList()))) {
                    productStepMapper.addProductOutStep(productStepList.stream().skip(j * number).limit(number).collect(Collectors.toList()));
                    productStepStaffMapper.addProductOutStepStaff(productStepList.stream().skip(j * number).limit(number).collect(Collectors.toList()), id);
                }
            }
        }
    }
 
    /**
     * 报工到人
     *
     * @param staffIds
     * @param productOutId
     */
    private void buildOutStaff(List<Long> staffIds, Long productOutId, BigDecimal productQty, Boolean status, String systemNo, Long id) {
        if (CollectionUtil.isNotEmpty(staffIds)) {
            List<Staff> staffList = staffMapper.selectListAll();
            for (Long staff : staffIds) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                ProductOutputStaff outputStaff = new ProductOutputStaff();
                staffList.forEach(a -> {
                    if (a.getId().equals(staff)) {
                        outputStaff.setStaffNo(a.getStaffNo());
                    }
                });
                outputStaff.setStaffId(staff);
                outputStaff.setProductOutId(productOutId);
                outputStaff.setSystemNo(systemNo);
                outputStaff.setDutyRecordId(id);
                outputStaff.setDate(formatter.format(LocalDateTime.now()));
                outputStaff.setQuantity(productQty);
                outputStaff.setArtificialType(status);
                productOutputStaffMapper.insert(outputStaff);
            }
        }
    }
 
    /**
     * 根据人员数据自动生成零件对应的人工记录
     */
    private void autoBuildArtificialInformation(List<Long> staffIds, Long productOutId, BigDecimal productQty, Long dutyRecordId, Long partId, Long workstationId, String remark) {
        // 1.根据零件/工作站查询对应的人工类型
        HandymanType handymanType = handymanTypeMapper.selectByWorkstationIdAndPartId(workstationId, partId);
        if (handymanType != null) {
            // 2.再生成对应的人工记录
            if (CollectionUtil.isNotEmpty(staffIds)) {
                List<Long> ids = new ArrayList<Long>();
                for (Long staffId : staffIds) {
                    // 根据人员编号/班次id查出对应的上班人员id
                    PersonBoard personBoard = personBoardMapper.selectByDutyRecordIdAndStaffId(dutyRecordId, staffId);
                    ArtificialInformation artificialInformation = new ArtificialInformation();
                    artificialInformation.setOutputId(productOutId);
                    artificialInformation.setPersonOutput(productQty);
                    artificialInformation.setDutyRecordId(dutyRecordId);
                    artificialInformation.setHandymanTypeId(handymanType.getId());
                    artificialInformation.setRemark(remark);
                    if (personBoard != null) {
                        artificialInformation.setProductionPersonId(personBoard.getId());
                    }
                    artificialInformationMapper.insert(artificialInformation);
                    ids.add(artificialInformation.getId());
                }
            }
        }
 
    }
 
    /**
     * 自动添加对应数量的投入
     */
    public void autoAddInput1(Long operationTaskId, Long workstationId, Long productMainId, BigDecimal productQty) {
        // 3.1.根据工单查询投入产出比
        List<OperationTaskMaterial> operationTaskMaterialList = operationTaskMaterialMapper.selectList(Wrappers.<OperationTaskMaterial>query().lambda().
                eq(OperationTaskMaterial::getOperationTaskId, operationTaskId));
        if (CollectionUtil.isNotEmpty(operationTaskMaterialList)) {
            // 3.2 根据投入比去查询对应的投料数量
            FeedingDTO param = new FeedingDTO();
            param.setWorkstationId(workstationId);
            for (OperationTaskMaterial operationTaskMaterial : operationTaskMaterialList) {
                param.setPartId(operationTaskMaterial.getPartId());
                // 根据零件id和工作站id 查询投料数据
                List<FeedingDTO> feedingList = feedingMapper.getFeedingByParam(QueryWrapperUtil.gen(param));
                // 投入总数量=投入比*产出数量
                BigDecimal summary = operationTaskMaterial.getQpa().multiply(productQty);
                if (CollectionUtil.isNotEmpty(feedingList)) {
                    for (FeedingDTO feedingDTO : feedingList) {
                        BigDecimal feedingCost;
                        ProductInput productInput = productInputMapper.selectOne(Wrappers.<ProductInput>lambdaQuery()
                                .eq(ProductInput::getProductMainId, productMainId).eq(ProductInput::getPartId, feedingDTO.getPartId())
                                .eq(ProductInput::getPartBatchNo, feedingDTO.getPartBatchNo()).eq(ProductInput::getSystemNo, feedingDTO.getSystemNo())
                                .eq(ProductInput::getStockId, feedingDTO.getStockId()));
                        if (feedingDTO.getResidualQuantity().compareTo(summary) == -1) {
                            feedingCost = feedingDTO.getResidualQuantity();
                            summary = summary.subtract(feedingDTO.getResidualQuantity());
                        } else {
                            feedingCost = summary;
                            summary = BigDecimal.ZERO;
                        }
//                        addOrUpdateProductInput(productInput, feedingDTO, feedingCost, productMainId);
                        // 3.4 减去对应投料数量
                        feedingUtils.updateById(feedingDTO.getId(), null, feedingCost.negate());
                        if (summary.compareTo(BigDecimal.ZERO) == 0) {
                            break;
                        }
                    }
                }
            }
        }
    }
 
 
    /**
     * 自动添加对应数量的投入
     */
    public void autoAddInput(Long operationTaskId, Long workstationId, Long productMainId, BigDecimal productQty) {
        String taskMoNo = operationTaskMapper.getTaskMoNo(operationTaskId);
        Long firstOperationId = operationTaskMapper.getFirstOperationId(operationTaskId);
        Long operationId = operationTaskMapper.getOperationIdByTaskId(operationTaskId);
        // 3.1.根据工单查询投入产出比
        List<OperationTaskMaterial> operationTaskMaterialList = operationTaskMaterialMapper.selectList(Wrappers.<OperationTaskMaterial>query().lambda().
                eq(OperationTaskMaterial::getOperationTaskId, operationTaskId));
        if (CollectionUtil.isNotEmpty(operationTaskMaterialList)) {
            // 3.2 根据投入比去查询对应的投料数量
            WorkstationLocation workstationLocation = workstationLocationMapper.selectOne(Wrappers.<WorkstationLocation>lambdaQuery()
                    .eq(WorkstationLocation::getWorkstationId, workstationId)
                    .eq(WorkstationLocation::getLocationType, WorkstationLocation.FED_LOCATION));
            if (workstationLocation == null) {
                throw new RuntimeException("该机台未绑定机台已投料库位");
            }
            for (OperationTaskMaterial operationTaskMaterial : operationTaskMaterialList) {
                //投入总数量=投入比*产出数量
                BigDecimal summary = operationTaskMaterial.getQpa().multiply(productQty);
                if (summary.compareTo(BigDecimal.ZERO) == 0) {
                    continue;
                }
                List<Stock> stockList = stockMapper.selectList(Wrappers.<Stock>lambdaQuery()
                        .eq(Stock::getPartId, operationTaskMaterial.getPartId())
                        .eq(Stock::getLocationId, workstationLocation.getLocationId())
                        .gt(Stock::getAvailableStockQuantity, BigDecimal.ZERO)
                        .orderByAsc(Stock::getUpdateTime));
                // 获取工单所需物料结构
                Map<Long, List<MoStructureComponent>> collect = getComponentList(operationTaskId);
                Part part = partService.getById(operationTaskMaterial.getPartId());
                if (collect.get(operationTaskMaterial.getPartId()) == null) {
                    continue;
                }
                for (Stock stock : stockList) {
                    String ifsLineItemNo = null;
                    String billNo = RandomStringUtils.random(10, true, true);
                    if (collect.get(stock.getPartId()).get(0).getIfsLineItemNo() != null) {
                        ifsLineItemNo = collect.get(stock.getPartId()).get(0).getIfsLineItemNo();
                    }
                    // 增加是否为工序库存
                    setOperationStockStatus(stock, part, operationTaskId);
                    // 工序库存判定
                    String wpbo = remoteParamService.getByKey(Constant.WORKBEHCH_PR_BP_OSC, SecurityConstants.FROM_IN).getData();
                    //取消工序库存的限制
                    if (BooleanUtil.isTrue(stock.getOperationStockStatus()) && !StringUtils.equals(wpbo, "false")) {
                        String stockMoNo = stockMapper.getStockMoNo(stock.getId());
                        if (!StringUtils.equals(stockMoNo, taskMoNo) && !firstOperationId.equals(operationId)) {
                            continue;
                        }
                    }
                    BigDecimal feedingCost;
                    //库存小于计算量则全部消耗掉
                    if (stock.getAvailableStockQuantity().compareTo(summary) == -1) {
                        feedingCost = stock.getAvailableStockQuantity();
                        stockUtils.updateById(stock.getId(), stock.getAvailableStockQuantity().negate(), BigDecimal.ZERO,
                                BigDecimal.ZERO, BigDecimal.ZERO, billNo, TransactionType.SUBMIT_CONSUME.getValue());
                    } else {
                        feedingCost = summary;
                        stockUtils.updateById(stock.getId(), summary.negate(), BigDecimal.ZERO,
                                BigDecimal.ZERO, BigDecimal.ZERO, billNo, TransactionType.SUBMIT_CONSUME.getValue());
                    }
                    List<ProductInput> inputList = new ArrayList<>();
                    // 判断是否存在相同的组件结构,如果是则生成多份投入
                    List<MoStructureComponent> moStructureComponents = collect.get(stock.getPartId());
                    if (moStructureComponents.size() > 1) {
                        BigDecimal total = moStructureComponents.stream().map(MoStructureComponent::getQpa).reduce(BigDecimal.ZERO, BigDecimal::add);
                        BigDecimal inputQty = BigDecimal.ZERO;
                        for (int i = 0; i < moStructureComponents.size(); i++) {
                            ProductInput productInput = productInputMapper.selectOne(Wrappers.<ProductInput>lambdaQuery()
                                    .eq(ProductInput::getProductMainId, productMainId)
                                    .eq(ProductInput::getPartId, stock.getPartId())
                                    .eq(ProductInput::getPartBatchNo, stock.getPartBatchNo())
                                    .eq(ProductInput::getSystemNo, stock.getSystemNo())
                                    .eq(ProductInput::getStockId, stock.getId())
                                    .eq(ProductInput::getIfsLineItemNo, moStructureComponents.get(i).getIfsLineItemNo()));
                            BigDecimal cost =
                                    feedingCost.multiply(moStructureComponents.get(i).getQpa()).divide(total, 6, RoundingMode.HALF_UP);
                            // 如果是最后一个,则消耗剩余数量
                            if (i == moStructureComponents.size() - 1) {
                                cost = feedingCost.subtract(inputQty);
                            }
                            inputQty = inputQty.add(cost);
                            if (productInput == null && cost.compareTo(BigDecimal.ZERO) > 0) {
                                productInput = new ProductInput();
                                productInput.setInputQuantity(cost);
                                productInput.setIfsLineItemNo(moStructureComponents.get(i).getIfsLineItemNo());
                            } else {
                                productInput.setInputQuantity(productInput.getInputQuantity().add(cost));
                            }
                            inputList.add(productInput);
                        }
                    } else {
                        ProductInput productInput = productInputMapper.selectOne(Wrappers.<ProductInput>lambdaQuery()
                                .eq(ProductInput::getProductMainId, productMainId)
                                .eq(ProductInput::getPartId, stock.getPartId())
                                .eq(ProductInput::getPartBatchNo, stock.getPartBatchNo())
                                .eq(ProductInput::getSystemNo, stock.getSystemNo())
                                .eq(ProductInput::getStockId, stock.getId())
                                .eq(ProductInput::getIfsLineItemNo, moStructureComponents.get(0).getIfsLineItemNo()));
                        if (productInput == null) {
                            productInput = new ProductInput();
                            productInput.setInputQuantity(feedingCost);
                            productInput.setIfsLineItemNo(moStructureComponents.get(0).getIfsLineItemNo());
                        } else {
                            productInput.setInputQuantity(productInput.getInputQuantity().add(feedingCost));
                        }
                        inputList.add(productInput);
                    }
 
                    addOrUpdateProductInput(inputList, stock, productMainId);
                    // 总需消耗减去已消耗
                    summary = summary.subtract(feedingCost);
                    if (summary.compareTo(BigDecimal.ZERO) == 0) {
                        break;
                    }
                }
            }
            // 如果投入数量不足,则抛出异常
            long count = operationTaskMaterialList.stream().map(OperationTaskMaterial::getPartId).distinct().count();
            Integer inputNumber = productInputMapper.countPartNumber(productMainId);
            if (!inputNumber.equals((int) count)) {
                throw new RuntimeException("投入物料与所需物料数量不符,请补充");
            }
        }
    }
 
 
    private void queryProductIn(Long productMainId, Long partId, String partBatchNo) {
        productInputMapper.selectOne(Wrappers.<ProductInput>lambdaQuery()
                .eq(ProductInput::getProductMainId, productMainId).eq(ProductInput::getPartId, partId).eq(ProductInput::getPartBatchNo, partBatchNo));
    }
 
    @Override
    public boolean updateProductOutput(ProductMainDTO productMainDTO) {
        ProductOutputDTO productOutputDTO = productMainDTO.getProductOutputList().get(0);
        ProductOutput productOutputOriginal = productOutputMapper.selectById(productOutputDTO.getId());
        BigDecimal oldProductQty = productOutputOriginal.getProductQty();
        BigDecimal oldScrapQty = productOutputOriginal.getScrapQty();
        ProductMain productMain = baseMapper.selectById(productOutputOriginal.getProductMainId());
        if (ProductMainStateStringValues.SUBMITTED.equals(productMain.getState())) {
            throw new RuntimeException("报工记录已提交,无法修改");
        }
        //更新产出的数据
        BigDecimal productQty = BigDecimal.ZERO;
        for (ProductOutputDTO productOutput : productMainDTO.getProductOutputList()) {
            productQty = productQty.add(productOutput.getProductQty());
        }
        checkSegmentDesc(productOutputDTO.getSegmentDesc());
        productOutputOriginal.setReelNumber(productOutputDTO.getReelNumber());
        productOutputOriginal.setStartMeterMark(productOutputDTO.getStartMeterMark());
        productOutputOriginal.setEndMeterMark(productOutputDTO.getEndMeterMark());
        productOutputOriginal.setProductQty(productQty);
        productOutputOriginal.setOutBatchNo(productOutputDTO.getOutBatchNo());
        productOutputOriginal.setIfsBatchNo(productOutputDTO.getIfsBatchNo());
        productOutputOriginal.setSegmentDesc(productOutputDTO.getSegmentDesc());
        productOutputOriginal.setScrapQty(productOutputDTO.getScrapQty());
        productOutputOriginal.setRemark(productOutputDTO.getRemark());
        productOutputMapper.updateById(productOutputOriginal);
        //修改投料的数量(投料数量:计算产量+报废数量)
        BigDecimal incrementQty = oldProductQty.add(oldScrapQty).subtract(productQty).subtract(productOutputOriginal.getScrapQty() == null ? BigDecimal.ZERO : productOutputOriginal.getScrapQty());
        if (incrementQty.compareTo(BigDecimal.ZERO) == 1) {
            // 根据终值去计算投入,不再根据增量去删
            autoDeleteInputV2(Collections.singletonList(productMain.getId()), TransactionType.OUTPUT_UPDATE.getValue());
            autoAddInput(productMain.getOperationTaskId(), productMain.getWorkstationId(), productMain.getId(), productQty.add(productOutputOriginal.getScrapQty() == null ? BigDecimal.ZERO : productOutputOriginal.getScrapQty()));
        } else if (incrementQty.compareTo(BigDecimal.ZERO) == -1) {
            // 自动加投入
            autoAddInput(productMain.getOperationTaskId(), productMain.getWorkstationId(), productMain.getId(), incrementQty.negate());
        }
        //将本次产出的人员全部删除
        productOutputStaffMapper.delete(Wrappers.<ProductOutputStaff>lambdaQuery().eq(ProductOutputStaff::getProductOutId, productOutputDTO.getId()));
        //将本次产出的人工记录全部删除
        List<ArtificialInformation> list = artificialInformationMapper.selectList(Wrappers.<ArtificialInformation>lambdaQuery().eq(ArtificialInformation::getOutputId, productOutputDTO.getId()));
        List<Long> ids = list.stream().map(ArtificialInformation::getId).collect(Collectors.toList());
        backUtils.backDeleteArtificialInformationByIds(ids);
        artificialInformationMapper.delete(Wrappers.<ArtificialInformation>lambdaQuery().eq(ArtificialInformation::getOutputId, productOutputDTO.getId()));
        for (ProductOutputDTO productOutput : productMainDTO.getProductOutputList()) {
            //添加人员
            addStaff(productOutput);
            autoBuildArtificialInformation(productOutput.getProductStaffIds(), productOutputDTO.getId(), productOutput.getProductQty(), productOutput.getDutyRecordId(), productOutputOriginal.getPartId(), productMain.getWorkstationId(), productOutput.getOutBatchNo());
        }
        // 更新班次产量
        dutyRecordMapper.refreshDutyOutputById(productOutputDTO.getDutyRecordId());
        return true;
    }
 
    /**
     * 报工到人
     *
     * @param productOutput
     */
    private void addStaff(ProductOutputDTO productOutput) {
        if (CollectionUtil.isNotEmpty(productOutput.getProductStaffIds())) {
            List<Staff> staffList = staffMapper.selectList(null);
            for (Long staff : productOutput.getProductStaffIds()) {
                ProductOutputStaff outputStaff = new ProductOutputStaff();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                staffList.forEach(a -> {
                    if (a.getId().equals(staff)) {
                        outputStaff.setStaffNo(a.getStaffNo());
                    }
                });
                outputStaff.setStaffId(staff);
                outputStaff.setProductOutId(productOutput.getId());
                if (productOutput.getSystemNo() == null) {
                    outputStaff.setSystemNo(formatter.format(LocalDateTime.now()));
                } else {
                    outputStaff.setSystemNo(productOutput.getSystemNo());
                }
                outputStaff.setDate(newFormatter.format(LocalDateTime.now()));
                outputStaff.setQuantity(productOutput.getProductQty());
                outputStaff.setDutyRecordId(productOutput.getDutyRecordId());
                outputStaff.setArtificialType(productOutput.getStatus());
                productOutputStaffMapper.insert(outputStaff);
            }
        }
    }
 
 
    @Override
    public ProductOutputDTO getShiftedProductByWidAndOpId(Long workstationId, Long opeartionTaskId) {
        List<ProductOutputDTO> productOutputList = productOutputMapper.getShiftProductOutByOpIdAndWsId(workstationId, opeartionTaskId);
        if (CollectionUtils.isEmpty(productOutputList)) {
            return null;
        } else {
            return productOutputList.get(0);
        }
    }
 
    @Override
    public IPage<List<ProductMainListDTO>> getList(Page page, QueryWrapper<ProductMainListDTO> gen) {
        return baseMapper.getList(page, gen);
    }
 
    @Override
    public R<Boolean> changeProductOutPutStateByMainId(Long id, String event) {
        List<ProductOutput> productOutputs = this.productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getProductMainId, id));
        for (ProductOutput productOutput : productOutputs) {
            if (("CHANGESHIFTTODRAFT").equals(event)) {
                Integer selectCount =
                        productOutputMapper.selectCount(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getOutBatchNo, productOutput.getOutBatchNo())
                                .gt(ProductOutput::getId, productOutput.getId()));
                if (selectCount > 0) {
                    throw new RuntimeException("该交班产出已存在接班产出记录");
                }
            }
/*            if(("DRAFTTOCHANGESHIFT").equals(event)){
                List<ProductOutputStaff> productOutputStaffList = productOutputStaffMapper.selectList(Wrappers.<ProductOutputStaff>lambdaQuery()
                        .eq(ProductOutputStaff::getProductOutId, productOutput.getId()));
                List<String> stateList = productOutputMapper.getStateByDutyRecordId(productOutputStaffList.get(0).getDutyRecordId());
                if(stateList.contains("03changeshift")){
                    throw new RuntimeException("同一个班次中,不允许存在多个状态为“交班”状态的报工单存在");
                }
            }*/
            Message<ProductOutEvents> message = MessageBuilder.withPayload(ProductOutEvents.valueOf(event)).setHeader("productOutput", productOutput).build();
            StateMachineHandler handler = new StateMachineHandler(productOutStateMachineFactory, productOutPersister, ProductOutStateMachineConfig.MACHINE_ID, productOutput);
            StateResult res = handler.sendEvent(message, productOutput.getId());
            if (!res.isSuccess()) {
                return R.failed(res.getMsg());
            }
        }
        return R.ok();
    }
 
    @Override
    public Boolean batchCancelProductMain(List<Long> ids) {
        synchronized (ids.toString().intern()) {
            List<ProductMain> productMains = this.baseMapper.selectBatchIds(ids);
            if (productMains.size() != ids.size()) {
                throw new RuntimeException("报工单已删除,请刷新页面");
            }
            boolean processing =
                    productMains.stream().anyMatch(m -> StringUtils.equals(ProductMainStateStringValues.PROCESSING,
                            m.getState()));
            if (BooleanUtil.isTrue(processing)) {
                throw new RuntimeException("存在处理中的报工记录,无法删除");
            }
            if (!productMains.isEmpty()) {
                List<ProductOutput> productOutputs = this.productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().in(ProductOutput::getProductMainId, ids));
                if (!productOutputs.isEmpty()) {
                    for (ProductOutput output : productOutputs) {
                        if (!output.getState().equals(ProductOutStateStringValues.DRAFT)) {
                            throw new RuntimeException("存在不是草稿状态下的产出记录无法直接删除");
                        }
                        // 存在段长来的产出单,需要处理段长批次生成表单
                        if (output.getIsSnGenerateOutput()) {
                            manufacturingOrderSnGenerateService.updateProduceStatusBySn(output.getOutBatchNo(), false, null);
                        }
                    }
                    this.deleteProductOutputByIds(productOutputs.stream().map(ProductOutput::getId).collect(Collectors.toList()));
                }
                for (Long id : ids) {
                    this.cancelProductMainById(id);
                }
                // 判断是否存在工步,存在则删除
                batchCancelStep(ids);
            }
            return true;
        }
    }
 
    private void batchCancelStep(List<Long> ids) {
        //删除工步
        List<ProductStep> productStepList = productStepMapper.selectList(Wrappers.<ProductStep>lambdaQuery().in(ProductStep::getProductMainId, ids));
        if (CollectionUtil.isNotEmpty(productStepList)) {
            Set<Long> productStepIds = productStepList.stream().map(o -> o.getId()).collect(Collectors.toSet());
            productStepMapper.delete(Wrappers.<ProductStep>lambdaQuery().in(ProductStep::getId, productStepIds));
            productStepStaffMapper.delete(Wrappers.<ProductStepStaff>lambdaQuery().in(ProductStepStaff::getProductStepId, productStepIds));
        }
    }
 
    @Override
    public Boolean batchChange(List<Long> ids, String event) {
//        List<ProductMain> productMains = this.baseMapper.selectBatchIds(ids);
//        if (!productMains.isEmpty()) {
//            if (event.equals("REVOKE") || event.equals("CHANGESHIFTTODRAFT")) {
//                // 更改报工单状态
//                for (Long id : ids) {
//                    changeState(id, event);
//                }
//
//                // 找出报工单下产出,并修改产出状态
//                List<ProductOutput> productOutputs = this.productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().in(ProductOutput::getProductMainId, ids));
//                if (!productOutputs.isEmpty()) {
//                    List<Long> shiftIds = new ArrayList<>();
//                    List<Long> outIds = new ArrayList<>();
//                    for (ProductOutput productOutput : productOutputs) {
//                        if (productOutput.getState().equals("03changeshift")) {
//                            shiftIds.add(productOutput.getId());
//                        } else {
//                            outIds.add(productOutput.getId());
//                        }
//                    }
//                    if (!shiftIds.isEmpty()) {
//                        R<Boolean> r = this.changeProductOutPutState(shiftIds, "CHANGESHIFTTODRAFT");
//                        if (r.getCode() != 0) {
//                            throw new RuntimeException(r.getMsg() == null ? "产出撤销未成功" : r.getMsg());
//                        }
//                    }
//                    if (!outIds.isEmpty()) {
//                        R<Boolean> r = this.changeProductOutPutState(outIds, event);
//                        if (r.getCode() != 0) {
//                            throw new RuntimeException(r.getMsg() == null ? "产出撤销未成功" : r.getMsg());
//                        }
//                    }
//                }
//            } else {
//                // 找出报工单下产出,并修改产出状态
//                List<ProductOutput> productOutputs = this.productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().in(ProductOutput::getProductMainId, ids));
//                if (!productOutputs.isEmpty()) {
//                    List<Long> outIds = productOutputs.stream().filter(out -> !out.getState().equals("03changeshift")).map(ProductOutput::getId).collect(Collectors.toList());
//                    R<Boolean> r = this.changeProductOutPutState(outIds, event);
//                    if (r.getCode() != 0) {
//                        throw new RuntimeException(r.getMsg() == null ? "产出提交未成功" : r.getMsg());
//                    }
//                }
//
//                // 更改报工单状态
//                for (Long id : ids) {
//                    changeState(id, event);
//                }
//            }
//        }
        for (Long id : ids) {
            //try {
            //    Boolean lock = redisHelper.lock(event + ":" + id);
            //    if (BooleanUtil.isFalse(lock)) {
            //        throw new RuntimeException("当前正在处理中,请稍后刷新页面查看");
            //    }
            //    ThreadUtil.execute(()->changeState(id, event));
            //}finally {
            //    redisHelper.delLock(event + ":" + id);
            //}
            //updateProcessing(id);
            //ThreadUtil.execute(()->changeState(id, event));
            changeState(id, event);
        }
        return true;
    }
 
    private void updateProcessing(Long id) {
        ProductMain productMain = productMainMapper.selectById(id);
        if (StringUtils.equals(ProductMainStateStringValues.PROCESSING, productMain.getState())) {
            throw new RuntimeException("处理中,请稍后再试");
        }
        productMain.setState(ProductMainStateStringValues.PROCESSING);
        updateById(productMain);
    }
 
    @Override
    public String getPrintUrl(Integer type, Long id, String sn) {
        if (type == 1) {
            return printUrlUtils.getPrintUrl() + id;
        } else if (type == 2) {
            List<ProductOutput> productOutputs = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getProductMainId, id));
            return printUrlUtils.getPrintUrl() + productOutputs.get(0).getId();
        } else if (type == 3) {
            return printUrlUtils.getSnPrintUrl() + "sn=" + (StringUtils.isNotBlank(sn) ? sn : "");
        } else {
            List<ProductOutput> productOutputs = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getProductMainId, id));
            return printUrlUtils.getSmallPrintUrl() + productOutputs.get(0).getId();
        }
    }
 
    @Override
    public boolean deleteProductOutputByIds(List<Long> ids) {
        //报工判断
        List<ProductOutput> productOutputList = productOutputMapper.selectBatchIds(ids);
        //查询主表的id
        List<Long> productMainIds = productOutputList.stream().map(ProductOutput::getProductMainId).distinct().collect(Collectors.toList());
        //根据报工id 和 提交状态 查询报工主表的数据
        Integer productMainCount = getBaseMapper().selectCount(Wrappers.<ProductMain>lambdaQuery()
                .in(ProductMain::getId, productMainIds)
                .eq(ProductMain::getState, ProductMainStateStringValues.SUBMITTED));
        if (productMainCount > 0) {
            throw new RuntimeException("存在已提交报工,无法修改");
        }
        //查询检测结果的数据判断是否
        //SN numbers
        Set<String> snNumbers = productOutputList.stream().map(productOutput -> productOutput.getSystemNo()).collect(Collectors.toSet());
 
        List<Result> resultList = resultMapper.selectList(Wrappers.<Result>lambdaQuery().in(Result::getSystemNo, snNumbers));
 
        if (resultList.size() > 0) {
            if (resultList.stream().filter(result -> result.getIsQualified() != null).count() > 0) {
                throw new RuntimeException("存在已检测合格的数据,无法修改");
            }
            resultMapper.deleteBatchIds(resultList.stream().map(result -> result.getId()).collect(Collectors.toList()));
        }
        //查询检测申请数据
        List<ApplyPart> applyPartList = applyPartMapper.selectList(Wrappers.<ApplyPart>lambdaQuery().in(ApplyPart::getSystemNo, snNumbers));
 
        if (!CollectionUtils.isEmpty(applyPartList)) {
            //判断检测申请是否汇报
            List<ApplyPart> applyPartListChecked = applyPartList.stream().filter(e -> null != e.getReportId()).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(applyPartListChecked)) {
                //删除检测申请
                List<Long> applyIds = applyPartList.stream().map(ApplyPart::getApplyId).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(applyIds)) {
                    applyMapper.deleteBatchIds(applyIds);
                }
                //删除检测申请材料
                List<Long> applyPartIds = applyPartList.stream().map(ApplyPart::getId).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(applyPartIds)) {
                    applyPartMapper.deleteBatchIds(applyPartIds);
                }
 
            } else {
                throw new RuntimeException("已经存在检测汇报,请先删除检测汇报!");
            }
        }
        // 删除产出和人工记录
        List<ProductOutputStaff> productOutputStaffList = productOutputStaffMapper.selectList(Wrappers.<ProductOutputStaff>lambdaQuery().in(ProductOutputStaff::getProductOutId, ids));
 
        productOutputStaffMapper.delete(Wrappers.<ProductOutputStaff>lambdaQuery().in(ProductOutputStaff::getProductOutId, ids));
        //逻辑删除 产出表记录
        productOutputMapper.delete(Wrappers.<ProductOutput>lambdaQuery().in(ProductOutput::getId, ids));
        //
        List<ArtificialInformation> artificialInformationList = artificialInformationMapper.selectList(Wrappers.<ArtificialInformation>lambdaQuery().in(ArtificialInformation::getOutputId, ids));
        //
        List<Long> aids = artificialInformationList.stream().map(ArtificialInformation::getId).collect(Collectors.toList());
 
        backUtils.backDeleteArtificialInformationByIds(aids);
 
        artificialInformationMapper.delete(Wrappers.<ArtificialInformation>lambdaQuery().in(ArtificialInformation::getOutputId, ids));
        // 自动删除投入 (根据报工单删除对应投入,不再重新计算投入)
        autoDeleteInputV2(productMainIds, TransactionType.INPUT_DELETE.getValue());
        // for (ProductOutput productOutput : productOutputList) {
        //     autoDeleteInput(productOutput.getProductMainId(), productOutput.getProductQty());
        // }
        // 更新班次产量
        Set<Long> dutyRecordIds = productOutputStaffList.stream().map(ProductOutputStaff::getDutyRecordId).collect(Collectors.toSet());
        //刷新班次记录
        refreshDutyRecord(dutyRecordIds);
 
        return true;
    }
 
 
    @Override
    public boolean deleteProductOutputById(Long id) {
        ProductOutput productOutput = productOutputMapper.selectById(id);
        ProductMain productMain = baseMapper.selectById(productOutput.getProductMainId());
        if (ProductMainStateStringValues.SUBMITTED.equals(productMain.getState())) {
            throw new RuntimeException("报工记录已提交,无法修改");
        }
        Integer resultNum = resultMapper.selectCount(Wrappers.<Result>lambdaQuery().eq(Result::getSystemNo, productOutput.getSystemNo()).isNotNull(Result::getIsQualified));
        if (resultNum > 0) {
            throw new RuntimeException("报工已检测无法删除");
        }
        //工作台报工数据删除时需要先校验,是否已经进行了检测汇报
        //TODO
        List<ApplyPart> applyPartList = applyPartMapper.selectList(Wrappers.<ApplyPart>lambdaQuery()
                .eq(ApplyPart::getSystemNo, productOutput.getSystemNo()));
        if (!CollectionUtils.isEmpty(applyPartList)) {
            List<ApplyPart> applyPartListChecked = applyPartList.stream().filter(e -> null != e.getReportId()).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(applyPartListChecked)) {
                //没有进行检测汇报,先删除检测申请数据,再删除报工数据
                List<Long> applyIds = applyPartList.stream().map(ApplyPart::getApplyId).collect(Collectors.toList());
                List<Long> applyPartIds = applyPartList.stream().map(ApplyPart::getId).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(applyIds)) {
                    applyMapper.deleteBatchIds(applyIds);
                }
                if (!CollectionUtils.isEmpty(applyPartIds)) {
                    applyPartMapper.deleteBatchIds(applyPartIds);
                }
                //删除检测结果
                //resultMapper.deleteBySystemNo(productOutput.getSystemNo());
                resultMapper.deleteAllBySystemNo(productOutput.getSystemNo());//【2022-09-20】
            } else {
                throw new RuntimeException("已经检测汇报,请先删除检测汇报!");
            }
        }
        // 删除产出和人工记录
        List<ProductOutputStaff> productOutputStaffList = productOutputStaffMapper.selectList(Wrappers.<ProductOutputStaff>lambdaQuery().eq(ProductOutputStaff::getProductOutId, id));
        productOutputStaffMapper.delete(Wrappers.<ProductOutputStaff>lambdaQuery().eq(ProductOutputStaff::getProductOutId, id));
        //逻辑删除 产出表记录
        productOutputMapper.deleteById(id);
        List<ArtificialInformation> list = artificialInformationMapper.selectList(Wrappers.<ArtificialInformation>lambdaQuery().eq(ArtificialInformation::getOutputId, id));
        List<Long> ids = list.stream().map(ArtificialInformation::getId).collect(Collectors.toList());
        backUtils.backDeleteArtificialInformationByIds(ids);
        artificialInformationMapper.delete(Wrappers.<ArtificialInformation>lambdaQuery().eq(ArtificialInformation::getOutputId, id));
        // 自动删除投入
        autoDeleteInputV2(Collections.singletonList(productOutput.getProductMainId()), TransactionType.INPUT_DELETE.getValue());
        // 更新班次产量
        Set<Long> dutyRecordIds = productOutputStaffList.stream().map(ProductOutputStaff::getDutyRecordId).collect(Collectors.toSet());
        refreshDutyRecord(dutyRecordIds);
        return true;
    }
 
 
    /**
     * 自动删除对应数量的投入
     */
    public void autoDeleteInput(Long productMainId, BigDecimal productQty) {
        //删除自动投入
        ProductMain productMain = baseMapper.selectById(productMainId);
        // 1.根据工单查询投入产出比
        List<OperationTaskMaterial> operationTaskMaterialList = operationTaskMaterialMapper.selectList(Wrappers.<OperationTaskMaterial>query().lambda().
                eq(OperationTaskMaterial::getOperationTaskId, productMain.getOperationTaskId()));
        if (CollectionUtil.isNotEmpty(operationTaskMaterialList)) {
            // 2. 根据投入比去查询对应的投入数量
            for (OperationTaskMaterial operationTaskMaterial : operationTaskMaterialList) {
                // 投入总数量=投入比*产出数量
                BigDecimal summary = operationTaskMaterial.getQpa().multiply(productQty);
                List<ProductInputDTO> productInputList = productInputMapper.queryList(productMain.getId(), operationTaskMaterial.getPartId());
                if (CollectionUtil.isNotEmpty(productInputList)) {
                    for (ProductInputDTO productInputDTO : productInputList) {
                        String billNo = RandomStringUtils.random(10, true, true);
                        // 3. 判断投入的数量是否满足删除的数量
                        if (productInputDTO.getInputQuantity().compareTo(summary) == 1) {
                            productInputDTO.setInputQuantity(productInputDTO.getInputQuantity().add(summary.negate()));
                            productInputMapper.updateById(productInputDTO);
                            Stock stock = stockMapper.selectById(productInputDTO.getStockId());
                            //库存记录
                            stockUtils.createTransaction(stock.getStockQuantity(), summary,
                                    stock.getPartId(), stock.getLocationId(), stock.getPartBatchNo(), billNo,
                                    TransactionType.PRODUCT_FEEDING.getValue(), stock.getIfsBatchNo());
                            stock.setStockQuantity(stock.getStockQuantity().add(summary));
                            stock.setAvailableStockQuantity(stock.getAvailableStockQuantity().add(summary));
                            stockMapper.updateById(stock);
                            summary = BigDecimal.ZERO;
                        } else {
                            productInputMapper.deleteById(productInputDTO.getId());
                            Stock stock = stockMapper.selectById(productInputDTO.getStockId());
                            //库存记录
                            stockUtils.createTransaction(stock.getStockQuantity(), productInputDTO.getInputQuantity(),
                                    stock.getPartId(), stock.getLocationId(), stock.getPartBatchNo(), billNo,
                                    TransactionType.PRODUCT_FEEDING.getValue(), stock.getIfsBatchNo());
                            stock.setStockQuantity(stock.getStockQuantity().add(productInputDTO.getInputQuantity()));
                            stock.setAvailableStockQuantity(stock.getAvailableStockQuantity().add(productInputDTO.getInputQuantity()));
                            stockMapper.updateById(stock);
                            summary = summary.add(productInputDTO.getInputQuantity().negate());
                        }
                        if (summary.compareTo(BigDecimal.ZERO) != 1) {
                            break;
                        }
                    }
                }
            }
        }
    }
 
    private void autoDeleteInputV2(List<Long> productMainIdList, String billType) {
        List<ProductMain> productMains = this.listByIds(productMainIdList);
        if (CollectionUtil.isNotEmpty(productMains)) {
            for (ProductMain productMain : productMains) {
                List<ProductInput> productInputs = productInputMapper.selectList(Wrappers.<ProductInput>lambdaQuery().eq(ProductInput::getProductMainId, productMain.getId()));
                if (CollectionUtil.isNotEmpty(productInputs)) {
                    for (ProductInput productInput : productInputs) {
                        Stock stock = stockMapper.selectById(productInput.getStockId());
                        boolean retBool = SqlHelper.retBool(productInputMapper.deleteById(productInput.getId()));
                        if (retBool) {
                            String billNo = RandomStringUtils.random(10, true, true);
                            stockUtils.updateById(stock.getId(), productInput.getInputQuantity(),
                                    BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, billNo, billType);
                        }
                    }
                }
            }
        }
    }
 
    @Override
    public Boolean saveProductInput(ProductInputDTO productInputDTO) {
        String billNo = RandomStringUtils.random(10, true, true);
        if (productInputDTO.getInputQuantity() == null) {
            throw new RuntimeException("投入数量不能为空");
        }
        if (productInputDTO.getInputQuantity().compareTo(BigDecimal.ZERO) <= 0) {
            throw new RuntimeException("投入数量必须大于零");
        }
        ProductMain productMain = baseMapper.selectById(productInputDTO.getProductMainId());
        Boolean isChangeshift = judgeChangeshift(productMain.getId());
        if (isChangeshift || !ProductMainStateStringValues.DRAFT.equals(productMain.getState())) {
            throw new RuntimeException("报工记录不是草稿状态,无法修改");
        }
        Stock stock = stockMapper.selectById(productInputDTO.getStockId());
        // 查找所需物料信息
        String ifsLineItemNo = null;
        Part part = partService.getById(stock.getPartId());
        Map<Long, List<MoStructureComponent>> collect = getComponentList(productMain.getOperationTaskId());
        if (collect.get(stock.getPartId()) == null) {
            throw new RuntimeException("投入物料与所需物料不匹配,请确认");
        } else if (collect.get(stock.getPartId()).get(0).getIfsLineItemNo() != null) {
            ifsLineItemNo = collect.get(stock.getPartId()).get(0).getIfsLineItemNo();
        }
 
        // 增加是否为工序库存
        setOperationStockStatus(stock, part, productMain.getOperationTaskId());
//        ProductInput productInput = productInputMapper.selectOne(Wrappers.<ProductInput>lambdaQuery()
//                .eq(ProductInput::getProductMainId, productMain.getId()).eq(ProductInput::getPartId, stock.getPartId())
//                .eq(ProductInput::getPartBatchNo, stock.getPartBatchNo()).eq(ProductInput::getSystemNo, stock.getSystemNo())
//                .eq(ProductInput::getStockId, stock.getId()));
//        if (productInput != null) {
//            throw new RuntimeException("该物料投入已存在,直接修改投入数量,请勿重复投入");
//        }
        stockUtils.createTransaction(stock.getStockQuantity(), productInputDTO.getInputQuantity().negate(),
                stock.getPartId(), stock.getLocationId(), stock.getPartBatchNo(), billNo,
                TransactionType.PRODUCT_FEEDING.getValue(), stock.getIfsBatchNo());
        //扣除库存
        stock.setAvailableStockQuantity(stock.getAvailableStockQuantity().add(productInputDTO.getInputQuantity().negate()));
        stock.setStockQuantity(stock.getStockQuantity().add(productInputDTO.getInputQuantity().negate()));
        if (stock.getAvailableStockQuantity().compareTo(BigDecimal.ZERO) == -1) {
            throw new RuntimeException("投料剩余数量不足");
        }
        stockMapper.updateById(stock);
 
        BigDecimal feedingCost = productInputDTO.getInputQuantity();
        List<ProductInput> inputList = new ArrayList<>();
        // 判断是否存在相同的组件结构,如果是则生成多份投入
        List<MoStructureComponent> moStructureComponents = collect.get(stock.getPartId());
        if (moStructureComponents.size() > 1) {
            BigDecimal total = moStructureComponents.stream().map(MoStructureComponent::getQpa).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal inputQty = BigDecimal.ZERO;
            for (int i = 0; i < moStructureComponents.size(); i++) {
                ProductInput productInput = productInputMapper.selectOne(Wrappers.<ProductInput>lambdaQuery()
                        .eq(ProductInput::getProductMainId, productMain.getId())
                        .eq(ProductInput::getPartId, stock.getPartId())
                        .eq(ProductInput::getPartBatchNo, stock.getPartBatchNo())
                        .eq(ProductInput::getSystemNo, stock.getSystemNo())
                        .eq(ProductInput::getStockId, stock.getId())
                        .eq(ProductInput::getIfsLineItemNo, moStructureComponents.get(i).getIfsLineItemNo()));
                BigDecimal cost = feedingCost.multiply(moStructureComponents.get(i).getQpa()).divide(total, 2, RoundingMode.HALF_UP);
                // 如果是最后一个,则消耗剩余数量
                if (i == moStructureComponents.size() - 1) {
                    cost = feedingCost.subtract(inputQty);
                }
                inputQty = inputQty.add(cost);
                if (productInput == null) {
                    productInput = new ProductInput();
                    productInput.setInputQuantity(cost);
                    productInput.setIfsLineItemNo(moStructureComponents.get(i).getIfsLineItemNo());
                } else {
                    productInput.setInputQuantity(productInput.getInputQuantity().add(cost));
                }
                inputList.add(productInput);
            }
        } else {
            ProductInput productInput = productInputMapper.selectOne(Wrappers.<ProductInput>lambdaQuery()
                    .eq(ProductInput::getProductMainId, productMain.getId())
                    .eq(ProductInput::getPartId, stock.getPartId())
                    .eq(ProductInput::getPartBatchNo, stock.getPartBatchNo())
                    .eq(ProductInput::getSystemNo, stock.getSystemNo())
                    .eq(ProductInput::getStockId, stock.getId())
                    .eq(ProductInput::getIfsLineItemNo, moStructureComponents.get(0).getIfsLineItemNo()));
            if (productInput == null) {
                productInput = new ProductInput();
                productInput.setPartId(stock.getPartId());
                productInput.setPartBatchNo(stock.getPartBatchNo());
                productInput.setProductMainId(productInputDTO.getProductMainId());
                productInput.setInputQuantity(feedingCost);
                productInput.setIfsLineItemNo(moStructureComponents.get(0).getIfsLineItemNo());
                productInput.setSystemNo(stock.getSystemNo());
                productInput.setStockId(stock.getId());
                productInput.setIfsBatchNo(stock.getIfsBatchNo());
                productInput.setOperationStockStatus(stock.getOperationStockStatus());
                productInputMapper.insert(productInput);
            } else {
                productInput.setInputQuantity(feedingCost);
                productInputMapper.updateById(productInput);
            }
        }
        addOrUpdateProductInput(inputList, stock, productMain.getId());
//        productInput = new ProductInput();
//        productInput.setPartId(stock.getPartId());
//        productInput.setPartBatchNo(stock.getPartBatchNo());
//        productInput.setProductMainId(productInputDTO.getProductMainId());
//        productInput.setInputQuantity(productInputDTO.getInputQuantity());
//        productInput.setSystemNo(stock.getSystemNo());
//        productInput.setStockId(stock.getId());
//        productInput.setIfsBatchNo(stock.getIfsBatchNo());
//        productInput.setIfsLineItemNo(collect.get(stock.getPartId()).get(0).getIfsLineItemNo());
//        productInputMapper.insert(productInput);
//        return productInput.getId();
        return true;
    }
 
    @Override
    public Map<Long, List<MoStructureComponent>> getComponentList(Long operationTaskId) {
        // 查找所需物料信息
        OperationTask operationTask = operationTaskMapper.selectById(operationTaskId);
        if (operationTask == null) {
            throw new RuntimeException("未找到工序任务");
        }
        // 找到当前工艺工序节点
        MoRoutingOperation operation = moRoutingOperationMapper.findByOperationTaskId(operationTaskId);
        MoRoutingOperation beforeOperation = null;
        // 找到上一个工艺工序节点
        if (operation.getOperationOrder() > 1) {
            beforeOperation = moRoutingOperationMapper.selectOne(Wrappers.<MoRoutingOperation>lambdaQuery().eq(MoRoutingOperation::getMoId, operation.getMoId())
                    .eq(MoRoutingOperation::getOperationOrder, operation.getOperationOrder() - 1));
        }
 
        ManufacturingOrderDTO manufacturingOrderDTO = manufacturingOrderMapper.getOperationSupplyById(operationTaskId).get(0);
//        RoutingOperation routingOperation = routingOperationMapper.selectById(operationTask.getRoutingOperationId());
        // 根据车间订单id,产出零件id,消耗工序id,找到对应的产出组件 (暂时去除消耗工序,产出没有消耗工序)
        List<MoStructureComponent> componentList =
                moStructureComponentMapper.selectList(Wrappers.<MoStructureComponent>lambdaQuery()
                        .eq(MoStructureComponent::getPlanManufacturingOrderId, manufacturingOrderDTO.getId())
                        .eq(MoStructureComponent::getPartId, operationTask.getPartId())
                        .and(wrapper -> wrapper.ne(MoStructureComponent::getOperationId, operation.getOperationId())
                                .or(w -> w.isNull(MoStructureComponent::getOperationId))));
        List<Long> idList = componentList.stream().map(MoStructureComponent::getId).collect(Collectors.toList());
        // 根据产出组件id找出所需物料组件
        List<MoStructureComponent> needComponentList = moStructureComponentMapper.selectList(Wrappers.<MoStructureComponent>lambdaQuery()
                .in(MoStructureComponent::getParent, idList)
                .eq(MoStructureComponent::getOperationId, operation.getOperationId()));
        // 制造订单将上一道工序产出加入投入结构
        if (beforeOperation != null) {
            Long partId = beforeOperation.getPartId();
            if (needComponentList.stream().noneMatch(p -> p.getPartId().equals(partId))) {
                MoStructureComponent join = new MoStructureComponent();
                join.setPartId(beforeOperation.getPartId());
                join.setQpa(BigDecimal.valueOf(1L));
                needComponentList.add(join);
            }
            // 修理订单将当前工序产出加入投入结构
        }
        // 注释修理订单,将产出加入投入结构,用户会在组件表中维护进去
        //else if ("F".equals(manufacturingOrderDTO.getWorkshopTypeCode())) {
        //    MoStructureComponent join = new MoStructureComponent();
        //    join.setPartId(operation.getPartId());
        //    join.setQpa(BigDecimal.valueOf(1L));
        //    needComponentList.add(join);
        //}
        return needComponentList.stream().collect(Collectors.groupingBy(MoStructureComponent::getPartId));
    }
 
    @Override
    public IPage<List<StepDTO>> getProductStep(Page page, QueryWrapper<ProductStepDTO> gen) {
        return productStepMapper.getProductStep(page, gen);
    }
 
    @Override
    public Boolean judgeAddInput(ProductStepDTO productStepDTO) {
        Boolean type = false;
        String state = "true";
        String key = "FEEF_HINT";
        String productionState = "02submitted";
        if (state.equals(remoteParamService.getByKey(key, SecurityConstants.FROM_IN).getData())) {
            int count = productStepMapper.selectCount(Wrappers.<ProductStep>lambdaQuery().eq(ProductStep::getSystemNo, productStepDTO.getSystemNo()).eq(ProductStep::getStepId, productStepDTO.getStepId()));
            if (count > 0) {
                throw new RuntimeException(productStepDTO.getSystemNo() + "该产出已经经过了该工步的处理");
            }
            ProductOutput productOutput = productOutputMapper.selectOne(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getOutBatchNo, productStepDTO.getSystemNo()));
            if (productOutput != null) {
                ProductMain productMain = baseMapper.selectById(productOutput.getProductMainId());
                //if (productMain.getState().equals(productionState)) {
                //    throw new RuntimeException(productStepDTO.getSystemNo() + "对应的产出已提交不可以再修改");
                //}
                OperationJoinStep operationJoinStep = operationJoinStepMapper.getStepById(productStepDTO.getOperationTaskId(), productStepDTO.getStepId());
                //根据工单的id查询工序与工步的关联表
                List<OperationJoinStep> operationJoinStepList = operationJoinStepMapper.getOperationJoinStep(productStepDTO.getOperationTaskId());
 
                if (CollectionUtil.isNotEmpty(operationJoinStepList)) {
                    //判断这道工步的上一步工步是否已经处理
                    for (OperationJoinStep newOperationJoinStep : operationJoinStepList) {
                        if ((operationJoinStep.getSort() == (newOperationJoinStep.getSort() + 1)) && (operationJoinStep.getSort() != 1)) {
                            int newCount = productStepMapper.selectCount(Wrappers.<ProductStep>lambdaQuery().eq(ProductStep::getSystemNo, productStepDTO.getSystemNo()).eq(ProductStep::getStepId, newOperationJoinStep.getTechnologyStepId()));
                            if (newCount == 0) {
                                throw new RuntimeException(productStepDTO.getSystemNo() + "这道工步的上一个工步没有处理");
                            }
                        }
                    }
                    //判断是否为最后一道工步
                    // 跳线车间投入已在报工时处理,工步时无需处理
                    //if (operationJoinStep != null && operationJoinStep.getSort().equals(operationJoinStepList.get(operationJoinStepList.size() - 1).getSort())) {
                    //    // 3.1.根据工单查询投入产出比
                    //    List<OperationTaskMaterial> operationTaskMaterialList = operationTaskMaterialMapper.selectList(Wrappers.<OperationTaskMaterial>query().lambda().
                    //            eq(OperationTaskMaterial::getOperationTaskId, productStepDTO.getOperationTaskId()));
                    //    if (CollectionUtil.isNotEmpty(operationTaskMaterialList)) {
                    //        // 3.2 根据投入比去查询对应的投料数量
                    //        WorkstationLocation workstationLocation = workstationLocationMapper.selectOne(Wrappers.<WorkstationLocation>lambdaQuery()
                    //                .eq(WorkstationLocation::getWorkstationId, productMain.getWorkstationId())
                    //                .eq(WorkstationLocation::getLocationType, WorkstationLocation.FED_LOCATION));
                    //        if (workstationLocation == null) {
                    //            throw new RuntimeException("该机台未绑定机台已投料库位");
                    //        }
                    //        for (OperationTaskMaterial operationTaskMaterial : operationTaskMaterialList) {
                    //            //投入总数量=投入比*产出数量
                    //            BigDecimal summary = operationTaskMaterial.getQpa().multiply(BigDecimal.ONE);
                    //            List<Stock> stockList = stockMapper.selectList(Wrappers.<Stock>lambdaQuery()
                    //                    .eq(Stock::getPartId, operationTaskMaterial.getPartId())
                    //                    .eq(Stock::getLocationId, workstationLocation.getLocationId())
                    //                    .gt(Stock::getAvailableStockQuantity, BigDecimal.ZERO));
                    //            // 获取工单所需物料结构
                    //            Map<Long, List<MoStructureComponent>> collect = getComponentList(productMain.getOperationTaskId());
                    //            if (collect.get(operationTaskMaterial.getPartId()) == null) {
                    //                continue;
                    //            }
                    //            for (Stock stock : stockList) {
                    //                BigDecimal feedingCost;
                    //                //库存小于计算量
                    //                if (stock.getAvailableStockQuantity().compareTo(summary) == -1) {
                    //                    feedingCost = stock.getAvailableStockQuantity();
                    //                } else {
                    //                    feedingCost = summary;
                    //                }
                    //
                    //                // 总需消耗减去已消耗
                    //                summary = summary.subtract(feedingCost);
                    //                if (summary.compareTo(BigDecimal.ZERO) == 0) {
                    //                    break;
                    //                }
                    //            }
                    //
                    //            // 料不足,不允许新增产出
                    //            if (summary.compareTo(BigDecimal.ZERO) == 1) {
                    //                type = true;
                    //                break;
                    //            }
                    //        }
                    //    }
                    //}
                }
            } else {
                throw new RuntimeException(productStepDTO.getSystemNo() + "不存在该产出,请核对SN码");
            }
        }
        return type;
    }
 
    @Override
    public List<ManufacturingOrderSnGenerateDTO> getGenerateSN(Long operationTaskId) {
        List<ManufacturingOrderSnGenerateDTO> result = new ArrayList<>();
        List<ManufacturingOrderDTO> orders = manufacturingOrderMapper.getOperationSupplyById(operationTaskId);
        if (orders.size() > 0) {
            // 根据理论消耗表找出成品车间订单
            MasterProductionScheduleTheoryQuantity theoryQuantity = theoryQuantityMapper.selectOne(
                    Wrappers.<MasterProductionScheduleTheoryQuantity>lambdaQuery()
                            .eq(MasterProductionScheduleTheoryQuantity::getMid, orders.get(0).getMpsId())
                            .eq(MasterProductionScheduleTheoryQuantity::getIsMaster, true));
            if (theoryQuantity != null) {
                // 找出所有成品车间订单
                List<ManufacturingOrder> manufacturingOrders = manufacturingOrderMapper.selectList(
                        Wrappers.<ManufacturingOrder>lambdaQuery()
                                .eq(ManufacturingOrder::getScheduleTheoryQuantityId, theoryQuantity.getId()));
                if (manufacturingOrders.size() > 0) {
                    for (ManufacturingOrder manufacturingOrder : manufacturingOrders) {
                        List<ManufacturingOrderSnGenerateDTO> generateList = manufacturingOrderSnGenerateMapper.selectListByMoId(manufacturingOrder.getId());
                        if (!generateList.isEmpty()) {
                            // 找出父级递归
                            for (ManufacturingOrderSnGenerateDTO generateDTO : generateList) {
                                if (generateDTO.getParentId() == null) {
                                    recursionSN(result, generateList, generateDTO);
                                }
                            }
                        }
                    }
                }
            }
        }
        return result;
    }
 
    private void recursionSN(List<ManufacturingOrderSnGenerateDTO> result, List<ManufacturingOrderSnGenerateDTO> generateList, ManufacturingOrderSnGenerateDTO generateDTO) {
        if (generateDTO.getParentId() == null) {
            result.add(generateDTO);
        }
        for (ManufacturingOrderSnGenerateDTO dto : generateList) {
            if (dto.getParentId() != null) {
                if (dto.getParentId().equals(generateDTO.getId())) {
                    if (generateDTO.getChildren() != null) {
                        generateDTO.getChildren().add(dto);
                    } else {
                        generateDTO.setChildren(new ArrayList<>());
                        generateDTO.getChildren().add(dto);
                    }
                    recursionSN(result, generateList, dto);
                }
            }
        }
    }
 
    @Override
    public List<ProductOutPutData> exportList(Long operationTaskId, Long workstationId) {
        return productOutputMapper.exportList(operationTaskId, workstationId);
    }
 
    private void addOrUpdateProductInput(List<ProductInput> productInputs, Stock stock, Long mainId) {
        //同一个零件同一批次存在记录,则在上面累加投入,否则新建一条记录
        for (ProductInput productInput : productInputs) {
            if (productInput.getId() != null) {
                productInputMapper.updateById(productInput);
            } else {
                productInput.setPartId(stock.getPartId());
                productInput.setPartBatchNo(stock.getPartBatchNo());
                productInput.setProductMainId(mainId);
                productInput.setSystemNo(stock.getSystemNo());
                productInput.setStockId(stock.getId());
                productInput.setIfsBatchNo(stock.getIfsBatchNo());
                productInput.setOperationStockStatus(stock.getOperationStockStatus());
                productInputMapper.insert(productInput);
            }
        }
    }
 
    @Override
    public boolean updateProductInput(ProductInput productInput) {
        String billNo = RandomStringUtils.random(10, true, true);
        if (productInput.getInputQuantity() == null) {
            throw new RuntimeException("投入数量不能为空");
        }
        if (productInput.getInputQuantity().compareTo(BigDecimal.ZERO) <= 0) {
            throw new RuntimeException("投入数量必须大于零");
        }
        ProductInput productInputOriginal = productInputMapper.selectById(productInput.getId());
        ProductMain productMain = baseMapper.selectById(productInputOriginal.getProductMainId());
        Boolean isChangeshift = judgeChangeshift(productMain.getId());
        if (isChangeshift || !ProductMainStateStringValues.DRAFT.equals(productMain.getState())) {
            throw new RuntimeException("报工记录不是草稿状态,无法修改");
        }
        productInputMapper.updateById(productInput);
        BigDecimal changeQuantity = productInputOriginal.getInputQuantity().subtract(productInput.getInputQuantity());
        Stock stock = stockMapper.selectById(productInputOriginal.getStockId());
        stockUtils.createTransaction(stock.getStockQuantity(), changeQuantity,
                stock.getPartId(), stock.getLocationId(), stock.getPartBatchNo(), billNo,
                TransactionType.PRODUCT_FEEDING.getValue(), stock.getIfsBatchNo());
        stock.setStockQuantity(stock.getStockQuantity().add(changeQuantity));
        stock.setAvailableStockQuantity(stock.getAvailableStockQuantity().add(changeQuantity));
        if (stock.getAvailableStockQuantity().compareTo(BigDecimal.ZERO) == -1) {
            throw new RuntimeException("投料剩余数量不足");
        }
        stockMapper.updateById(stock);
        return true;
    }
 
    @Override
    public boolean deleteProductInputById(Long id) {
        String billNo = RandomStringUtils.random(10, true, true);
        ProductInput productInput = productInputMapper.selectById(id);
        if (productInput != null) {
            ProductMain productMain = baseMapper.selectById(productInput.getProductMainId());
            List<OperationTaskMaterialDTO> operationTaskMaterials = operationTaskMaterialMapper.getMaterial(Wrappers.<OperationTaskMaterialDTO>lambdaQuery()
                    .eq(OperationTaskMaterialDTO::getOperationTaskId, productMain.getOperationTaskId()));
            if (operationTaskMaterials == null) {
                throw new RuntimeException("工单所需物料为空");
            }
            List<ProductInputDTO> ProductInputDTOList = productInputMapper.queryListByDelete(productInput.getProductMainId(), productInput.getId());
            if (CollectionUtil.isEmpty(ProductInputDTOList)) {
                throw new RuntimeException("当前删除的物料是最后一条");
            }
            List<String> partNoList = ProductInputDTOList.stream().map(ProductInputDTO::getPartNo).collect(Collectors.toList());
            Set<String> operationPartNoList = operationTaskMaterials.stream().map(OperationTaskMaterialDTO::getPartNo).collect(Collectors.toSet());
            if (!partNoList.containsAll(operationPartNoList)) {
                throw new RuntimeException("当前删除的物料是最后一条");
            }
            Boolean isChangeshift = judgeChangeshift(productMain.getId());
            if (isChangeshift || !ProductMainStateStringValues.DRAFT.equals(productMain.getState())) {
                throw new RuntimeException("报工记录不是草稿状态,无法修改");
            }
            Stock stock = stockMapper.selectById(productInput.getStockId());
            stockUtils.createTransaction(stock.getStockQuantity(), productInput.getInputQuantity(),
                    stock.getPartId(), stock.getLocationId(), stock.getPartBatchNo(), billNo,
                    TransactionType.PRODUCT_CANCEL.getValue(), stock.getIfsBatchNo());
            stock.setAvailableStockQuantity(stock.getAvailableStockQuantity().add(productInput.getInputQuantity()));
            stock.setStockQuantity(stock.getStockQuantity().add(productInput.getInputQuantity()));
            stockMapper.updateById(stock);
            productInputMapper.deleteById(id);
        }
        return true;
    }
 
    @Override
    public IPage getOutputList(Page page, QueryWrapper<ProductOutputDTO> gen, ProductOutputDTO productOutputDTO) {
        ProductOutputDTO searchProductOutputDTO = new ProductOutputDTO();
        BeanUtils.copyProperties(productOutputDTO, searchProductOutputDTO);
        productOutputDTO.setStartTime(null);
        productOutputDTO.setEndTime(null);
        IPage<ProductOutputDTO> outputList = productOutputMapper.getOutputList(page, QueryWrapperUtil.gen(productOutputDTO), searchProductOutputDTO);
        if (!outputList.getRecords().isEmpty()) {
            boolean orderBy = productOutputDTO.getCriteria().contains("orderBy");
            if (orderBy) {
                JSONObject json = JSONObject.parseObject(productOutputDTO.getCriteria());
                json.remove("orderBy");
                productOutputDTO.setCriteria(json.toJSONString());
            }
            BigDecimal sum = productOutputMapper.getSumProductQty(QueryWrapperUtil.gen(productOutputDTO), searchProductOutputDTO);
            ProductOutputDTO out = new ProductOutputDTO();
            out.setStaffName("");
            out.setProductQty(sum);
            outputList.getRecords().add(out);
        }
        return outputList;
    }
 
 
    @Override
    public List<ProductOutputDTO> getOutputListByScan(ProductOutputDTO productOutputDTO) {
        List<ProductOutputDTO> outputList = productOutputMapper.getOutputListByScan(productOutputDTO);
        return outputList;
    }
 
    @Override
    public List<Step> getStep(Long id) {
        return stepMapper.getStep(id);
    }
 
    @Override
    public List<StepDTO> getProductStep(Long id) {
        return stepMapper.getProductStep(id);
    }
 
    @Override
    public List<StepDTO> getProductStepBySn(Long id, String sn) {
        return stepMapper.getProductStepBySn(id, sn);
    }
 
    @Override
    public ProductStepDTO getAllProductStep(Long id) {
        ProductStepDTO productStepDTO = productStepMapper.getById(id);
        List<StepDTO> stepDTOList = stepMapper.getAllProductStep(id);
        productStepDTO.setStepDTOList(stepDTOList);
        return productStepDTO;
    }
 
    @Override
    public List<StepDTO> addOrUpdateStep(ProductStepDTO productStepDTO) {
        Boolean lock = redisHelper.lock(productStepDTO.getSystemNo() + "-" + productStepDTO.getStepId());
        if (BooleanUtil.isFalse(lock)) {
            throw new RuntimeException("已有相同工单工步在执行,稍后刷新页面再试");
        }
        try {
            int count = productStepMapper.selectCount(Wrappers.<ProductStep>lambdaQuery().eq(ProductStep::getSystemNo, productStepDTO.getSystemNo()).eq(ProductStep::getStepId, productStepDTO.getStepId()));
            if (count > 0) {
                throw new RuntimeException(productStepDTO.getSystemNo() + "该产出已经经过了该工步的处理");
            }
            ProductOutput productOutput = productOutputMapper.selectOne(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getOutBatchNo, productStepDTO.getSystemNo()));
            ProductMain productMain = baseMapper.selectById(productOutput.getProductMainId());
            if (productMain.getOperationTaskId().compareTo(productStepDTO.getOperationTaskId()) != 0) {
                throw new RuntimeException(productStepDTO.getSystemNo() + "该产出不属于当前工单,请重新确认");
            }
            DutyRecord dutyRecord = dutyRecordMapper.selectOne(Wrappers.<DutyRecord>lambdaQuery().eq(DutyRecord::getDutyNo, productStepDTO.getDutyNo()));
            JoinStepTemplate joinStepTemplate = joinStepTemplateMapper.selectOne(Wrappers.<JoinStepTemplate>lambdaQuery().eq(JoinStepTemplate::getStepId, productStepDTO.getStepId()));
            if (joinStepTemplate != null) {
                List<OperationTaskRecordDTO> operationTaskRecordDTOList = operationTaskRecordMapper.getAllTemplateRecord(productStepDTO.getOperationTaskId(), joinStepTemplate.getTemplateId(), dutyRecord.getId());
                if (CollectionUtil.isEmpty(operationTaskRecordDTOList)) {
                    throw new RuntimeException(productStepDTO.getSystemNo() + "该工步对应的生产记录没有填写,请填写后继续操作");
                }
            }
            ProductStep productStep = new ProductStep();
            productStep.setOperationTaskId(productStepDTO.getOperationTaskId());
            productStep.setStepId(productStepDTO.getStepId());
            productStep.setProductMainId(productOutput.getProductMainId());
            productStep.setSystemNo(productStepDTO.getSystemNo());
            if (productOutput != null) {
                productStep.setStepBatchNo(productOutput.getOutBatchNo());
            }
            productStepMapper.insert(productStep);
            for (ProductStepStaff newProductStepStaff : productStepDTO.getStepStaffList()) {
                ProductStepStaff productStepStaff = new ProductStepStaff();
                productStepStaff.setStaffId(newProductStepStaff.getStaffId());
                productStepStaff.setProductStepId(productStep.getId());
                productStepStaffMapper.insert(productStepStaff);
            }
            //根据工单的id和工步的id查询工序与工步的关联表
            // 跳线报工单提交不在最后一个工步处理,已提前提交处理
            //OperationJoinStep operationJoinStep = operationJoinStepMapper.getStepById(productStepDTO.getOperationTaskId(), productStepDTO.getStepId());
            ////根据工单的id查询工序与工步的关联表
            //List<OperationJoinStep> operationJoinStepList = operationJoinStepMapper.getOperationJoinStep(productStepDTO.getOperationTaskId());
            //if (CollectionUtil.isNotEmpty(operationJoinStepList)) {
            //    if (operationJoinStep != null && operationJoinStep.getSort().equals(operationJoinStepList.get(operationJoinStepList.size() - 1).getSort())) {
            //        if (productOutput != null) {
            //            productMain.setState(ProductMainStateStringValues.PROCESSING);
            //            updateById(productMain);
            //            productOutput.setProductQty(BigDecimal.ONE);
            //            productOutputMapper.updateById(productOutput);
            //            List<Long> ids = new ArrayList<>();
            //            ids.add(productOutput.getProductMainId());
            //            if (productMain != null) {
            //                autoAddInput(productStepDTO.getOperationTaskId(), productMain.getWorkstationId(), productMain.getId(), productOutput.getProductQty());
            //            }
            //            batchChange(ids, "SUBMIT");
            //        }
            //    }
            //}
            //查询工装模具,如果存在工步对应的模具就新增使用记录
            ThreadUtil.execute(() -> addMouldUseOrder(productStepDTO, productMain.getProductNo(), productOutput.getOutBatchNo()));
            return productStepMapper.getStepById(productStep.getOperationTaskId(), productStep.getStepId(), productMain.getId());
        } finally {
            redisHelper.delLock(productStepDTO.getSystemNo() + "-" + productStepDTO.getStepId());
        }
    }
 
    public synchronized void addMouldUseOrder(ProductStepDTO productStepDTO, String productNo, String outBatchNo) {
        List<MouldRegister> mouldRegisterList = mouldRegisterMapper.selectList(Wrappers.<MouldRegister>lambdaQuery().eq(MouldRegister::getWorkstationId, productStepDTO.getWorkstationId()).eq(MouldRegister::getStepId, productStepDTO.getStepId()));
        if (CollectionUtil.isNotEmpty(mouldRegisterList)) {
            for (MouldRegister mouldRegister : mouldRegisterList) {
                MouldUseRecord mouldUseRecord = new MouldUseRecord();
                mouldUseRecord.setMouldRegisterId(mouldRegister.getId());
                mouldUseRecord.setBatchNo(outBatchNo);
                mouldUseRecord.setOperationTaskId(productStepDTO.getOperationTaskId());
                mouldUseRecord.setOutput(BigDecimal.ONE);
                mouldUseRecord.setProductNo(productNo);
                mouldUseRecord.setUsageAmount(BigDecimal.ONE.multiply(mouldRegister.getLifeConversionFactor()));
                mouldUseRecord.setStatus("未提交");
                mouldUseRecord.setWorkstationId(productStepDTO.getWorkstationId());
                mouldUseRecordMapper.insert(mouldUseRecord);
            }
        }
    }
 
    @Override
    public boolean deleteProductStep(Long id) {
        ProductStep productStep = productStepMapper.selectById(id);
        if (productStep != null) {
            //根据工单的id和工步的id查询工序与工步的关联表
            OperationJoinStep operationJoinStep = operationJoinStepMapper.getStepById(productStep.getOperationTaskId(), productStep.getStepId());
            //根据工单的id查询工序与工步的关联表
            List<OperationJoinStep> operationJoinStepList = operationJoinStepMapper.getOperationJoinStep(productStep.getOperationTaskId());
            ProductOutput productOutput = productOutputMapper.selectOne(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getSystemNo, productStep.getSystemNo()));
            if (CollectionUtil.isNotEmpty(operationJoinStepList)) {
                //判断下一道工步是否已经执行,如果执行了当前工步不可删除
                for (OperationJoinStep newOperationJoinStep : operationJoinStepList) {
                    if (newOperationJoinStep.getSort() == operationJoinStep.getSort() + 1) {
                        ProductStep nweProductStep = productStepMapper.selectOne(Wrappers.<ProductStep>lambdaQuery().eq(ProductStep::getSystemNo, productStep.getSystemNo()).eq(ProductStep::getStepId, newOperationJoinStep.getTechnologyStepId()));
                        if (nweProductStep != null) {
                            throw new RuntimeException(productStep.getSystemNo() + "的下一道工步已经处理,请先删除下一道工步");
                        }
                    }
                }
                //判断是否为最后一道工步
                if (operationJoinStep != null && operationJoinStep.getSort().equals(operationJoinStepList.get(operationJoinStepList.size() - 1).getSort())) {
                    if (productOutput != null) {
                        List<Long> ids = new ArrayList<>();
                        ids.add(productOutput.getId());
                        changeProductOutPutState(ids, "REVOKE");
                        productOutput.setProductQty(BigDecimal.ZERO);
                        productOutput.setState(ProductOutStateStringValues.DRAFT);
                        productOutputMapper.updateById(productOutput);
                        autoDeleteInputV2(Collections.singletonList(productOutput.getProductMainId()), TransactionType.INPUT_DELETE.getValue());
                    }
                }
            }
        }
        productStepMapper.deleteById(id);
        productStepStaffMapper.delete(Wrappers.<ProductStepStaff>lambdaQuery().eq(ProductStepStaff::getProductStepId, id));
        //删除工步的同时,更改对应的模具使用记录
        ThreadUtil.execute(() -> deleteMouldUseOrder(productStep));
        return true;
    }
 
    @Override
    public IPage<List<ProductOutputDTO>> getProductOut(Page page, QueryWrapper<ProductOutputDTO> gen, Long id) {
        return productOutputMapper.getProductOut(page, gen, id);
    }
 
    @Override
    public R<Boolean> changeProductOutPutState(List<Long> ids, String event) {
        if (CollectionUtil.isNotEmpty(ids)) {
            for (Long id : ids) {
                ProductOutput productOutput = productOutputMapper.selectById(id);
                Message<ProductOutEvents> message = MessageBuilder.withPayload(ProductOutEvents.valueOf(event)).setHeader("productOutput", productOutput).build();
                StateMachineHandler handler = new StateMachineHandler(productOutStateMachineFactory, productOutPersister, ProductOutStateMachineConfig.MACHINE_ID, productOutput);
                StateResult res = handler.sendEvent(message, productOutput.getId());
                if (!res.isSuccess()) {
                    return R.failed(res.getMsg());
                }
            }
        }
        return R.ok();
    }
 
    /**
     * 刷新班次产量字段
     *
     * @param dutyRecordIds
     */
    private void refreshDutyRecord(Set<Long> dutyRecordIds) {
        if (CollectionUtil.isNotEmpty(dutyRecordIds)) {
            dutyRecordIds.stream().forEach(dutyRecordId -> {
                dutyRecordMapper.refreshDutyOutputById(dutyRecordId);
            });
        }
    }
 
    private void setOperationStockStatus(Stock stock, Part part, Long operationTaskId) {
        if (stock.getOperationStockStatus() == null) {
            // 原材料(通过查零件基础表的【零件类型】为‘已采购(原材料)’且【计划方法】为‘A’),【是否工序库存】字段默认为‘否’
            if (part.getMaterialType().equals("3") && part.getPlanningMethod().equals("A")) {
                stock.setOperationStockStatus(false);
            }
        }
    }
 
    public synchronized void deleteMouldUseOrder(ProductStep productStep) {
        ProductMain productMain = baseMapper.selectById(productStep.getProductMainId());
        List<MouldRegister> mouldRegisterList = mouldRegisterMapper.selectList(Wrappers.<MouldRegister>lambdaQuery().eq(MouldRegister::getStepId, productStep.getStepId()).eq(MouldRegister::getWorkstationId, productMain.getWorkstationId()));
        if (CollectionUtil.isNotEmpty(mouldRegisterList)) {
            for (MouldRegister mouldRegister : mouldRegisterList) {
                MouldUseRecord mouldUseRecord = mouldUseRecordMapper.selectOne(Wrappers.<MouldUseRecord>lambdaQuery().eq(MouldUseRecord::getProductNo, productMain.getProductNo()).eq(MouldUseRecord::getMouldRegisterId, mouldRegister.getId()));
                if (mouldUseRecord != null) {
                    BigDecimal number = mouldUseRecord.getUsageAmount();
                    mouldUseRecord.setUsageAmount(number.subtract(BigDecimal.ONE.multiply(mouldRegister.getLifeConversionFactor())));
                    mouldUseRecordMapper.updateById(mouldUseRecord);
                }
            }
        }
    }
 
 
    @Override
    public List<String> getGenerateSnByCustomerOrderNo(String customerOrderNo) {
        return manufacturingOrderSnGenerateMapper.getProductSnsByCustomerOrderNo("%" + customerOrderNo + "%");
    }
 
    @Override
    public String getSNByTaskId(Long taskId) {
        return manufacturingOrderMapper.getSNByTaskId(taskId);
    }
 
    @Override
    public long getOutputByBatchNo(String outBatchNo) {
        return productOutputMapper.selectCount(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getOutBatchNo,
                outBatchNo));
    }
 
    @Override
    public Boolean batchLabelPrintTimes(List<Long> ids) {
        updateLabelPrintTimes(ids);
        return true;
    }
 
    @Override
    public Boolean checkBatchLabelPrint(List<Long> ids, Boolean isSubmit) {
        List<ProductOutput> outputList = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery()
                .in(ProductOutput::getId, ids));
        for (ProductOutput productOutput : outputList) {
            if (productOutput.getPrintNum() == null) {
                productOutput.setPrintNum(1L);
            } else {
                return false;
            }
        }
        if (!isSubmit) {
            productOutputService.updateBatchById(outputList);
        }
        return true;
    }
 
 
    @Override
    public R checkLabelPrintPassword(String password, List<Long> ids, Boolean isSubmit) {
        String res = remoteParamService.getByKey(WORKBENCH_LABEL_REPRINT, SecurityConstants.FROM_IN).getData();
 
        if (null == password || password.length() == 0) {
            return R.failed("密码不可为空");
        }
 
        if (null == res) {
            return R.failed("密码验证失败");
        }
 
        if (!res.equals(password)) {
            return R.failed("密码错误");
        }
 
        //密码校验通过后,更新打印次数
        if (!isSubmit) {
            updateLabelPrintTimes(ids);
        }
        return R.ok();
    }
 
    @Override
    public R updatePrintNum(List<Long> ids) {
        updateLabelPrintTimes(ids);
        return R.ok();
    }
 
    @Override
    public List<ProductOutputLabelDTO> batchLabelPrint(List<Long> ids) {
        return productOutputMapper.batchLabelPrint(ids);
    }
 
    @Override
    public List<String> getPartNamesByOrderNo(String customerOrderNo) {
        return customerOrderMapper.getPartNamesByOrderNo(customerOrderNo);
    }
 
    @Override
    public List<String> getProductSnByCustomerNoAndPartName(String customerOrderNo, String partName) {
        return manufacturingOrderSnGenerateMapper.getProductSnByCustomerNoAndPartName(customerOrderNo, partName);
    }
 
    @Override
    public R validateOverProduction(List<ProductMainDTO> productMainDTOList) {
        BigDecimal outQty = BigDecimal.ZERO;
        Long taskId = productMainDTOList.get(0).getOperationTaskId();
        List<ProductOutputDTO> oriOutputList =
                productOutputMapper.selectByTaskId(taskId);
        List<ProductMainDTO> mains = new ArrayList<>();
        Set<Long> oriMainIdSet = new HashSet<>();
        if (productMainDTOList.get(0).getId() != null) {
            mains = productMainDTOList;
            oriMainIdSet = mains.stream().map(ProductMain::getId).collect(Collectors.toSet());
        } else {
            for (ProductMainDTO productMainDTO : productMainDTOList) {
                for (int i = 0; i < productMainDTO.getDiscsNumber(); i++) {
                    ProductMainDTO productMain = new ProductMainDTO();
                    productMain.setOperationTaskId(productMainDTO.getOperationTaskId());
                    productMain.setWorkstationId(productMainDTO.getWorkstationId());
                    productMain.setProductOutputList(productMainDTO.getProductOutputList());
                    productMain.setIsChangeShift(productMainDTO.getIsChangeShift());
                    productMain.setState(ProductMainStateStringValues.DRAFT);
                    mains.add(productMain);
                }
            }
        }
 
        // 排除更新数据,汇总原有产出数量
        Set<Long> finalOriMainIdSet = oriMainIdSet;
        BigDecimal oriProductQty =
                oriOutputList.stream().filter(o -> !finalOriMainIdSet.contains(o.getProductMainId())).map(ProductOutput::getProductQty).reduce(BigDecimal.ZERO, BigDecimal::add);
        for (ProductMainDTO productMainDTO : mains) {
            outQty =
                    outQty.add(productMainDTO.getProductOutputList().stream().map(p -> p.getEndMeterMark().subtract(p.getStartMeterMark()))
                            .reduce(BigDecimal.ZERO, BigDecimal::add));
        }
 
        OperationTask operationTask = operationTaskMapper.selectById(taskId);
        BigDecimal outputQty = operationTask.getCompletedQuantity().add(outQty).add(oriProductQty);
        if (outputQty.compareTo(operationTask.getPlannedQuantity().multiply(new BigDecimal("0.05").add(BigDecimal.ONE))) >= 0) {
            return R.ok(ValidateOverProductionDTO.builder().success(Boolean.FALSE)
                    .message("最多可报工" + operationTask.getPlannedQuantity().multiply(new BigDecimal("0.05").add(BigDecimal.ONE)) + ",当前报工总量" + outputQty + ",已超报,请班组长输入密码确认").build());
        }
        return R.ok(ValidateOverProductionDTO.builder().success(Boolean.TRUE).build());
    }
 
 
    @Override
    public R checkRawPart(List<String> partNoList) {
        String checkInputType = remoteParamService.getByKey(Constant.CHECK_INPUT_TYPE, SecurityConstants.FROM_IN).getData();
        if (StringUtils.equals(checkInputType, "false")) {
            return R.ok(CheckRawPartDTO.builder().success(Boolean.TRUE).build());
        }
        if (CollectionUtil.isEmpty(partNoList)) {
            throw new RuntimeException("零件号不能为空");
        }
        Set<String> noMaterialpartNoList = new HashSet<>();
        for (String partNo : partNoList) {
            Part part = partService.getOne(Wrappers.<Part>lambdaQuery()
                    .eq(Part::getPartNo, partNo)
                    .eq(Part::getMaterialType, "3"));
            if (part == null) {
                noMaterialpartNoList.add(partNo);
            }
        }
        if (CollectionUtil.isEmpty(noMaterialpartNoList)) {
            return R.ok(CheckRawPartDTO.builder().success(Boolean.TRUE).build());
        } else {
            return R.ok(CheckRawPartDTO.builder().success(Boolean.FALSE).message("以下零件号不是原材料" + noMaterialpartNoList.toString()).build());
        }
 
 
    }
 
    /**
     * 校验当前报工投料是否充足
     *
     * @param productMainDTOList
     * @return
     */
    @Override
    public R validateOverFeed(List<ProductMainDTO> productMainDTOList) {
        //校验要不要进行投料判断
        String checkInputLimit = remoteParamService.getByKey(Constant.WORKBEHCH_PR_BP_CIQ, SecurityConstants.FROM_IN).getData();
        if (StringUtils.equals(checkInputLimit, "false")) {
            return R.ok(ValidateOverFeedResultDTO.builder().success(Boolean.TRUE).build());
        }
        //投料判断
        List<ProductMainDTO> mains = new ArrayList<>();
        Set<Long> oriMainIdSet = new HashSet<>();
        BigDecimal oriProductQty = BigDecimal.ZERO;
        if (productMainDTOList.get(0).getId() != null) {
            mains = productMainDTOList;
            oriMainIdSet = mains.stream().map(ProductMain::getId).collect(Collectors.toSet());
            List<ProductOutput> oriOutputList =
                    productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().in(ProductOutput::getProductMainId,
                            oriMainIdSet));
            oriProductQty =
                    oriOutputList.stream().map(p -> BigDecimalUtils.getBigDecimalValue(p.getProductQty())
                            .add(BigDecimalUtils.getBigDecimalValue(p.getScrapQty()))).reduce(BigDecimal.ZERO,
                            BigDecimal::add);
        } else {
            for (ProductMainDTO productMainDTO : productMainDTOList) {
                for (int i = 0; i < productMainDTO.getDiscsNumber(); i++) {
                    ProductMainDTO productMain = new ProductMainDTO();
                    productMain.setOperationTaskId(productMainDTO.getOperationTaskId());
                    productMain.setWorkstationId(productMainDTO.getWorkstationId());
                    productMain.setProductOutputList(productMainDTO.getProductOutputList());
                    productMain.setIsChangeShift(productMainDTO.getIsChangeShift());
                    productMain.setState(ProductMainStateStringValues.DRAFT);
                    mains.add(productMain);
                }
            }
        }
        BigDecimal productQty = BigDecimal.ZERO;
        for (ProductMainDTO mainDTO : mains) {
            productQty =
                    productQty.add(mainDTO.getProductOutputList().stream().map(p -> BigDecimalUtils.getBigDecimalValue(p.getEndMeterMark())
                            .subtract(BigDecimalUtils.getBigDecimalValue(p.getStartMeterMark()))
                            .add(BigDecimalUtils.getBigDecimalValue(p.getScrapQty())))
                            .reduce(BigDecimal.ZERO, BigDecimal::add));
        }
        Long operationTaskId = mains.get(0).getOperationTaskId();
        Long workStationId = mains.get(0).getWorkstationId();
        Step step = stepMapper.getFirstStep(operationTaskId);
        if (step != null) {
            return R.ok(ValidateOverFeedResultDTO.builder().success(Boolean.TRUE).build());
        }
        String taskMoNo = operationTaskMapper.getTaskMoNo(productMainDTOList.get(0).getOperationTaskId());
        // 根据工单找到对应车间订单的第一道工序id
        Long firstOperationId =
                operationTaskMapper.getFirstOperationId(productMainDTOList.get(0).getOperationTaskId());
        // 找到当前工单对应的工序id
        Long operationId = operationTaskMapper.getOperationIdByTaskId(productMainDTOList.get(0).getOperationTaskId());
        // 根据工单查询投入产出比
        List<OperationTaskMaterial> operationTaskMaterialList = operationTaskMaterialMapper.selectList(Wrappers.<OperationTaskMaterial>query().lambda().
                eq(OperationTaskMaterial::getOperationTaskId, operationTaskId));
 
        // 按照partId分组
        Map<Long, OperationTaskMaterial> taskMaterialMap =
                operationTaskMaterialList.stream().collect(Collectors.toMap(OperationTaskMaterial::getPartId,
                        taskMaterial -> taskMaterial, (v1, v2) -> v2));
 
        if (CollectionUtil.isEmpty(operationTaskMaterialList)) {
            return R.ok(ValidateOverFeedResultDTO.builder().success(Boolean.TRUE).build());
        }
        WorkstationLocation workstationLocation =
                workstationLocationMapper.selectOne(Wrappers.<WorkstationLocation>lambdaQuery()
                        .eq(WorkstationLocation::getWorkstationId, workStationId)
                        .eq(WorkstationLocation::getLocationType, WorkstationLocation.FED_LOCATION));
        if (workstationLocation == null) {
            throw new RuntimeException("该机台未绑定机台已投料库位");
        }
        // 所需所有零件id
        Set<Long> partIdSet =
                operationTaskMaterialList.stream().filter(o -> o.getPartId() != null).map(OperationTaskMaterial::getPartId).collect(Collectors.toSet());
        List<Stock> stockList = stockMapper.selectList(Wrappers.<Stock>lambdaQuery()
                .in(Stock::getPartId, partIdSet)
                .eq(Stock::getLocationId, workstationLocation.getLocationId())
                .gt(Stock::getAvailableStockQuantity, BigDecimal.ZERO));
        // 获取所有零件
        List<Part> partList = partService.list(Wrappers.<Part>lambdaQuery().in(Part::getId, partIdSet));
        Map<Long, Part> partMap = partList.stream().collect(Collectors.toMap(Part::getId, part -> part,
                (v1, v2) -> v2));
        List<Stock> availableStockList = new ArrayList<>();
        for (Stock stock : stockList) {
            Part part = partMap.get(stock.getPartId());
            setOperationStockStatus(stock, part, operationTaskId);
            if (BooleanUtil.isTrue(stock.getOperationStockStatus())) {
                String stockMoNo = stockMapper.getStockMoNo(stock.getId());
                if (!StringUtils.equals(stockMoNo, taskMoNo) && !firstOperationId.equals(operationId)) {
                    continue;
                }
            }
            availableStockList.add(stock);
        }
        Map<Long, List<Stock>> stockMap = availableStockList.stream().collect(Collectors.groupingBy(Stock::getPartId));
        // 计算各零件所需数量和已有库存数量
        List<ValidateOverFeedDTO> overFeedDTOS = new ArrayList<>();
        for (Map.Entry<Long, OperationTaskMaterial> entry : taskMaterialMap.entrySet()) {
            OperationTaskMaterial taskMaterial = entry.getValue();
            BigDecimal costQuantity = taskMaterial.getQpa().multiply(productQty);
            BigDecimal stockQuantity = BigDecimal.ZERO;
            if (stockMap.containsKey(taskMaterial.getPartId())) {
                stockQuantity =
                        stockMap.get(taskMaterial.getPartId()).stream().map(Stock::getAvailableStockQuantity).reduce(BigDecimal.ZERO, BigDecimal::add);
                // 将修改的原有报工所需材料还原回去
                stockQuantity = stockQuantity.add(oriProductQty.multiply(taskMaterial.getQpa()));
            }
            ValidateOverFeedDTO overFeedDTO =
                    ValidateOverFeedDTO.builder().partName(partMap.get(taskMaterial.getPartId()).getPartName())
                            .costQuantity(costQuantity).stockQuantity(stockQuantity).build();
            overFeedDTOS.add(overFeedDTO);
        }
        List<ValidateOverFeedDTO> overFeeds =
                overFeedDTOS.stream().filter(feedDto -> feedDto.getCostQuantity().compareTo(feedDto.getStockQuantity()) > 0).collect(Collectors.toList());
        List<String> resultMsg = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(overFeeds)) {
            resultMsg =
                    overFeeds.stream().map(f -> ("物料【" + f.getPartName() + "】" + "已有库存数量【" + f.getStockQuantity() +
                            "】,所需数量【" + f.getCostQuantity() + "】")).collect(Collectors.toList());
        }
        if (CollectionUtil.isNotEmpty(resultMsg)) {
            return R.ok(ValidateOverFeedResultDTO.builder().success(Boolean.FALSE).message(resultMsg).build());
        }
        return R.ok(ValidateOverFeedResultDTO.builder().success(Boolean.TRUE).build());
    }
 
    @Override
    public R process(List<Long> ids) {
        List<ProductMain> productMainList = productMainMapper.selectBatchIds(ids);
        boolean b = productMainList.stream().anyMatch(s -> !StringUtils.equals(ProductMainStateStringValues.DRAFT,
                s.getState()));
        if (BooleanUtil.isTrue(b)) {
            throw new RuntimeException("存在非草稿状态报工单,无法提交");
        }
        productMainList.forEach(p -> p.setState(ProductMainStateStringValues.PROCESSING));
        updateBatchById(productMainList);
        return R.ok();
    }
 
    @Override
    public Boolean validateIsLastOperation(Long id) {
        return operationTaskMapper.validateIsLastOperation(id);
    }
 
    @Override
    public List<ProductOutput> validateChangeProductOut(List<ProductOutput> list) {
        List<String> snList =
                list.stream().map(ProductOutput::getOutBatchNo).collect(Collectors.toList());
        List<ProductOutput> productOutputList = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery()
                .in(ProductOutput::getOutBatchNo, snList).eq(ProductOutput::getState, ProductOutStateStringValues.CHANGESHIFT));
        if (CollectionUtil.isNotEmpty(productOutputList)) {
            return list.stream().filter(s -> StringUtils.equals(s.getOutBatchNo(),
                    productOutputList.get(0).getOutBatchNo())).collect(Collectors.toList());
        }
        return null;
    }
 
    @Override
    public Boolean resetState(List<Long> ids) {
        List<ProductMain> productMainList = baseMapper.selectList(Wrappers.<ProductMain>lambdaQuery()
                .in(ProductMain::getId, ids)
                .eq(ProductMain::getState, ProductMainStateStringValues.PROCESSING));
        productMainList.stream().forEach(a -> {
            a.setState(ProductMainStateStringValues.DRAFT);
        });
        return this.updateBatchById(productMainList);
    }
 
    @Override
    public List<ProductOutputDTO> getDraftProductOut(Long id) {
        return productOutputMapper.getDraftProductOut(id);
    }
 
    @Override
    public Boolean validateStepFinish(String outBatchNo) {
        Integer productOutCount =
                productOutputMapper.selectCount(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getOutBatchNo,
                        outBatchNo));
        if (productOutCount == 0) {
            return true;
        }
        List<OperationJoinStep> operationJoinStepList = operationJoinStepMapper.getOperationJoinStepBySn(outBatchNo);
        if (CollectionUtil.isNotEmpty(operationJoinStepList)) {
            Integer integer =
                    productStepMapper.selectCount(Wrappers.<ProductStep>lambdaQuery().eq(ProductStep::getStepId,
                            operationJoinStepList.get(0).getTechnologyStepId()).eq(ProductStep::getSystemNo, outBatchNo));
            if (integer == 0) {
                throw new RuntimeException("当前SN有工步流程未走完");
            }
        }
        return Boolean.TRUE;
    }
 
    @Override
    public Boolean checkSn(StockDTO stockDTO) {
        if (StringUtils.isNotBlank(stockDTO.getPartBatchNo()) && !"*".equals(stockDTO.getPartBatchNo())) {
            List<Stock> stockList = stockMapper.selectList(Wrappers.<Stock>lambdaQuery().eq(Stock::getPartBatchNo, stockDTO.getPartBatchNo()).gt(Stock::getStockQuantity, 0));
            if (CollectionUtil.isNotEmpty(stockList)) {
                if (!stockList.get(0).getPartId().equals(stockDTO.getPartId())) {
                    throw new RuntimeException("零件号不一致");
                }
            }
            List<ProductOutput> productOutputList = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getOutBatchNo, stockDTO.getPartBatchNo()).eq(ProductOutput::getState, "01draft"));
            if (CollectionUtil.isNotEmpty(productOutputList)) {
                if (!productOutputList.get(0).getPartId().equals(stockDTO.getPartId())) {
                    throw new RuntimeException("零件号不一致");
                }
            }
 
        }
 
        return true;
    }
 
    /**
     * 判断工单是否是交班状态
     *
     * @param productMainId
     * @return Boolean
     */
    public Boolean judgeChangeshift(Long productMainId) {
        String state = productOutputMapper.judgeChangeshift(productMainId);
        if (ProductOutStateStringValues.CHANGESHIFT.equals(state)) {
            return true;
        } else {
            return false;
        }
    }
 
 
    public void updateLabelPrintTimes(List<Long> ids) {
        List<ProductOutput> outputList = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery()
                .in(ProductOutput::getId, ids));
        for (ProductOutput productOutput : outputList) {
            if (productOutput.getPrintNum() == null) {
                productOutput.setPrintNum(1L);
            } else {
                productOutput.setPrintNum(productOutput.getPrintNum() + 1);
            }
        }
        productOutputService.updateBatchById(outputList);
    }
}