Fixiaobai
2023-11-17 6ee9d58d62dbbccf95ce809f358ec9f8d088b705
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
package com.chinaztt.mes.plan.service.impl;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.anji.captcha.service.CaptchaCacheService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaztt.ifs.api.feign.IfsFeignClient;
import com.chinaztt.mes.basic.entity.Part;
import com.chinaztt.mes.basic.mapper.PartMapper;
import com.chinaztt.mes.basic.mapper.StaffMapper;
import com.chinaztt.mes.basic.mapper.UserServiceMapper;
import com.chinaztt.mes.basic.util.RedisUtils;
import com.chinaztt.mes.common.handler.StateMachineHandler;
import com.chinaztt.mes.common.numgen.NumberGenerator;
import com.chinaztt.mes.common.oa.OAProcess;
import com.chinaztt.mes.common.oa.OAProperty;
import com.chinaztt.mes.common.oa.OAResult;
import com.chinaztt.mes.common.util.StateResult;
import com.chinaztt.mes.common.util.WechatMsgTips;
import com.chinaztt.mes.common.wechat.WechatProperty;
import com.chinaztt.mes.plan.dto.*;
import com.chinaztt.mes.plan.entity.*;
import com.chinaztt.mes.plan.excel.CustomerOrderData;
import com.chinaztt.mes.plan.mapper.*;
import com.chinaztt.mes.plan.service.*;
import com.chinaztt.mes.plan.state.auditstate.constant.AuditStateStringValues;
import com.chinaztt.mes.plan.state.orderstate.CustomerOrderStateMachineConfig;
import com.chinaztt.mes.plan.state.orderstate.constant.CustomerOrderEvents;
import com.chinaztt.mes.plan.state.orderstate.constant.CustomerOrderStateStringValues;
import com.chinaztt.mes.plan.state.orderstate.constant.CustomerOrderStates;
import com.chinaztt.mes.plan.util.CustomerOrderClientConfigure;
import com.chinaztt.mes.plan.util.CustomerOrderUnitWhiteListConfig;
import com.chinaztt.mes.plan.util.CustomerOrderUtil;
import com.chinaztt.mes.plan.util.FileSaveUtil;
import com.chinaztt.mes.plan.vo.CustomerOrderVO1;
import com.chinaztt.mes.quality.dto.CustomOrderSyncDTO;
import com.chinaztt.mes.technology.entity.*;
import com.chinaztt.mes.technology.mapper.*;
import com.chinaztt.mes.technology.service.DocumentService;
import com.chinaztt.mes.technology.state.bom.constant.BomStates;
import com.chinaztt.mes.technology.state.document.constant.DocumentStateStringValues;
import com.chinaztt.mes.technology.state.document.constant.DocumentStates;
import com.chinaztt.mes.technology.state.routing.constant.RoutingStates;
import com.chinaztt.mes.warehouse.dto.PackagingDTO;
import com.chinaztt.mes.warehouse.entity.Packaging;
import com.chinaztt.mes.warehouse.entity.Stock;
import com.chinaztt.mes.warehouse.mapper.PackagingMapper;
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.oss.OssProperties;
import com.chinaztt.ztt.common.oss.service.OssTemplate;
import com.chinaztt.ztt.common.security.util.SecurityUtils;
import com.google.gson.Gson;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.dao.DuplicateKeyException;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.scheduling.annotation.Async;
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.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
 
/**
 * 客户订单表
 *
 * @author cxf
 * @date 2020-09-14 16:35:26
 */
@Slf4j
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class CustomerOrderServiceImpl extends ServiceImpl<CustomerOrderMapper, CustomerOrder> implements CustomerOrderService {
 
    private BomComponentMapper bomComponentMapper;
    private BomMapper bomMapper;
    private CustomerOrderUnitWhiteListConfig customerOrderUnitWhiteListConfig;
    private CustomerOrderParamMapper customerOrderParamMapper;
    private CustomerOrderParamJointStockCompanyMapper customerOrderParamJointStockCompanyMapper;
    private CustomerOrderUtil customerOrderUtil;
    private CustomerMapper customerMapper;
    private DocumentMapper documentMapper;
    private DocumentService documentService;
    private OrderParamMapper orderParamMapper;
    private OAProperty oaProperty;
    private OrderParamService orderParamService;
    private OperationTaskProduceMapper operationTaskProduceMapper;
    private IfsFeignClient ifsFeignClient;
    private JoinModelCustomerMapper joinModelCustomerMapper;
    private JoinDocumentBomRoutingMapper joinDocumentBomRoutingMapper;
    private MpsRequirementsMapper mpsRequirementsMapper;
    private MasterProductionScheduleMapper masterProductionScheduleMapper;
    private MasterProductionScheduleTheoryQuantityMapper masterProductionScheduleTheoryQuantityMapper;
    private NumberGenerator<MpsRequirements> numberGenerator;
    private NumberGenerator<MasterProductionSchedule> scheduleNumberGenerator;
    private PartMapper partMapper;
    private PlanJoinOrderRequirementsMapper planJoinOrderRequirementsMapper;
    private RoutingMapper routingMapper;
    private StateMachineFactory<CustomerOrderStates, CustomerOrderEvents> customerOrderStateMachineFactory;
    private StateMachinePersister<CustomerOrderStates, CustomerOrderEvents, CustomerOrder> persister;
    private CustomerOrderClientConfigure customerOrderClientConfigure;
    private CaptchaCacheService captchaCacheService;
    private CustomerForJointStockCompanyMapper customerForJointStockCompanyMapper;
    private CustomerOrderForJointStockCompanyMapper customerOrderForJointStockCompanyMapper;
 
    private OrderProcessConfigFileMapper orderProcessConfigFileMapper;
 
    private ProcessConfigFileOrderMappingMapper processConfigFileOrderMappingMapper;
 
    private ProcessConfigFileOrderMappingService processConfigFileOrderMappingService;
    private CustomerOrderMapper customerOrderMapper;
 
    private RedisUtils redisUtils;
 
    private ProcessConfigService processConfigService;
 
    private ProcessConfigMapper processConfigMapper;
 
    private DocumentJgtMapper documentJgtMapper;
 
    private PackageCodeCustomerOrderRelationService packageCodeCustomerOrderRelationService;
 
    private PackageCodeCustomerOrderRelationMapper packageCodeCustomerOrderRelationMapper;
 
    private PackagingMapper packagingMapper;
    private RemoteParamService remoteParamService;
 
    private StaffMapper staffMapper;
 
    private WechatProperty wechatProperty;
 
    private UserServiceMapper userServiceMapper;
 
    private final OssProperties ossProperties;
    private final OssTemplate minioTemplate;
    private final String PART_PROPERTY = "PART_PROPERTY";
    private final static String MO_RETURN_STAFF = "MO_RETURN_STAFF";
 
    private Environment environment;
 
    private final static String OTC_MAIN_STATUS_CANCEL = "已取消";
 
    private final static String OTC_MAIN_STATUS_TRANSMIT = "已下达";
 
    private final static String AFFILIATED_CONTRACT = "中天注塑厂";
 
    //private FileSaveUtil fileSaveUtil;
 
    @Override
    public void otcDownload(Long id, HttpServletResponse response) {
        customerOrderUtil.otcDownLoadFiles(id, response);
    }
 
    @Override
    public boolean createMpsRequirements(List<MpsRequirementsDTO> mpsRequirementsList) {
        try {
            for (MpsRequirementsDTO mpsRequirementsDTO : mpsRequirementsList) {
                // 1.保存主生产计划需求计划
                mpsRequirementsDTO.setIndeRequNo(numberGenerator.generateNumberWithPrefix(MpsRequirements.DIGIT, MpsRequirements.PREFIX, MpsRequirements::getIndeRequNo));
                mpsRequirementsDTO.setSourceType("02");
                mpsRequirementsMapper.insert(mpsRequirementsDTO);
                // 2.保存关联表
                planJoinOrderRequirementsMapper.insert(new PlanJoinOrderRequirements(mpsRequirementsDTO.getCustomerOrderId(), mpsRequirementsDTO.getId()));
            }
        } catch (Exception e) {
            throw new RuntimeException("创建主计划失败");
        }
        return true;
    }
 
    @Override
    public IPage getCustomerOrderPage(Page page, QueryWrapper<CustomerOrder> planCustomerOrder, String type) {
        //ZttUser currentUser = SecurityUtils.getUser();
        ////获取员工id
        //Long staffId = userServiceMapper.selectById(currentUser.getId()).getStaffId();
        return customerOrderMapper.getCustomerOrderPage(page, planCustomerOrder);
    }
 
 
    @Override
    public boolean changeMarkPlanned(List<Long> ids, String coState) {
//        changeCoState(ids, event);
        for (Long id : ids) {
            CustomerOrder customerOrder = baseMapper.selectById(id);
            customerOrder.setCoState(coState);
            if (coState.equals(CustomerOrderStateStringValues.CANCEL)) {
                if (!CustomerOrderStateStringValues.CANCEL.equals(customerOrder.getCoState())) {
                    List<JoinModelCustomer> joinModelCustomers = joinModelCustomerMapper.selectList(Wrappers.<JoinModelCustomer>lambdaQuery()
                            .eq(JoinModelCustomer::getModel, "plan_master_production_schedule")
                            .eq(JoinModelCustomer::getCustomerOrderId, customerOrder.getId()));
                    if (CollectionUtil.isNotEmpty(joinModelCustomers)) {
                        throw new RuntimeException(customerOrder.getCustomerOrderNo() + "已存在生产计划,作废失败");
                    }
                }
            }
            baseMapper.updateById(customerOrder);
        }
        return true;
    }
 
    /**
     * 改变状态
     *
     * @param customerOrder
     * @param
     */
    private void changeAudit(CustomerOrder customerOrder, String isAudit) {
        //审核状态 通过 订单状态待计划
        if (isAudit.equals(AuditStateStringValues.ACCEPTED)) {
            //TODO: 要加零件id参数
            Document document = documentMapper.selectById(customerOrder.getTechnologyDocumentId());
            Part part = partMapper.selectOne(Wrappers.<Part>lambdaQuery().eq(Part::getEngChgLevel, "1").eq(Part::getId,customerOrder.getPartId() ));
            if (null == part) {
                throw new RuntimeException("根据零件编号 = 【" + customerOrder.getPartNo() + "】MES本地查无匹配零件对象");
            }
            if (!part.getMaterialType().equals("3") && null == document) {
                throw new RuntimeException("缺少工艺文件");
            }
            customerOrder.setCoState(CustomerOrderStateStringValues.PLAN);
            docAccept(customerOrder, document);
        }
        //审核状态 草稿 订单状态待计划
        if (isAudit.equals(AuditStateStringValues.DRAFT)) {
            if (!CustomerOrderStateStringValues.CANCEL.equals(customerOrder.getCoState())) {
                List<JoinModelCustomer> joinModelCustomers = joinModelCustomerMapper.selectList(Wrappers.<JoinModelCustomer>lambdaQuery()
                        .eq(JoinModelCustomer::getModel, "plan_master_production_schedule")
                        .eq(JoinModelCustomer::getCustomerOrderId, customerOrder.getId()));
                if (CollectionUtil.isNotEmpty(joinModelCustomers)) {
                    throw new RuntimeException(customerOrder.getCustomerOrderNo() + "已存在生产计划,取消失败");
                }
            }
            customerOrder.setIsAudit(isAudit);
            customerOrder.setCoState(CustomerOrderStateStringValues.PLAN);
            baseMapper.updateById(customerOrder);
        }
    }
 
 
    @Override
    public R fullUpdate(CustomerOrderVO1 customerOrderVO1) {
        CustomerOrder customerOrder = new CustomerOrder();
        BeanUtils.copyProperties(customerOrderVO1,customerOrder);
        customerOrder.setId(customerOrderVO1.getId());
        customerOrderMapper.updateById(customerOrder);
 
        Customer customer = new Customer();
        BeanUtils.copyProperties(customerOrderVO1,customer);
        customer.setId(customerOrderMapper.selectById(customerOrderVO1.getId()).getCustomerId());
        customerMapper.updateById(customer);
        return R.ok("修改成功!");
    }
 
    @Override
    public boolean updateOrderDescription(CustomerOrderDTO customerOrderDTO) {
        CustomerOrder customerOrder = baseMapper.selectById(customerOrderDTO.getId());
        customerOrder.setOrderDescription(customerOrderDTO.getOrderDescription());
        if (customerOrder.getCoState().equals(CustomerOrderStateStringValues.UNIEDIT)) {
            customerOrder.setCoState(CustomerOrderStateStringValues.PARTUNCHECKED);
        }
        baseMapper.updateById(customerOrder);
        return true;
    }
 
 
    @Override
    public CustomerOrderVO1 getCustomerOrderById(Long id) {
        CustomerOrderVO1 customerOrderVO1 = new CustomerOrderVO1();
        //销售产品单(客户行表)
        CustomerOrder customerOrder = baseMapper.selectById(id);
        BeanUtils.copyProperties(customerOrder, customerOrderVO1);
        //客户主表
        Customer customer = customerMapper.selectById(customerOrder.getCustomerId());
        BeanUtils.copyProperties(customer,customerOrderVO1);
        if (customerOrder.getTechnologyDocumentId() != null) {
            Document document = documentMapper.selectById(customerOrder.getTechnologyDocumentId());
            if (document != null) {
                //工艺文件编号
                customerOrderVO1.setDocNumber(document.getNumber());
                //工艺文件名称
                customerOrderVO1.setDocName(document.getName());
            }
        }
        customerOrderVO1.setId(id);
        return customerOrderVO1;
    }
 
    @Override
    public R createScheduleCheck(List<CustomerOrderDTO> customerOrderDTOList) {
        for (CustomerOrderDTO customerOrder : customerOrderDTOList) {
            if (!customerOrder.getBuyQtyDue().equals(customerOrder.getQtyPlaned())) {
                return R.ok(CreateScheduleDTO.builder().success(Boolean.FALSE).message("计划数量与需求数量不一致").build());
            }
        }
        return R.ok(CreateScheduleDTO.builder().success(Boolean.TRUE).build());
    }
 
 
    @Override
    public boolean createMasterProductionSchedule(List<CustomerOrderDTO> customerOrderDTOList) {
        List<Long> ids = customerOrderDTOList.stream().map(CustomerOrderDTO::getId).collect(Collectors.toList());
        Integer count = getBaseMapper().selectCount(Wrappers.<CustomerOrder>lambdaQuery()
                .ne(CustomerOrder::getIsAudit, AuditStateStringValues.ACCEPTED)
                .in(CustomerOrder::getId, ids));
        if (count > 0) {
            throw new RuntimeException("未通过订单不可创建生产计划");
        }
        if (CollectionUtil.isEmpty(customerOrderDTOList)) {
            throw new RuntimeException("请选择客户订单");
        }
        int check = this.count(Wrappers.<CustomerOrder>lambdaQuery().in(CustomerOrder::getId, ids)
                .eq(CustomerOrder::getCoState, CustomerOrderStateStringValues.PLANED));
        if (check > 0) {
            throw new RuntimeException("已下发的订单不可重复创建主计划");
        }
 
        for (CustomerOrderDTO customerOrderDTO : customerOrderDTOList) {
            BigDecimal qta = customerOrderDTO.getQtyPlaned();
            //修改工单分段SN号数据 (2023-03-17 旧分段逻辑不再使用)
            // List<OperationTaskProduce> operationTaskProduceList = customerOrderDTO.getOutPutBatchList();
            // if (CollectionUtil.isNotEmpty(operationTaskProduceList)) {
            //     qta = operationTaskProduceList.stream().map(OperationTaskProduce::getQty).reduce(BigDecimal.ZERO, BigDecimal::add);
            // }
            //保存主生产计划
            MasterProductionSchedule masterProductionSchedule = new MasterProductionSchedule();
            //主生产计划号
            masterProductionSchedule.setMpsNo(scheduleNumberGenerator.generateNumberWithPrefix(MasterProductionSchedule.DIGIT, MasterProductionSchedule.PREFIX, MasterProductionSchedule::getMpsNo));
            Part part = partMapper.selectOne(Wrappers.<Part>lambdaQuery().eq(Part::getPartNo, customerOrderDTO.getPartNo()));
            //零件id
            masterProductionSchedule.setPartId(part.getId());
            //将审核状态和工艺文件的id同步给生产计划
            masterProductionSchedule.setIsAudit(customerOrderDTO.getIsAudit());
            masterProductionSchedule.setTechnologyDocumentId(customerOrderDTO.getTechnologyDocumentId());
            masterProductionSchedule.setManufactureAttr(customerOrderDTO.getManufactureAttr());
            masterProductionSchedule.setDocNumber(customerOrderDTO.getDocNumber());
            //需求数量
            masterProductionSchedule.setQtyRequired(qta);
            //需求日期
            masterProductionSchedule.setRequiredDate(customerOrderDTO.getDeliveryDate());
            //备注
            masterProductionSchedule.setRemark(customerOrderDTO.getRemark());
            masterProductionSchedule.setQtyRequired(qta);
            masterProductionSchedule.setRequiredDate(customerOrderDTO.getWantedDeliveryDate());
            masterProductionSchedule.setRemark(customerOrderDTO.getRemark());
            masterProductionSchedule.setSource("销售订单");
            masterProductionScheduleMapper.insert(masterProductionSchedule);
            customerOrderDTO.setRequireNumber(customerOrderDTO.getQtyPlaned());
 
            // if (CollectionUtil.isNotEmpty(operationTaskProduceList)) {
            //     for (OperationTaskProduce operationTaskProduce : operationTaskProduceList) {
            //         operationTaskProduce.setMpsId(masterProductionSchedule.getId());
            //         operationTaskProduceMapper.updateById(operationTaskProduce);
            //     }
            // }
 
            //更新客户订单的下发数量
            customerOrderDTO.setRequireNumber(customerOrderDTO.getRequireNumber().add(customerOrderDTO.getQtyPlaned()));
            if (customerOrderDTO.getRequireNumber().compareTo(customerOrderDTO.getBuyQtyDue()) >= 0) {//已下发数量等于销售数量(小于销售数量不能更改状态),状态应该更新为已计划。目前状态依旧为待计划。
                customerOrderDTO.setCoState(CustomerOrderStateStringValues.PLANED);
            }
            baseMapper.updateById(customerOrderDTO);
            //计算半成品用量
            calPlanTheory(masterProductionSchedule);
            //保存主计划与客户订单的关系
            JoinModelCustomer joinModelCustomer = new JoinModelCustomer();
            joinModelCustomer.setCustomerOrderId(customerOrderDTO.getId());
            joinModelCustomer.setModel("plan_master_production_schedule");
            joinModelCustomer.setModelId(masterProductionSchedule.getId());
            joinModelCustomerMapper.insert(joinModelCustomer);
        }
        return true;
    }
 
    //多个销售订单创建一个主生产计划
    @Override
    public MasterProductionSchedule createOneMasterProductionScheduleByCustomerOrders(List<CustomerOrderDTO> customerOrders) {
        List<Long> ids = customerOrders.stream().map(CustomerOrderDTO::getId).collect(Collectors.toList());
        Integer count = getBaseMapper().selectCount(Wrappers.<CustomerOrder>lambdaQuery()
                .ne(CustomerOrder::getIsAudit, AuditStateStringValues.ACCEPTED)
                .in(CustomerOrder::getId, ids));
        if (count > 0) {
            throw new RuntimeException("未通过订单不可创建生产计划");
        }
        if (CollectionUtil.isEmpty(customerOrders)) {
            throw new RuntimeException("请选择客户订单");
        }
 
        //保存主生产计划
        MasterProductionSchedule masterProductionSchedule = new MasterProductionSchedule();
        masterProductionSchedule.setMpsNo(scheduleNumberGenerator.generateNumberWithPrefix(MasterProductionSchedule.DIGIT, MasterProductionSchedule.PREFIX, MasterProductionSchedule::getMpsNo));
 
        BigDecimal qta = BigDecimal.ZERO;
 
        List<OperationTaskProduce> updateOperationTaskProduceList = new ArrayList<>();
 
        for (CustomerOrderDTO customerOrderDTO : customerOrders) {
            updateOperationTaskProduceList.addAll(customerOrderDTO.getOutPutBatchList());
            qta = qta.add(customerOrderDTO.getQtyPlaned());
            masterProductionSchedule.setPartId(customerOrderDTO.getPartId());
            //将审核状态和工艺文件的id同步给生产计划
            masterProductionSchedule.setIsAudit(customerOrderDTO.getIsAudit());
            masterProductionSchedule.setTechnologyDocumentId(customerOrderDTO.getTechnologyDocumentId());
            masterProductionSchedule.setManufactureAttr(customerOrderDTO.getManufactureAttr());
            // 查询工艺文件编号
            Document document = this.documentMapper.selectById(customerOrderDTO.getTechnologyDocumentId());
            masterProductionSchedule.setDocNumber(document.getNumber());
 
            // 取最近的交货日期
            if (masterProductionSchedule.getRequiredDate() == null) {
                masterProductionSchedule.setRequiredDate(customerOrderDTO.getWantedDeliveryDate());
            } else {
                if (masterProductionSchedule.getRequiredDate().compareTo(customerOrderDTO.getWantedDeliveryDate()) > 0) {
                    masterProductionSchedule.setRequiredDate(customerOrderDTO.getWantedDeliveryDate());
                }
            }
 
            // 订单备注进行拼接
            if (masterProductionSchedule.getRemark() == null) {
                masterProductionSchedule.setRemark(customerOrderDTO.getRemark());
            } else {
                masterProductionSchedule.setRemark(masterProductionSchedule.getRemark() + " " + customerOrderDTO.getRemark());
            }
            masterProductionSchedule.setSource("销售订单");
 
            // 更新销售订单状态为已下发
            customerOrderDTO.setCoState(CustomerOrderStateStringValues.PLANED);
            baseMapper.updateById(customerOrderDTO);
        }
 
        masterProductionSchedule.setQtyRequired(qta);
        masterProductionScheduleMapper.insert(masterProductionSchedule);
 
        // 更新批次表的生产计划id
        if (CollectionUtil.isNotEmpty(updateOperationTaskProduceList)) {
            for (OperationTaskProduce operationTaskProduce : updateOperationTaskProduceList) {
                operationTaskProduce.setMpsId(masterProductionSchedule.getId());
                operationTaskProduceMapper.updateById(operationTaskProduce);
            }
        }
 
        //计算半成品用量
        calPlanTheory(masterProductionSchedule);
 
        // 这里只生成一个关联关系
        // 保存主计划与客户订单的关系
        JoinModelCustomer joinModelCustomer = new JoinModelCustomer();
        joinModelCustomer.setCustomerOrderId(customerOrders.get(0).getId());
        joinModelCustomer.setModel("plan_master_production_schedule");
        joinModelCustomer.setModelId(masterProductionSchedule.getId());
        joinModelCustomerMapper.insert(joinModelCustomer);
 
        return masterProductionSchedule;
    }
 
    /**
     * 创建生产计划半成品用量
     *
     * @param masterProductionSchedule 生产计划
     */
    @Override
    public void calPlanTheory(MasterProductionSchedule masterProductionSchedule) {
        if (null == masterProductionSchedule.getTechnologyDocumentId()) {
            return;
        }
        Document document = documentMapper.selectById(masterProductionSchedule.getTechnologyDocumentId());
        if (null == document) {
            return;
        }
        Long docId = document.getId();
        //查询成品的BOM
        JoinDocumentBomRouting joinDocumentBomRouting = joinDocumentBomRoutingMapper.selectOne(Wrappers.<JoinDocumentBomRouting>lambdaQuery()
                .eq(JoinDocumentBomRouting::getDocumentId, docId).isNull(JoinDocumentBomRouting::getParentId));
        MasterProductionScheduleTheoryQuantity masterProductionScheduleTheoryQuantity = new MasterProductionScheduleTheoryQuantity();
        masterProductionScheduleTheoryQuantity.setPartId(masterProductionSchedule.getPartId());
        masterProductionScheduleTheoryQuantity.setQuantity(masterProductionSchedule.getQtyRequired());
        masterProductionScheduleTheoryQuantity.setMid(masterProductionSchedule.getId());
        masterProductionScheduleTheoryQuantity.setBomId(joinDocumentBomRouting.getBomId());
        masterProductionScheduleTheoryQuantity.setRoutingId(joinDocumentBomRouting.getRoutingId());
        masterProductionScheduleTheoryQuantity.setJoinDocBomRoutingId(joinDocumentBomRouting.getId());
        masterProductionScheduleTheoryQuantity.setIsMaster(true);
        masterProductionScheduleTheoryQuantityMapper.insert(masterProductionScheduleTheoryQuantity);
        List<JoinDocumentBomRouting> joinDocumentBomRoutingChildList = joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery()
                .eq(JoinDocumentBomRouting::getParentId, joinDocumentBomRouting.getId()));
        calPlanTheory(masterProductionScheduleTheoryQuantity, joinDocumentBomRoutingChildList, joinDocumentBomRouting.getBomId());
    }
 
    /**
     * @param mfather                         新增父产品的理论用量数据
     * @param joinDocumentBomRoutingChildList 子节点半成品
     * @param bomId                           父节点的bomId
     */
    private void calPlanTheory(MasterProductionScheduleTheoryQuantity mfather, List<JoinDocumentBomRouting> joinDocumentBomRoutingChildList, Long bomId) {
        //查询半成品的子节点
        for (JoinDocumentBomRouting jchild : joinDocumentBomRoutingChildList) {
            // 根据父bom的id 和 当前零件的partid 查询零件用量
            List<BomComponent> bomComponentList = bomComponentMapper.selectList(Wrappers.<BomComponent>lambdaQuery()
                    .eq(BomComponent::getBomId, bomId).eq(BomComponent::getPartId, jchild.getPartId()));
            if (bomComponentList.size() > 0) {
                BomComponent bomComponent = bomComponentList.get(0);
                if (bomComponent.getQpa() != null) {
                    MasterProductionScheduleTheoryQuantity mchild = new MasterProductionScheduleTheoryQuantity();
                    mchild.setPartId(bomComponent.getPartId());
                    mchild.setRoutingId(jchild.getRoutingId());
                    mchild.setBomId(jchild.getBomId());
                    mchild.setQuantity(bomComponent.getQpa().multiply(mfather.getQuantity()));
                    mchild.setMid(mfather.getMid());
                    mchild.setJoinDocBomRoutingId(jchild.getId());
                    masterProductionScheduleTheoryQuantityMapper.insert(mchild);
                    List<JoinDocumentBomRouting> list = joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery().eq(JoinDocumentBomRouting::getParentId, jchild.getId()));
                    calPlanTheory(mchild, list, jchild.getBomId());
                }
            }
        }
    }
 
    @Override
    public void changeCoState(List<Long> ids, String event) {
        for (Long id : ids) {
            CustomerOrder customerOrder = baseMapper.selectById(id);
            Message<CustomerOrderEvents> message = MessageBuilder.withPayload(CustomerOrderEvents.valueOf(event)).setHeader("customerOrder", customerOrder).build();
            StateMachineHandler handler = new StateMachineHandler(customerOrderStateMachineFactory, persister, CustomerOrderStateMachineConfig.MACHINE_ID, customerOrder);
            StateResult res = handler.sendEvent(message, customerOrder.getId());
            if (!res.isSuccess()) {
                throw new RuntimeException(res.getMsg());
            }
        }
    }
 
    @Override
    public R handleDocument(List<Long> ids, Long docId) {
        Document document = documentMapper.selectById(docId);
        if (document == null) {
            return R.failed("工艺文件缺失");
        }
        List<CustomerOrder> customerOrderList = baseMapper.selectBatchIds(ids);
        customerOrderList.forEach(l->{
            log.info("关联数据==============================>"+l);
        });
        String msg = "";
        for (CustomerOrder customerOrder : customerOrderList) {
            if (BooleanUtil.isTrue(customerOrder.getIsDocument())) {
                msg += customerOrder.getCustomerOrderNo() + "已关联工艺文件!";
            }
            if (StringUtils.isBlank(customerOrder.getPartNo())) {
                msg += customerOrder.getCustomerOrderNo() + "未选择销售件!";
            }
            //if (StringUtils.isBlank(customerOrder.getPartNo())) {
            //    customerOrder.setPartNo(document.getPartNo());
            //}
            customerOrder.setIsDocument(true);
            customerOrder.setCoState(CustomerOrderStateStringValues.PLAN);
            customerOrder.setTechnologyDocumentId(docId);
        }
        if (StringUtils.isBlank(msg)) {
            saveOrUpdateBatch(customerOrderList);
            return R.ok().setMsg("OK");
        } else {
            return R.failed(msg);
        }
    }
 
 
    /**
     * 取消关联
     *
     * @param ids
     * @return
     */
    @Override
    public R rejectHandleDocument(List<Long> ids) {
        for (Long id : ids) {
            CustomerOrder customerOrder = baseMapper.selectById(id);
            if (customerOrder.getIsAudit() != null) {
                if (customerOrder.getIsAudit().equals(AuditStateStringValues.ACCEPTED) || customerOrder.getIsAudit().equals(AuditStateStringValues.PENDING)) {
                    return R.failed("合同号:" + customerOrder.getCustomerOrderNo() + "行号:" + customerOrder.getCoLineNo() + "已在流程中不可解除关联");
                }
            }
            baseMapper.rejectHandleDocument(id);
        }
        return R.ok();
    }
 
    /**
     * 根据时间获取otc订单数据
     *
     * @return
     */
    @Override
    public R otcCustomerOrderSyncAuto() {
        String param = XxlJobHelper.getJobParam();
        LocalDateTime dateTime = null;
        if (StringUtils.isNotBlank(param)) {
            dateTime = LocalDateTime.now().minusHours(Long.parseLong(param));
        } else {
            dateTime = LocalDateTime.now().minusHours(1);
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return otcCustomerOrderSync(dateTime.format(formatter), "0");
    }
 
    /**
     * 根据时间获取otc订单数据
     *
     * @param selectTime
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R otcCustomerOrderSync(String selectTime, String pathCode) {
        try {
            if (StringUtils.isBlank(selectTime)) {
                return R.failed("缺少查询时间");
            }
            String token = customerOrderUtil.getToken();
            return addCustomerFromOtc(selectTime, token);
        } catch (Exception e) {
            return R.failed(e.getMessage());
        }
    }
 
 
    /**
     * 添加主表信息
     *
     * @param selectTime 时间
     * @param token      token
     * @return
     */
    private R addCustomerFromOtc(String selectTime, String token) {
        try {
            Map<String, Object> map = new HashMap<>();
            if (StringUtils.isNotBlank(selectTime)) {
                map.put("selectTime", selectTime);
            }
            String str = HttpRequest.get(customerOrderClientConfigure.getOtcHost() + customerOrderClientConfigure.getOtcCustomerUrl())
                    .contentType("application/json")
                    .header("Authorization", "Bearer " + token).form(map).execute().body();
            JSONObject result = JSONObject.parseObject(str);
            //主表参数表
            List<OrderParam> orderParams = orderParamService.list();
            if (result.getInteger("code") == 0) {
                int num = 0;
                int detailNum = 0;
                JSONArray jsonArray = result.getJSONArray("data");
                for (Object obj : jsonArray) {
                    JSONObject customerJSONObject = JSONObject.parseObject(obj.toString());
                    //合同编号
                    String contractNo = customerJSONObject.getString("orderNo");
                    //主表在OTC中的状态
                    String otcMainStatus = customerJSONObject.getString("status");
                    //所属公司
                    String affiliatedCompany = customerJSONObject.getString("affiliatedCompany");
                    //所属工厂
                    String affiliatedContract=customerJSONObject.getString("affiliatedContract");
                    //只拉取所属公司为中天海洋系统有限公司的数据
                    if (!AFFILIATED_CONTRACT.equals(affiliatedContract)){
                        continue;
                    }
                    // 不在这几个状态中的数据就跳过
                    if (!Arrays.asList(CustomerOrderStateStringValues.GETOTCSTATE).contains(otcMainStatus)) {
                        continue;
                    }
                    Customer customer = customerMapper.selectOne(Wrappers.<Customer>lambdaQuery().eq(Customer::getContractNo, contractNo));
                    if (customer == null) {
                        customer = new Customer();
                    }
                    //如果OTC中主表状态是取消那就跳过或者删除已经同步的数据
                    if (OTC_MAIN_STATUS_CANCEL.equals(otcMainStatus)) {
                        if (customer.getId() != null) {
                            customerMapper.deleteById(customer.getId());
                            baseMapper.delete(Wrappers.<CustomerOrder>lambdaQuery().eq(CustomerOrder::getCustomerId, customer.getId()));
                        }
                        continue;
                    }
                    if (!OTC_MAIN_STATUS_TRANSMIT.equals(otcMainStatus)) {//null == affiliatedCompany || !Arrays.asList("已下达").contains(otcMainStatus) /*|| affiliatedCompany.equals("江苏中天科技股份有限公司")*/) {
                        continue;//只获取OTC中已审核及已下达的订单,
                    }
                    //客户编号
                    customer.setCustomerNo(customerJSONObject.getString("customerNo"));
                    //合同号
                    customer.setContractNo(contractNo);
                    //客户合同号
                    customer.setCustomerContractNo(customerJSONObject.getString("customerContractNumber"));
                    //客户名称
                    customer.setCustomerName(customerJSONObject.getString("customerName"));
                    //工程名称
                    customer.setEntityName(customerJSONObject.getString("projectName"));
                    //交货日期
                    customer.setDeliveryDate(customerJSONObject.get("wantedDeliveryDate") != null ?
                            customerJSONObject.getDate("wantedDeliveryDate").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null);
                    //事业部
                    customer.setSalesDepartment(customerJSONObject.getString("division"));
                    //省份
                    customer.setProvince(customerJSONObject.getString("province"));
                    //业务员名称
                    customer.setSalesMan(customerJSONObject.getString("salesmanName"));
                    //业务员编号
                    customer.setSalerWorkCode(customerJSONObject.getString("salesmanNo"));
                    //正本状态
                    customer.setOriginalContractStatus(customerJSONObject.getString("originalStatus"));
                    //合同正本状态
                    customer.setReturnStatus(customerJSONObject.getString("returnStatus"));
                    //项目性质
                    customer.setIsCp(customerJSONObject.getString("natureOfProjectExecution"));
                    //下单日期
                    customer.setPlaceOrderDate(customerJSONObject.getDate("orderDate").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    //审核日期
                    customer.setVerifyDate(customerJSONObject.get("reviewTime") != null ?
                            customerJSONObject.getDate("reviewTime").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null);
                    //工厂下单日期
                    customer.setFactoryPlaceOrderDate(customerJSONObject.get("factoryOrderDate") != null ?
                            customerJSONObject.getDate("factoryOrderDate").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null);
                    //备注
                    customer.setComment(customerJSONObject.getString("comment"));
                    if (customer.getId() == null) {
                        customerMapper.insert(customer);
                    } else {
                        customerMapper.updateById(customer);
                    }
                    num += 1;
 
                    detailNum += addCustomerOrderFromOtc(customerJSONObject, customer, token, orderParams, otcMainStatus);
                }
                return R.ok().setMsg("同步或更新合同主体" + num + "条,合同明细" + detailNum + "条!");
            } else {
                return R.failed("订单主体获取失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
 
    /**
     * 添加子表信息
     *
     * @param customer
     * @param otcMainStatus
     * @throws Exception
     */
    private int addCustomerOrderFromOtc(JSONObject customerJSONObject, Customer customer, String token, List<OrderParam> orderParamList, String otcMainStatus) {
        Map<String, String> productTypeGroupMap = customerOrderUnitWhiteListConfig.getProductTypeGroupMap();
        int num = 0;
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("orderNo", customer.getContractNo());
            map.put("selectTime", "1899-12-31 23:59:59");
            JSONObject result = JSONObject.parseObject(HttpRequest.get(customerOrderClientConfigure.getOtcHost() + customerOrderClientConfigure.getOtcCustomerOrderUrl())
                    .contentType("application/json")
                    .header("Authorization", "Bearer " + token).form(map).execute().body());
            if (result.getInteger("code") == 0) {
                JSONArray jsonArray = result.getJSONArray("data");
                for (Object obj : jsonArray) {
                    JSONObject customerOrderJSONObject = JSONObject.parseObject(obj.toString());
                    String otcLoneId = customerOrderJSONObject.getLong("id").toString();
                    //OTC的订单状态
                    String otcOrderStatus = customerOrderJSONObject.getString("lineStatus").toString();
                    CustomerOrder customerOrder = baseMapper.selectOne(Wrappers.<CustomerOrder>lambdaQuery()
                            .eq(CustomerOrder::getOtcLineNo, otcLoneId));
                    if (customerOrder == null) {
                        customerOrder = new CustomerOrder();
                    }
                    //如果这个单子在OTC中取消状态 那就删除
                    if (otcOrderStatus.equals(OTC_MAIN_STATUS_CANCEL)) {
                        if (customerOrder.getId() != null) {
                            baseMapper.deleteById(customerOrder.getId());
                        }
                        continue;
                    }
                    //OTC合同号主表id
                    customerOrder.setOtcOrderId(customerOrderJSONObject.getLong("orderId"));
                    //otc行号
                    customerOrder.setOtcLineNo(otcLoneId);
                    //零件号
                    customerOrder.setPartNo(customerOrderJSONObject.getString("partNo"));
                    //来源 0:自动
                    customerOrder.setSourceId("0");
                    //合同号
                    customerOrder.setCustomerOrderNo(customer.getContractNo());
                    //客户号
                    customerOrder.setCustomerNo(customer.getCustomerNo());
                    //客户名称
                    customerOrder.setCustomerName(customer.getCustomerName());
                    //工程名称
                    customerOrder.setEntityName(customer.getEntityName());
                    //数量
                    customerOrder.setBuyQtyDue(customerOrderJSONObject.getBigDecimal("quantity"));
                    //OTC单位
                    customerOrder.setOtcUnit(customerOrderJSONObject.getString("unit"));
                    //期望交货日期
                    customerOrder.setWantedDeliveryDate(customer.getDeliveryDate());
                    //主表id
                    customerOrder.setCustomerId(customer.getId());
                    //电压等级
                    customerOrder.setVoltAgeClass(customerOrderJSONObject.getString("voltageLevel"));
                    //外呼颜色
                    customerOrder.setOuterColor(customerOrderJSONObject.getString("outerSheathColor"));
                    //客户零件名称
                    customerOrder.setProductName(customerOrderJSONObject.getString("productName"));
                    //客户零件规格
                    customerOrder.setCustomerPartSpec(customerOrderJSONObject.getString("specificationModel"));
                    //订单版本
                    customerOrder.setVersion(customerOrderJSONObject.getInteger("version"));
                    //事业部
                    customerOrder.setDivision(customerOrderJSONObject.getString("division"));
                    //印字类型
                    customerOrder.setPrintType(customerOrderJSONObject.getString("printType"));
                    //印字内容
                    customerOrder.setPrintContent(customerOrderJSONObject.getString("printContent"));
                    //印字要求
                    customerOrder.setPrintingRequirements(customerOrderJSONObject.getString("printingRequirements"));
                    //包装要求
                    customerOrder.setPackageRequire(customerOrderJSONObject.getString("packageRequire"));
                    //质量要求
                    customerOrder.setQualityRequire(customerOrderJSONObject.getString("qualityRequire"));
                    //生产需求说明
                    customerOrder.setOtherProductRequire(customerOrderJSONObject.getString("otherProductRequire"));
                    //系统
                    customerOrder.setDivisionSystem(customerOrderJSONObject.getString("divisionSystem"));
                    //收货地址
                    customerOrder.setShippingAddress(customerOrderJSONObject.getString("shippingAddress"));
                    //业务员
                    customerOrder.setSalesmanName(customer.getSalesMan());
                    //盘长要求
                    customerOrder.setLengthRequirement(customerOrderJSONObject.getString("lengthRequirement"));
                    //产品备注Ï
                    customerOrder.setRemark(customerOrderJSONObject.getString("orderComment"));
                    //产品类型
                    customerOrder.setProductType(customerOrderJSONObject.getString("productType"));
                    //产品分组
                    customerOrder.setProductGroup(productTypeGroupMap.get(customerOrderJSONObject.getString("productType")));
                    //采集性质
                    customerOrder.setCentralizedMiningProperty(customerJSONObject.getString("centralizedMiningProperty"));
                    //最终客户名称
                    customerOrder.setFinalCustomerName(customerJSONObject.getString("finalCustomerName"));
                    //销售件描述
                    customerOrder.setSalesPartName(customerOrderJSONObject.getString("partDesc"));
 
                    if (customerOrder.getId() == null) {
                        // 零件是否推送
                        customerOrder.setOtcPartSync(false);
                        // 默认为N 数据字典为:N:普通,S:样品,D:研发
                        customerOrder.setManufactureAttr("N");
                        //是否关联工艺文件为否
                        customerOrder.setIsDocument(false);
                        //状态为 如果采集性质 非采集和 省采集  状态位编辑  否则为 零件待选
                        if (customerOrder.getCentralizedMiningProperty().equals("非集采") || customerOrder.getCentralizedMiningProperty().equals("省集采")) {
                            customerOrder.setCoState(CustomerOrderStateStringValues.UNIEDIT);
                        } else {
                            customerOrder.setCoState(CustomerOrderStateStringValues.PARTUNCHECKED);
                        }
                        if (org.apache.commons.lang3.StringUtils.equals(OTC_MAIN_STATUS_TRANSMIT, otcMainStatus)) {
                            customerOrder.setCoState(CustomerOrderStateStringValues.TECHNOLOGYUNCHECK);
                            customerOrder.setOtcPartSync(Boolean.TRUE);
                        }
                        // 如果状态为零件待选,且零件号不为空,更新状态
                        if (StrUtil.isNotBlank(customerOrder.getPartNo()) && CustomerOrderStateStringValues.PARTUNCHECKED.equals(customerOrder.getCoState())) {
                            customerOrder.setCoState(CustomerOrderStateStringValues.TECHNOLOGYUNCHECK);
                            customerOrder.setOtcPartSync(Boolean.TRUE);
                        }
                        //审核状态为 03accepted 通过
                        customerOrder.setIsAudit(AuditStateStringValues.ACCEPTED);
                        baseMapper.insert(customerOrder);
                    }
                    addCustomerPara(customerJSONObject, customerOrderJSONObject, customerOrder, orderParamList);
                    num += 1;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("订单行数据获取失败,原因:" + e.getMessage());
        }
        return num;
    }
 
    ///**
    // * 添加主表信息
    // *
    // * @param selectTime 时间
    // * @param token      token
    // * @return
    // */
    //private R addCustomerFromOtc(String selectTime, String token) {
    //    try {
    //        Map<String, Object> map = new HashMap<>();
    //        if (StringUtils.isNotBlank(selectTime)) {
    //            map.put("selectTime", selectTime);
    //        }
    //        String str = HttpRequest.get(customerOrderClientConfigure.getOtcHost() + customerOrderClientConfigure.getOtcCusomerUrl())
    //                .contentType("application/json")
    //                .header("Authorization", "Bearer " + token).form(map).execute().body();
    //        JSONObject result = JSONObject.parseObject(str);
    //        //主表参数表
    //        List<OrderParam> orderParams = orderParamService.list();
    //        if (result.getInteger("code") == 0) {
    //            int num = 0;
    //            int detailNum = 0;
    //            JSONArray jsonArray = result.getJSONArray("data");
    //            for (Object obj : jsonArray) {
    //                JSONObject customerJSONObject = JSONObject.parseObject(obj.toString());
    //                //合同编号
    //                String contractNo = customerJSONObject.getString("orderNo");
    //                //主表在OTC中的状态
    //                String otcMainStatus = customerJSONObject.getString("status");
    //                //所属公司
    //                String affiliatedCompany = customerJSONObject.getString("affiliatedCompany");
    //                // 不在这几个状态中的数据就跳过
    //                if (!Arrays.asList(CustomerOrderStateStringValues.GETOTCSTATE).contains(otcMainStatus)) {
    //                    continue;
    //                }
    //                Customer customer = customerMapper.selectOne(Wrappers.<Customer>lambdaQuery().eq(Customer::getContractNo, contractNo));
    //                if (customer == null) {
    //                    customer = new Customer();
    //                }
    //                //如果OTC中主表状态是取消那就跳过或者删除已经同步的数据
    //                if (otcMainStatus.equals("已取消")) {
    //                    if (customer.getId() != null) {
    //                        customerMapper.deleteById(customer.getId());
    //                        baseMapper.delete(Wrappers.<CustomerOrder>lambdaQuery().eq(CustomerOrder::getCustomerId, customer.getId()));
    //                    }
    //                    continue;
    //                }
    //                if (null == affiliatedCompany || !Arrays.asList("已审核", "已下达").contains(otcMainStatus) || affiliatedCompany.equals("江苏中天科技股份有限公司")) {
    //                    continue;//只获取OTC中已审核及已下达的订单,且所属公司不是中天科技
    //                }
    //                //客户编号
    //                customer.setCustomerNo(customerJSONObject.getString("customerNo"));
    //                //合同号
    //                customer.setContractNo(contractNo);
    //                //客户合同号
    //                customer.setCustomerContractNo(customerJSONObject.getString("customerContractNumber"));
    //                //客户名称
    //                customer.setCustomerName(customerJSONObject.getString("customerName"));
    //                //工程名称
    //                customer.setEntityName(customerJSONObject.getString("projectName"));
    //                //交货日期
    //                customer.setDeliveryDate(customerJSONObject.get("wantedDeliveryDate") != null ?
    //                        customerJSONObject.getDate("wantedDeliveryDate").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null);
    //                //事业部
    //                customer.setSalesDepartment(customerJSONObject.getString("division"));
    //                //省份
    //                customer.setProvince(customerJSONObject.getString("province"));
    //                //业务员名称
    //                customer.setSalesMan(customerJSONObject.getString("salesmanName"));
    //                //业务员编号
    //                customer.setSalerWorkCode(customerJSONObject.getString("salesmanNo"));
    //                //正本状态
    //                customer.setOriginalContractStatus(customerJSONObject.getString("originalStatus"));
    //                //合同正本状态
    //                customer.setReturnStatus(customerJSONObject.getString("returnStatus"));
    //                //项目性质
    //                customer.setIsCp(customerJSONObject.getString("natureOfProjectExecution"));
    //                //下单日期
    //                customer.setPlaceOrderDate(customerJSONObject.getDate("orderDate").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
    //                //审核日期
    //                customer.setVerifyDate(customerJSONObject.get("reviewTime") != null ?
    //                        customerJSONObject.getDate("reviewTime").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null);
    //                //工厂下单日期
    //                customer.setFactoryPlaceOrderDate(customerJSONObject.get("factoryOrderDate") != null ?
    //                        customerJSONObject.getDate("factoryOrderDate").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null);
    //                //备注
    //                customer.setComment(customerJSONObject.getString("comment"));
    //                if (customer.getId() == null) {
    //                    customerMapper.insert(customer);
    //                } else {
    //                    customerMapper.updateById(customer);
    //                }
    //                num += 1;
    //
    //                detailNum += addCustomerOrderFromOtc(customerJSONObject, customer, token, orderParams, otcMainStatus);
    //            }
    //            return R.ok().setMsg("同步或更新合同主体" + num + "条,合同明细" + detailNum + "条!");
    //        } else {
    //            return R.failed("订单主体获取失败");
    //        }
    //    } catch (Exception e) {
    //        throw new RuntimeException(e.getMessage());
    //    }
    //}
    //
 
    /**
     * 添加子表信息
     *
     * @param customer
     * @param otcMainStatus
     * @throws Exception
     */
    //private int addCustomerOrderFromOtc(JSONObject customerJSONObject, Customer customer, String token, List<OrderParam> orderParamList, String otcMainStatus) {
    //    Map<String, String> productTypeGroupMap = customerOrderUnitWhiteListConfig.getProductTypeGroupMap();
    //    int num = 0;
    //    try {
    //        Map<String, Object> map = new HashMap<>();
    //        map.put("orderNo", customer.getContractNo());
    //        map.put("selectTime", "1899-12-31 23:59:59");
    //        JSONObject result = JSONObject.parseObject(HttpRequest.get(customerOrderClientConfigure.getOtcHost() + customerOrderClientConfigure.getOtcCustomerOrderUrl())
    //                .contentType("application/json")
    //                .header("Authorization", "Bearer " + token).form(map).execute().body());
    //        if (result.getInteger("code") == 0) {
    //            JSONArray jsonArray = result.getJSONArray("data");
    //            for (Object obj : jsonArray) {
    //                JSONObject customerOrderJSONObject = JSONObject.parseObject(obj.toString());
    //                String otcLoneId = customerOrderJSONObject.getLong("id").toString();
    //                //OTC的订单状态
    //                String otcOrderStatus = customerOrderJSONObject.getString("lineStatus").toString();
    //                CustomerOrder customerOrder = baseMapper.selectOne(Wrappers.<CustomerOrder>lambdaQuery()
    //                        .eq(CustomerOrder::getOtcLineNo, otcLoneId));
    //                if (customerOrder == null) {
    //                    customerOrder = new CustomerOrder();
    //                }
    //                //如果这个单子在OTC中取消状态 那就删除
    //                if (otcOrderStatus.equals("已取消")) {
    //                    if (customerOrder.getId() != null) {
    //                        baseMapper.deleteById(customerOrder.getId());
    //                    }
    //                    continue;
    //                }
    //                //OTC合同号主表id
    //                customerOrder.setOtcOrderId(customerOrderJSONObject.getLong("orderId"));
    //                //otc行号
    //                customerOrder.setOtcLineNo(otcLoneId);
    //                //零件号
    //                customerOrder.setSalesPartNo(customerOrderJSONObject.getString("partNo"));
    //                //来源
    //                customerOrder.setSourceId("OTC");
    //                //合同号
    //                customerOrder.setCustomerOrderNo(customer.getContractNo());
    //                //客户号
    //                customerOrder.setCustomerNo(customer.getCustomerNo());
    //                //客户名称
    //                customerOrder.setCustomerName(customer.getCustomerName());
    //                //销售数量原先OTC的单位
    //                customerOrder.setOtcQuantity(customerOrderJSONObject.getBigDecimal("quantity"));
    //                //OTC单位
    //                customerOrder.setOtcUnit(customerOrderJSONObject.getString("unit"));
    //                //期望交货日期
    //                customerOrder.setWantedDeliveryDate(customer.getDeliveryDate());
    //                //主表id
    //                customerOrder.setCustomerId(customer.getId());
    //                //电压等级
    //                customerOrder.setVoltAgeClass(customerOrderJSONObject.getString("voltageLevel"));
    //                //外呼颜色
    //                customerOrder.setOuterColor(customerOrderJSONObject.getString("outerSheathColor"));
    //                //客户零件名称
    //                customerOrder.setProductName(customerOrderJSONObject.getString("productName"));
    //                //客户零件规格
    //                customerOrder.setCustomerPartSpec(customerOrderJSONObject.getString("specificationModel"));
    //                //订单版本
    //                customerOrder.setVersion(customerOrderJSONObject.getInteger("version"));
    //                //事业部
    //                customerOrder.setDivision(customerOrderJSONObject.getString("division"));
    //                //印字类型
    //                customerOrder.setPrintType(customerOrderJSONObject.getString("printType"));
    //                //印字内容
    //                customerOrder.setPrintContent(customerOrderJSONObject.getString("printContent"));
    //                //印字要求
    //                customerOrder.setPrintingRequirements(customerOrderJSONObject.getString("printingRequirements"));
    //                //包装要求
    //                customerOrder.setPackageRequire(customerOrderJSONObject.getString("packageRequire"));
    //                //质量要求
    //                customerOrder.setQualityRequire(customerOrderJSONObject.getString("qualityRequire"));
    //                //生产需求说明
    //                customerOrder.setOtherProductRequire(customerOrderJSONObject.getString("otherProductRequire"));
    //                //系统
    //                customerOrder.setDivisionSystem(customerOrderJSONObject.getString("divisionSystem"));
    //                //收货地址
    //                customerOrder.setShippingAddress(customerOrderJSONObject.getString("shippingAddress"));
    //                //业务员
    //                customerOrder.setSalesmanName(customer.getSalesMan());
    //                //盘长要求
    //                customerOrder.setLengthRequirement(customerOrderJSONObject.getString("lengthRequirement"));
    //                //备注Ï
    //                customerOrder.setRemark(customerOrderJSONObject.getString("comment"));
    //                //产品类型
    //                customerOrder.setProductType(customerOrderJSONObject.getString("productType"));
    //                //产品分组
    //                customerOrder.setProductGroup(productTypeGroupMap.get(customerOrderJSONObject.getString("productType")));
    //                //采集性质
    //                customerOrder.setCentralizedMiningProperty(customerJSONObject.getString("centralizedMiningProperty"));
    //                //最终客户名称
    //                customerOrder.setFinalCustomerName(customerJSONObject.getString("finalCustomerName"));
    //                //销售件描述
    //                customerOrder.setSalesPartName(customerOrderJSONObject.getString("partDesc"));
    //
    //                if (customerOrder.getId() == null) {
    //                    // 零件是否推送
    //                    customerOrder.setOtcPartSync(false);
    //                    // 默认为N 数据字典为:N:普通,S:样品,D:研发
    //                    customerOrder.setManufactureAttr("N");
    //                    //是否关联工艺文件为否
    //                    customerOrder.setIsDocument(false);
    //                    //状态为 如果采集性质 非采集和 省采集  状态位编辑  否则为 零件待选
    //                    if (customerOrder.getCentralizedMiningProperty().equals("非集采") || customerOrder.getCentralizedMiningProperty().equals("省集采")) {
    //                        customerOrder.setCoState(CustomerOrderStateStringValues.UNIEDIT);
    //                    } else {
    //                        customerOrder.setCoState(CustomerOrderStateStringValues.PARTUNCHECKED);
    //                    }
    //                    if (org.apache.commons.lang3.StringUtils.equals("已下达", otcMainStatus)) {
    //                        customerOrder.setCoState(CustomerOrderStateStringValues.TECHNOLOGYUNCHECK);
    //                        customerOrder.setOtcPartSync(Boolean.TRUE);
    //                    }
    //                    //审核状态为 01draft 草稿
    //                    customerOrder.setIsAudit(AuditStateStringValues.DRAFT);
    //                    baseMapper.insert(customerOrder);
    //                } else {
    //                    // 如果状态为零件待选,且销售件号不为空,更新状态
    //                    if (StrUtil.isNotBlank(customerOrder.getSalesPartNo()) && CustomerOrderStateStringValues.PARTUNCHECKED.equals(customerOrder.getCoState())) {
    //                        customerOrder.setCoState(CustomerOrderStateStringValues.TECHNOLOGYUNCHECK);
    //                        customerOrder.setOtcPartSync(Boolean.TRUE);
    //                    }
    //                    baseMapper.updateById(customerOrder);
    //                }
    //                addCustomerPara(customerJSONObject, customerOrderJSONObject, customerOrder, orderParamList);
    //                num += 1;
    //            }
    //        }
    //    } catch (Exception e) {
    //        throw new RuntimeException("订单行数据获取失败,原因:" + e.getMessage());
    //    }
    //    return num;
    //}
 
    /**
     * @param jsonObjMain    主表的jsonObj
     * @param jsonObjDetail  子表的jsonObj
     * @param customerOrder  客户订单(股份公司)
     * @param orderParamList
     */
    private void addCustomerPara(JSONObject jsonObjMain, JSONObject jsonObjDetail, CustomerOrder customerOrder, List<OrderParam> orderParamList) {
        //先删除再次新增
        customerOrderParamMapper.delete(Wrappers.<CustomerOrderParam>lambdaQuery().eq(CustomerOrderParam::getOrderId, customerOrder.getId()));
        //新增参数
        for (OrderParam orderParam : orderParamList) {
            String field = orderParam.getField();
            CustomerOrderParam customerOrderParam = new CustomerOrderParam();
            customerOrderParam.setField(orderParam.getField());
            customerOrderParam.setOrderId(customerOrder.getId());
            customerOrderParam.setOrderParamId(orderParam.getId());
            if (orderParam.getDistinguish().equals("主表")) {
                customerOrderParam.setValue(jsonObjMain.getString(field));
            } else {
                customerOrderParam.setValue(jsonObjDetail.getString(field));
            }
            customerOrderParamMapper.insert(customerOrderParam);
        }
    }
 
    /**
     * @param jsonObjMain    主表的jsonObj
     * @param jsonObjDetail  子表的jsonObj
     * @param customerOrder  客户订单
     * @param orderParamList
     */
    private void addCustomerParaForJointStockCompany(JSONObject jsonObjMain, JSONObject jsonObjDetail, CustomerOrderForJointStockCompany customerOrder, List<OrderParam> orderParamList) {
        //先删除再次新增
        customerOrderParamJointStockCompanyMapper.delete(Wrappers.<CustomerOrderParamJointStockCompany>lambdaQuery().eq(CustomerOrderParamJointStockCompany::getOrderId, customerOrder.getId()));
        //新增参数
        for (OrderParam orderParam : orderParamList) {
            String field = orderParam.getField();
            CustomerOrderParamJointStockCompany customerOrderParam = new CustomerOrderParamJointStockCompany();
            customerOrderParam.setField(orderParam.getField());
            customerOrderParam.setOrderId(customerOrder.getId());
            customerOrderParam.setOrderParamId(orderParam.getId());
            if (orderParam.getDistinguish().equals("主表")) {
                customerOrderParam.setValue(jsonObjMain.getString(field));
            } else {
                customerOrderParam.setValue(jsonObjDetail.getString(field));
            }
            customerOrderParamJointStockCompanyMapper.insert(customerOrderParam);
        }
    }
 
    @Override
    public R querySalesPartStd(SalesPartDTO salesPartDTO) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotBlank(salesPartDTO.getSalesPartNo())) {
            jsonObject.put("CATALOG_NO", salesPartDTO.getSalesPartNo());
        }
//        String catalogDesc = "TRUE";
//        if (StringUtils.isNotBlank(salesPartDTO.getSalesPartDesc())) {
//            catalogDesc += "%" + salesPartDTO.getSalesPartDesc() + "%;";
//        }
//        if (StringUtils.isNotBlank(salesPartDTO.getModel())) {
//            catalogDesc += "%" + salesPartDTO.getModel() + "%;";
//        }
//        if (StringUtils.isNotBlank(salesPartDTO.getSpecification())) {
//            catalogDesc += "%" + salesPartDTO.getSpecification() + "%;";
//        }
//        if (StringUtils.isNotBlank(salesPartDTO.getVoltageLevel())) {
//            catalogDesc += "%" + salesPartDTO.getVoltageLevel() + "%;";
//        }
//        if (catalogDesc.contains("%")) {
//            jsonObject.put("CATALOG_DESC", catalogDesc);
//        }
        jsonObject.put("ACTIVE", "Y");
        if (StringUtils.isNotBlank(salesPartDTO.getSalesPartDesc())) {
            jsonObject.put("CATALOG_DESC", salesPartDTO.getSalesPartDesc());
        }
        R result = ifsFeignClient.querySalesPartStd(jsonObject, true);
        if (result.getCode() == 0) {
            JSONObject data = (JSONObject) JSON.toJSON(result.getData());
            return R.ok(data.getJSONArray("LIST_INFO"), "OK");
        } else {
            return R.failed("IFS错误——" + result.getMsg());
        }
    }
 
    @Override
    public R syncIfsLineNo(List<Long> ids) {
        List<CustomerOrder> customerOrderList = baseMapper.selectList(Wrappers.<CustomerOrder>lambdaQuery().in(CustomerOrder::getId, ids));
        return queryCoInfoStd(customerOrderList);
 
    }
 
    @Override
    public R syncIfsLineNoAuto() {
        List<CustomerOrder> customerOrderList = baseMapper.selectList(Wrappers.<CustomerOrder>lambdaQuery()
                .isNotNull(CustomerOrder::getOtcLineNo).and(wapper -> wapper
                        .isNull(CustomerOrder::getIfsDeliveryNo).or()
                        .isNull(CustomerOrder::getIfsLineItemNo).or()
                        .isNull(CustomerOrder::getIfsLineNo)));
        return queryCoInfoStd(customerOrderList);
    }
 
    @Override
    public boolean batchUpdateSalePartNo(CustomerOrderDTO customerOrderDTO) {
        List<Long> ids = customerOrderDTO.getUpdateIds();
        if (CollectionUtil.isEmpty(ids)) {
            throw new RuntimeException("请选择客户订单行");
        }
        List<String> unitWhitMapList = customerOrderUnitWhiteListConfig.getUnitWhitListMap();
        for (Long id : ids) {
            CustomerOrder customerOrder = baseMapper.selectById(id);
            customerOrder.setSalesPartNo(customerOrderDTO.getSalesPartNo());
            customerOrder.setPartNo(customerOrderDTO.getPartNo());
            customerOrder.setSalesPartName(customerOrderDTO.getSalesPartName());
            customerOrder.setIfsSalesUnit(customerOrderDTO.getIfsSalesUnit());
            customerOrder.setIfsDeliveryNo(customerOrderDTO.getIfsDeliveryNo());
            customerOrder.setUnit(customerOrderDTO.getUnit());
            String unitConcat = customerOrder.getOtcUnit() + "_" + customerOrderDTO.getIfsSalesUnit();
            if (!customerOrder.getOtcUnit().equals(customerOrderDTO.getIfsSalesUnit()) && !unitWhitMapList.contains(unitConcat)) {
                //如果销售单位和ifs中销售单位不一样则不给保存A
                throw new RuntimeException("订单行销售单位和销售件销售计量单位不一致并且白名单中不存在对应关系");
            } else {
                customerOrder.setOtcPartSync(false);
                customerOrder.setBuyQtyDue(customerOrderDTO.getIfsConvFactor().multiply(customerOrder.getOtcQuantity()));
                if (BooleanUtil.isTrue(customerOrder.getIsDocument())) {
                    customerOrder.setCoState(CustomerOrderStateStringValues.PLAN);
                } else {
                    customerOrder.setCoState(CustomerOrderStateStringValues.TECHNOLOGYUNCHECK);
                }
                updateById(customerOrder);
            }
        }
        return true;
    }
 
    /**
     * 查询ifs行号的数据
     *
     * @param customerOrderList
     * @return
     */
    private R queryCoInfoStd(List<CustomerOrder> customerOrderList) {
        Map<String, CustomerOrder> customerOrderMap = customerOrderList.stream().collect(Collectors.toMap(CustomerOrder::getOtcLineNo, a -> a, (k1, k2) -> k1));
        String otcLineNos = "";
        for (CustomerOrder customerOrder : customerOrderList) {
            otcLineNos += new Long(customerOrder.getOtcLineNo()) + ";";
        }
        if (StringUtils.isBlank(otcLineNos)) {
            return R.ok().setMsg("同步0条");
        }
        R result = ifsFeignClient.queryCoInfoStd(new JSONObject().fluentPut("OTC_LINE_NO", otcLineNos), true);
        if (result.getCode() == 0) {
            int i = 0;
            JSONObject data = (JSONObject) JSON.toJSON(result.getData());
            JSONArray listInfo = data.getJSONArray("LIST_INFO");
            for (Object obj : listInfo) {
                JSONObject info = JSONObject.parseObject(obj.toString());
                String otcLineNo = info.getString("OTC_LINE_NO");
                if (customerOrderMap.get(otcLineNo) == null) {
                    continue;
                }
                CustomerOrder customerOrder = customerOrderMap.get(otcLineNo);
                customerOrder.setIfsDeliveryNo(info.getString("REL_NO"));
                customerOrder.setIfsLineItemNo("LINE_ITEM_NO");
                customerOrder.setIfsLineNo("LINE_NO");
                i += 1;
                baseMapper.updateById(customerOrder);
            }
            return R.ok().setMsg("同步" + i + "条");
        } else {
            return R.failed("IFS错误——" + result.getMsg());
        }
    }
 
 
    /**
     * @param ids
     * @return
     */
    @Override
    public String oa(List<Long> ids) {
        String msg = "";
        Map<String, String> mainFields = new HashMap<>();
        List<Map<String, String>> detailFieldList = new ArrayList<>();
        List<String> cpfzList = new ArrayList<>();
        Long customerId = null;
        List<CustomerOrderDTO> customerOrderDTOList = baseMapper.selectOrderDocAndPart(ids);
        for (CustomerOrderDTO customerOrderDTO : customerOrderDTOList) {
            if (!customerOrderDTO.getIsDocument() || customerOrderDTO.getTechnologyDocumentId() == null) {
                msg = "【otc行号:" + customerOrderDTO.getOtcLineNo() + "缺少工艺文件】";
                return msg;
            }
            if (StringUtils.isBlank(customerOrderDTO.getSalesPartNo())) {
                msg = "【otc行号:" + customerOrderDTO.getOtcLineNo() + "请先选择销售件】";
                return msg;
            }
            if (StringUtils.isBlank(customerOrderDTO.getDocName())) {
                msg = "【otc行号:" + customerOrderDTO.getOtcLineNo() + "工艺文件丢失】";
                return msg;
            }
            if (StringUtils.isBlank(customerOrderDTO.getPartName())) {
                msg = "【otc行号:" + customerOrderDTO.getOtcLineNo() + "工艺文件的零件丟失】";
                return msg;
            }
            Map<String, String> detailField = new HashMap<>();
            //合同otc行号
            detailField.put("otcxh", Objects.toString(customerOrderDTO.getOtcLineNo(), org.apache.commons.lang3.StringUtils.EMPTY));
            //零件编号
            detailField.put("ljh", Objects.toString(customerOrderDTO.getPartNo(), org.apache.commons.lang3.StringUtils.EMPTY));
            //零件名称
            detailField.put("ljmc", Objects.toString(customerOrderDTO.getPartName(), org.apache.commons.lang3.StringUtils.EMPTY));
            //产品分组
            detailField.put("cpfz", customerOrderDTO.getProductGroup());
            //产品名称
            detailField.put("cpmc", Objects.toString(customerOrderDTO.getProductName(), org.apache.commons.lang3.StringUtils.EMPTY));
            //规格型号
            detailField.put("cpgg", Objects.toString(customerOrderDTO.getSpecs(), org.apache.commons.lang3.StringUtils.EMPTY));
            //下单数量
            detailField.put("xssl", Objects.toString(customerOrderDTO.getBuyQtyDue(), org.apache.commons.lang3.StringUtils.EMPTY));
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            //希望交货日期
            detailField.put("qwjhrq", customerOrderDTO.getWantedDeliveryDate() != null ? formatter.format(customerOrderDTO.getWantedDeliveryDate()) : "");
            //电压等级
            detailField.put("dydj", Objects.toString(customerOrderDTO.getVoltAgeClass(), org.apache.commons.lang3.StringUtils.EMPTY));
            //外护颜色
            detailField.put("whys", Objects.toString(customerOrderDTO.getOuterColor(), org.apache.commons.lang3.StringUtils.EMPTY));
            //单位
            detailField.put("dw", Objects.toString(customerOrderDTO.getUnit(), org.apache.commons.lang3.StringUtils.EMPTY));
            customerId = customerOrderDTO.getCustomerId();
            cpfzList.add(customerOrderDTO.getProductGroup());
            detailFieldList.add(detailField);
        }
        Customer customer = customerMapper.selectById(customerId);
        //工艺文件展示连接
        mainFields.put("technology_document_id",
                "<a href='" + oaProperty.getDocumentUrl() + org.apache.commons.lang3.StringUtils.join(ids, ",") +
                        "' target='_blank'>工艺详情</a>");
        mainFields.put("contract_no", Objects.toString(customer.getContractNo(), org.apache.commons.lang3.StringUtils.EMPTY));
        mainFields.put("customer_no", Objects.toString(customer.getCustomerNo(), org.apache.commons.lang3.StringUtils.EMPTY));
        mainFields.put("customer_name", Objects.toString(customer.getCustomerName(), org.apache.commons.lang3.StringUtils.EMPTY));
        mainFields.put("cpfz", org.apache.commons.lang3.StringUtils.join(cpfzList, ","));
        mainFields.put("source", "customerOrder");
        String requestName = "工艺审批流程";
        String createrId = SecurityUtils.getUser().getUsername();
        String workflowId = oaProperty.getCustomerOrderOaId();
 
        try {
            OAResult oaResult = OAProcess.start(mainFields, detailFieldList, requestName, workflowId, createrId);
            //OA流程发起成功,状态变成待审批 ,订单和工艺文件同步进行
            if (oaResult.success()) {
                List<CustomerOrder> CustomerOrderList = new ArrayList<>();
                for (Long id : ids) {
                    CustomerOrder customerOrder = new CustomerOrder();
                    customerOrder.setId(id);
                    customerOrder.setOaWorkflowId(oaResult.getAddWorkflowResult());
                    customerOrder.setIsAudit(AuditStateStringValues.PENDING);
                    CustomerOrderList.add(customerOrder);
                }
                updateBatchById(CustomerOrderList);
                return "【客户订单号:" + customer.getCustomerNo() + "提交成功!】";
            } else {
                return "【客户订单号:" + customer.getCustomerNo() + "提交失败】" + oaResult.getErrorMsg();
            }
        } catch (Exception e) {
            return "【客户订单号:" + customer.getCustomerNo() + "提交失败】";
        }
    }
 
    /**
     * oa回调
     *
     * @param data
     * @return
     */
    @Override
    public OACallBackResult oaResultCallBack(String data) {
        OACallBackResult oaCallBackResult = new OACallBackResult();
        oaCallBackResult.setMessage(oaReturnMsg(0, "success"));
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String requestId = jsonObject.getLong("requestId").toString();
            String checkResult = jsonObject.getString("CHECKRESULT");
            String source = jsonObject.getString("source");
            oaCallBackResult.setResult(checkResult);
            oaCallBackResult.setSource(source);
            oaCallBackResult.setWorkflowId(requestId);
            docAuditChange(requestId, checkResult, source);
        } catch (Exception e) {
            oaCallBackResult.setMessage(oaReturnMsg(1, e.getMessage()));
        } finally {
            return oaCallBackResult;
        }
    }
 
    private String oaReturnMsg(int code, String msg) {
        return "<miap><miap-header><errorcode>" + code + "</errorcode><errormsg>" + msg + "</errormsg></miap-header><miap-Body></miap-Body></miap>";
    }
 
    /**
     * 主需求的OA回调 0 :退回 1 :通过
     * source = customerOrder 客户订单工艺审批
     * source = masterProductionSchedule 生产计划工艺审批
     *
     * @return
     */
    private void docAuditChange(String oaWorkflowId, String checkResult, String source) {
        try {
            //通过的话客户订单
            if (source.equals("customerOrder")) {
                List<CustomerOrder> customerOrderList = getBaseMapper().selectList(Wrappers.<CustomerOrder>lambdaQuery().eq(CustomerOrder::getOaWorkflowId, oaWorkflowId));
                for (CustomerOrder customerOrder : customerOrderList) {
                    Document document = documentMapper.selectById(customerOrder.getTechnologyDocumentId());
                    if (checkResult.equals("1")) {
                        //通过
                        customerOrderDocAccept(customerOrder, document);
                    } else {
                        //不通过的话
                        customerOrderDocReject(customerOrder, document);
                    }
                }
            }
            //生产计划
            if (source.equals("masterProductionSchedule")) {
                MasterProductionSchedule masterProductionSchedule = masterProductionScheduleMapper.selectOne(Wrappers.<MasterProductionSchedule>lambdaQuery().eq(MasterProductionSchedule::getOaWorkflowId, oaWorkflowId));
                Document document = documentMapper.selectById(masterProductionSchedule.getTechnologyDocumentId());
                if (checkResult.equals("1")) {
                    masterProductionScheduleDocAccept(masterProductionSchedule, document);
                } else {
                    //不通过的话
                    masterProductionScheduleDocReject(masterProductionSchedule, document);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("回调异常:" + e.getMessage());
        }
    }
 
    /**
     * 客户订单工艺审批通过后执行
     *
     * @param customerOrder
     * @param document
     */
    @Async
    public void customerOrderDocAccept(CustomerOrder customerOrder, Document document) {
        customerOrder = customerOrderUtil.updateCustomerOrderLine(customerOrder);
//        pushPartNoToOtc(customerOrder);
        docAccept(customerOrder, document);
    }
 
    /**
     * 根据工艺文件id 将工艺文件改为接口,将BOM和工艺路线都改为已接收
     *
     * @param document document
     */
    @Override
    public void docAccept(CustomerOrder customerOrder, Document document) {
        if (null != document) {
            changeAllDocState(customerOrder, document);
        } else {
            customerOrder.setIsAudit(AuditStateStringValues.ACCEPTED);
            baseMapper.updateById(customerOrder);
        }
    }
 
    private void changeAllDocState(CustomerOrder customerOrder, Document document) {
        //修改主表的状态
        customerOrder.setIsAudit(AuditStateStringValues.ACCEPTED);
        baseMapper.updateById(customerOrder);
        //document.setState(DocumentStateStringValues.ACCEPTED);
        //documentService.saveOrUpdate(document);
        //将工艺文件BOM和工艺路线的状态都改为已接收
        List<JoinDocumentBomRouting> joinDocumentBomRoutingList = joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery().eq(JoinDocumentBomRouting::getDocumentId, document.getId()));
        joinDocumentBomRoutingList.forEach(joinDocumentBomRouting -> {
            //将BOM改为已接收
            if (joinDocumentBomRouting.getBomId() != null) {
                Bom bom = bomMapper.selectById(joinDocumentBomRouting.getBomId());
                bom.setState(BomStates.ACCEPTED.getValue());
                bomMapper.updateById(bom);
            }
            //将工艺路线改为已接收
            if (joinDocumentBomRouting.getRoutingId() != null) {
                Routing routing = routingMapper.selectById(joinDocumentBomRouting.getRoutingId());
                routing.setState(RoutingStates.ACCEPTED.getValue());
                routingMapper.updateById(routing);
            }
        });
    }
 
 
    private void expectionCustomerOrder(CustomerOrder customerOrder, Document document) {
        //修改主表的状态
        customerOrder.setIsAudit(AuditStateStringValues.EXPECT);
        baseMapper.updateById(customerOrder);
        document.setState(DocumentStateStringValues.REJECT);
        documentService.saveOrUpdate(document);
    }
 
    private void expectionMasterSchdule(MasterProductionSchedule masterProductionSchedule, Document document) {
        //修改主表的状态
        masterProductionSchedule.setIsAudit(AuditStateStringValues.EXPECT);
        masterProductionScheduleMapper.updateById(masterProductionSchedule);
        document.setState(DocumentStateStringValues.REJECT);
        documentService.saveOrUpdate(document);
    }
 
    /**
     * 客户订单工艺审批退回后执行
     *
     * @param customerOrder
     * @param document
     */
    @Async
    public void customerOrderDocReject(CustomerOrder customerOrder, Document document) {
        customerOrder.setIsAudit(AuditStateStringValues.REJECT);
        document.setState(DocumentStates.REJECT.getValue());
        baseMapper.updateById(customerOrder);
        documentMapper.updateById(document);
    }
 
    @Override
    public boolean pushotc(List<Long> ids, String pathCode) {
        if (pathCode.equals("0")) {
            for (Long id : ids) {
                CustomerOrder customerOrder = baseMapper.selectById(id);
                pushotc(customerOrder);
            }
        } else if (pathCode.equals("1")) {
            for (Long id : ids) {
                CustomerOrderForJointStockCompany customerOrderForJointStockCompany = customerOrderForJointStockCompanyMapper.selectById(id);
                pushotc(customerOrderForJointStockCompany);
            }
        } else {
            throw new RuntimeException("业务路径码 = 【" + pathCode + "】非法");
        }
 
        return true;
    }
 
    @Override
    public boolean pushotc(CustomerOrder customerOrder) {
        if (StringUtils.isBlank(customerOrder.getSalesPartNo())) {
            throw new RuntimeException(customerOrder.getOtcLineNo() + " 请选择销售件号");
        }
        String token = customerOrderUtil.getToken();
        customerOrder = customerOrderUtil.updateCustomerOrderLine(customerOrder);
        JSONArray jsonArray = new JSONArray().fluentAdd(new JSONObject()
                .fluentPut("orderId", customerOrder.getOtcOrderId())
                .fluentPut("lineId", new Long(customerOrder.getOtcLineNo()))
                .fluentPut("partNo", customerOrder.getSalesPartNo())
                .fluentPut("version", customerOrder.getVersion()));
        String str = HttpRequest.post(customerOrderClientConfigure.getOtcHost() + customerOrderClientConfigure.getOtcPushPartNoUrl())
                .contentType("application/json")
                .header("Authorization", "Bearer " + token).body(JSONArray.toJSONString(jsonArray)).execute().body();
        JSONObject result = JSONObject.parseObject(str);
        if (result.getInteger("code") != 0) {
            throw new RuntimeException(customerOrder.getOtcLineNo() + "  OTC推送失败:错误编号" + result.getInteger("code") + "  错误信息:" + result.getString("msg"));
        } else {
            customerOrder.setOtcPartSync(true);
            baseMapper.updateById(customerOrder);
        }
        return true;
    }
 
    @Override
    public boolean pushotc(CustomerOrderForJointStockCompany customerOrder) {
        if (StringUtils.isBlank(customerOrder.getSalesPartNo())) {
            throw new RuntimeException(customerOrder.getOtcLineNo() + " 请选择销售件号");
        }
        String token = customerOrderUtil.getToken();
        customerOrder = customerOrderUtil.updateCustomerOrderLineForJointStockCompany(customerOrder);
        JSONArray jsonArray = new JSONArray().fluentAdd(new JSONObject()
                .fluentPut("orderId", customerOrder.getOtcOrderId())
                .fluentPut("lineId", new Long(customerOrder.getOtcLineNo()))
                .fluentPut("partNo", customerOrder.getSalesPartNo())
                .fluentPut("version", customerOrder.getVersion()));
        String str = HttpRequest.post(customerOrderClientConfigure.getOtcHost() + customerOrderClientConfigure.getOtcPushPartNoUrl())
                .contentType("application/json")
                .header("Authorization", "Bearer " + token).body(JSONArray.toJSONString(jsonArray)).execute().body();
        JSONObject result = JSONObject.parseObject(str);
        if (result.getInteger("code") != 0) {
            throw new RuntimeException(customerOrder.getOtcLineNo() + "  OTC推送失败:错误编号" + result.getInteger("code"));
        } else {
            customerOrder.setOtcPartSync(true);
            customerOrderForJointStockCompanyMapper.updateById(customerOrder);
        }
        return true;
    }
 
    /**
     * 零件编号推送到订单
     *
     * @param customerOrder
     */
    private void pushPartNoToOtc(CustomerOrder customerOrder) {
        try {
            if (StringUtils.isNotBlank(customerOrder.getSalesPartNo())) {
                String token = customerOrderUtil.getToken();
                JSONArray jsonArray = new JSONArray().fluentAdd(new JSONObject()
                        .fluentPut("lineId", new Long(customerOrder.getOtcLineNo()))
                        .fluentPut("orderId", customerOrder.getOtcOrderId())
                        .fluentPut("partNo", customerOrder.getSalesPartNo())
                        .fluentPut("version", customerOrder.getVersion()));
                String str = HttpRequest.post(customerOrderClientConfigure.getOtcHost() + customerOrderClientConfigure.getOtcPushPartNoUrl())
                        .contentType("application/json")
                        .header("Authorization", "Bearer " + token).body(JSONArray.toJSONString(jsonArray)).execute().body();
                JSONObject result = JSONObject.parseObject(str);
                if (result.getInteger("code") == 0) {
                    customerOrder.setOtcPartSync(true);
                    baseMapper.updateById(customerOrder);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("token获取异常");
        }
    }
 
    /**
     * 生产计划工艺审批通过后执行
     *
     * @param masterProductionSchedule
     * @param document
     */
    @Async
    public void masterProductionScheduleDocAccept(MasterProductionSchedule masterProductionSchedule, Document document) {
        //修改主表的状态
        masterProductionSchedule.setIsAudit(AuditStateStringValues.ACCEPTED);
        masterProductionScheduleMapper.updateById(masterProductionSchedule);
        document.setState(DocumentStateStringValues.ACCEPTED);
        documentService.saveOrUpdate(document);
        //将工艺文件BOM和工艺路线的状态都改为已接收
        List<JoinDocumentBomRouting> joinDocumentBomRoutingList = joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery().eq(JoinDocumentBomRouting::getDocumentId, document.getId()));
        joinDocumentBomRoutingList.forEach(joinDocumentBomRouting -> {
            //将BOM改为已接收
            if (joinDocumentBomRouting.getBomId() != null) {
                Bom bom = bomMapper.selectById(joinDocumentBomRouting.getBomId());
                bom.setState(BomStates.ACCEPTED.getValue());
                bomMapper.updateById(bom);
            }
            //将工艺路线改为已接收
            if (joinDocumentBomRouting.getRoutingId() != null) {
                Routing routing = routingMapper.selectById(joinDocumentBomRouting.getRoutingId());
                routing.setState(RoutingStates.ACCEPTED.getValue());
                routingMapper.updateById(routing);
            }
        });
    }
 
    /**
     * 生产计划工艺审批退回后执行
     *
     * @param masterProductionSchedule
     * @param document
     */
    @Async
    public void masterProductionScheduleDocReject(MasterProductionSchedule masterProductionSchedule, Document document) {
        masterProductionSchedule.setIsAudit(AuditStateStringValues.REJECT);
        document.setState(DocumentStates.REJECT.getValue());
        masterProductionScheduleMapper.updateById(masterProductionSchedule);
        documentMapper.updateById(document);
    }
 
    @Override
    public R getOtcCustomerOrderFileList(String customerOrderNo) {
        return customerOrderUtil.getOtcCustomerOrderFileList(customerOrderNo);
    }
 
 
    @Override
    public boolean changeAudit(List<Long> ids, String isAudit) {
        List<CustomerOrder> customerOrderList = baseMapper.selectList(Wrappers.<CustomerOrder>lambdaQuery().in(CustomerOrder::getId, ids));
        for (CustomerOrder customerOrder : customerOrderList) {
            if (isAudit.equals(customerOrder.getIsAudit())) {
                continue;
            }
            changeAudit(customerOrder, isAudit);
        }
        return true;
    }
 
 
    @Override
    public void export(HttpServletResponse response, QueryWrapper<CustomerOrderDTO> wrapper) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("客户订单导出", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        try {
            //新建ExcelWriter
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
            //获取sheet0对象
            WriteSheet mainSheet = EasyExcel.writerSheet(0, "导出").head(CustomerOrderData.class).build();
            //向sheet0写入数据 传入空list这样只导出表头
            List<CustomerOrderData> customerOrderDataList = getExcelData(wrapper);
            excelWriter.write(customerOrderDataList, mainSheet);
            //关闭流
            excelWriter.finish();
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }
 
 
    private List<CustomerOrderData> getExcelData(QueryWrapper<CustomerOrderDTO> wrapper) {
        List<CustomerOrderData> customerOrderDataList = baseMapper.getExport(wrapper);
        for (CustomerOrderData customerOrderData : customerOrderDataList) {
            List<CustomerOrderParam> customerOrderParamList = customerOrderParamMapper.selectList(Wrappers.<CustomerOrderParam>lambdaQuery()
                    .isNotNull(CustomerOrderParam::getField)
                    .isNotNull(CustomerOrderParam::getValue)
                    .eq(CustomerOrderParam::getOrderId, customerOrderData.getId()));
            Map<String, String> map = customerOrderParamList.stream().collect(Collectors.toMap(CustomerOrderParam::getField, CustomerOrderParam::getValue));
            customerOrderData.setCoState(getCoStateValue(customerOrderData.getCoState()));
            customerOrderData.setIsAudit(getIsAuditValue(customerOrderData.getIsAudit()));
            customerOrderData.setContractEntity(map.get("contractEntity"));
            customerOrderData.setProductType(map.get("productType"));
            customerOrderData.setUnitPrice(map.get("unitPrice"));
            customerOrderData.setAmount(map.get("amount"));
            customerOrderData.setReceivingContact(map.get("receivingContact"));
            customerOrderData.setReceivingContactPhone(map.get("receivingContactPhone"));
        }
        return customerOrderDataList;
    }
 
    private String getIsAuditValue(String key) {
        switch (key) {
            case AuditStateStringValues.ACCEPTED:
                return "通过";
            case AuditStateStringValues.DRAFT:
                return "草稿";
            case AuditStateStringValues.PENDING:
                return "审核中";
            case AuditStateStringValues.REJECT:
                return "退回";
            case AuditStateStringValues.EXPECT:
                return "异常";
            default:
                return "";
        }
    }
 
    private String getCoStateValue(String key) {
        switch (key) {
            case CustomerOrderStateStringValues.PARTUNCHECKED:
                return "零件待选";
            case CustomerOrderStateStringValues.TECHNOLOGYUNCHECK:
                return "工艺文件待选";
            case CustomerOrderStateStringValues.PLAN:
                return "待计划";
            case CustomerOrderStateStringValues.PLANED:
                return "已下发";
            case CustomerOrderStateStringValues.CANCEL:
                return "已作废";
            case CustomerOrderStateStringValues.UNIEDIT:
                return "零件编辑";
            default:
                return "";
        }
    }
 
 
    /**
     * 查询属性
     *
     * @param key
     * @param value
     * @return
     */
    @Override
    public List<String> queryPartPropertiesStd(String key, String value) {
        List<String> answer2 = new ArrayList<>();
        Pattern regex = Pattern.compile(value);
        if (!captchaCacheService.exists(PART_PROPERTY + "_" + key)) {
            cachePartProperty();
        }
        List<String> stringList = new ArrayList<>();
        String str = captchaCacheService.get(PART_PROPERTY + "_" + key);
        if (str == null || str.equals("")) {
            return null;
        }
        stringList = Arrays.asList(str.split(","));
        for (String revalue : stringList) {
            if (regex.matcher(revalue).find()) {
                answer2.add(revalue);
            }
            if (answer2.size() > 19) {
                break;
            }
        }
        return answer2;
    }
 
    @Override
    public R uploadProcessConfigFile(MultipartFile file, String orderNumber, String lineNumber) {
        String fileName = FileUtil.extName(file.getOriginalFilename());
        try {
            OrderProcessConfigFile configFile = new OrderProcessConfigFile();
            configFile.setFileName(fileName);
            configFile.setOriginalFileName(file.getOriginalFilename());
            configFile.setOrderNumber(orderNumber);
            configFile.setLineNumber(lineNumber);
            configFile.setBucketName(FileSaveUtil.StoreFile(file));
            orderProcessConfigFileMapper.insert(configFile);
            ProcessConfigFileOrderMapping mapping = ProcessConfigFileOrderMapping.builder().configFileId(configFile.getId())
                    .orderNumber(orderNumber).lineNumber(lineNumber).build();
            processConfigFileOrderMappingMapper.insert(mapping);
            return R.ok();
        } catch (Exception e) {
            log.error("上传失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.failed(e.getLocalizedMessage());
        }
    }
 
    @Override
    public List<OrderProcessConfigFileDTO> getProcessConfigFiles(String orderNumber, String lineNumber) {
        return orderProcessConfigFileMapper.getProcessConfigFiles(orderNumber, lineNumber);
    }
 
    @Deprecated
    @Override
    public boolean updateRange(Long id, String range) {
        orderProcessConfigFileMapper.updateRange(id, range);
        return true;
    }
 
    @Override
    public void getFile(String bucket, String fileName, HttpServletResponse response) {
        try {
            String path = FileSaveUtil.FILE_PATH + bucket;
            InputStream inputStream = new FileInputStream(path);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IoUtil.copy(inputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("文件读取异常: {}", e.getLocalizedMessage());
        }
    }
 
    @Override
    public R deleteProcessConfigFile(Long id) {
        try {
            OrderProcessConfigFile configFile = orderProcessConfigFileMapper.selectById(id);
            String filePath=FileSaveUtil.FILE_PATH+"//"+configFile.getBucketName();
            boolean del = FileUtil.del(new File(filePath));
            //minioTemplate.removeObject(configFile.getBucketName(), configFile.getFileName());
            orderProcessConfigFileMapper.deleteById(id);
            processConfigFileOrderMappingMapper.delete(Wrappers.<ProcessConfigFileOrderMapping>lambdaQuery().eq(ProcessConfigFileOrderMapping::getConfigFileId, id));
            return R.ok();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return R.failed(e.getMessage());
        }
    }
 
    @Override
    public Boolean fileAssociatedOrder(FileAssociatedOrderDTO fileAssociatedOrderDTO) {
        Long configFileId = fileAssociatedOrderDTO.getConfigFileId();
        List<ProcessConfigFileOrderMapping> mappingList =
                fileAssociatedOrderDTO.getCustomerOrderList().stream().map(s -> ProcessConfigFileOrderMapping.builder().configFileId(configFileId)
                        .orderNumber(s.getCustomerOrderNo()).lineNumber(s.getOtcLineNo()).build()).collect(Collectors.toList());
        processConfigFileOrderMappingMapper.delete(Wrappers.<ProcessConfigFileOrderMapping>lambdaQuery()
                .eq(ProcessConfigFileOrderMapping::getConfigFileId, configFileId));
        return processConfigFileOrderMappingService.saveBatch(mappingList);
    }
 
    @Override
    public List<ProcessConfigFileOrderMapping> processConfigMapping(Long id) {
        return processConfigFileOrderMappingMapper.selectList(Wrappers.<ProcessConfigFileOrderMapping>lambdaQuery()
                .eq(ProcessConfigFileOrderMapping::getConfigFileId, id));
    }
 
    @Override
    public void exportCustomerOrderSplit(HttpServletResponse response, CustomerOrderExportDTO customerOrderExportDTO) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("客户订单箱码导出", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
        try {
            //新建ExcelWriter
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
            //获取sheet0对象
            WriteSheet mainSheet = EasyExcel.writerSheet(0, "TM").head(CustomerOrderExportDTO.class).build();
            //向sheet0写入数据 传入空list这样只导出表头
            List<CustomerOrderExportDTO> customerOrderExportDTOList = getCustomerOrderExportList(customerOrderExportDTO);
            excelWriter.write(customerOrderExportDTOList, mainSheet);
            //关闭流
            excelWriter.finish();
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }
 
    private List<CustomerOrderExportDTO> getCustomerOrderExportList(CustomerOrderExportDTO customerOrderExportDTO) {
        CustomerOrderExportData exportData =
                customerOrderMapper.getCustomerOrderExportData(customerOrderExportDTO.getId());
        String currentDate = DateUtil.format(new Date(), "yyyy/MM/dd");
        String dateCode = DateUtil.format(new Date(), "yyMM");
        if (exportData.getOtcQuantity() == null) {
            throw new RuntimeException("没有OTC销售数量");
        }
        BigDecimal count = exportData.getOtcQuantity().divide(customerOrderExportDTO.getSplitQuantity(), 0,
                RoundingMode.CEILING);
        List<CustomerOrderExportDTO> resultList = new ArrayList<>();
        List<PackageCodeCustomerOrderRelation> relationList = new ArrayList<>();
        Integer tail = 1;
        // 查询目前最大的箱码数
        Integer maxTail = packageCodeCustomerOrderRelationMapper.getMaxTail(customerOrderExportDTO.getTitle() + dateCode);
        if (maxTail != null) {
            tail = maxTail + 1;
        }
        for (int i = 0; i < count.intValue(); i++) {
            BigDecimal splitQuantity = customerOrderExportDTO.getSplitQuantity().stripTrailingZeros();
            if (i == count.intValue() - 1) {
                splitQuantity =
                        exportData.getOtcQuantity().subtract(customerOrderExportDTO.getSplitQuantity().multiply(count.subtract(BigDecimal.ONE))).stripTrailingZeros();
            }
 
            CustomerOrderExportDTO exportDTO = CustomerOrderExportDTO.builder()
                    .orderNo(exportData.getCustomerOrderNo())
                    .currentDate(currentDate)
                    .dateCode(dateCode)
                    .spec(StringUtils.isNotBlank(exportData.getPartName()) ? exportData.getPartName().replace(
                            "馈线跳线",
                            StringUtils.EMPTY).trim() : StringUtils.EMPTY)
                    .quantity(String.format("%02d", splitQuantity.longValue()))
                    .title(customerOrderExportDTO.getTitle())
                    .tail(tail.toString())
                    .packageCode(customerOrderExportDTO.getTitle() + dateCode + String.format("%02d", splitQuantity.longValue()) + tail)
                    .build();
            PackagingExportQrCodeData qrCodeData = PackagingExportQrCodeData.builder()
                    .partNo(exportData.getPartNo()).lotBatchNo("*").qtyArrived(splitQuantity.toPlainString())
                    .wdr(exportDTO.getPackageCode()).unitMeas(exportData.getOtcUnit()).packageCode(exportDTO.getPackageCode())
                    .materialCode(exportData.getCusMaterialCode()).build();
            exportDTO.setQrCode(JSON.toJSONString(qrCodeData, SerializerFeature.WriteNullStringAsEmpty));
            resultList.add(exportDTO);
            PackageCodeCustomerOrderRelation orderRelation =
                    PackageCodeCustomerOrderRelation.builder().customerOrderId(customerOrderExportDTO.getId()).customerOrderNo(exportData.getCustomerOrderNo())
                            .otcLineNo(exportData.getOtcLineNo()).packageCode(exportDTO.getPackageCode()).build();
            relationList.add(orderRelation);
            tail++;
        }
        try {
            packageCodeCustomerOrderRelationService.saveBatch(relationList);
        } catch (DuplicateKeyException e) {
            throw new RuntimeException("箱码重复,请重新导出");
        }
        return resultList;
    }
 
 
    public void cachePartProperty() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ATTRIBUTE", "规格;型号;电压等级");
        //设置缓存时间
        Long seconds = new Long(600);
        R result = ifsFeignClient.queryPartPropertiesStd(jsonObject, true);
        if (result.getCode() == 0) {
            JSONObject data = (JSONObject) JSON.toJSON(result.getData());
            JSONArray jsonArray = data.getJSONArray("LIST_INFO");
            Map<String, List<String>> map = new HashMap<>();
            if (CollectionUtil.isNotEmpty(jsonArray)) {
                List<JSONObject> jsonObjects = JSONObject.parseArray(jsonArray.toJSONString(), JSONObject.class);
                map = jsonObjects.stream().collect(Collectors.groupingBy(item -> item.getString("ATTRIBUTE"),
                        Collectors.mapping(a -> a.getString("ATTRIBUTE_VALUE"), Collectors.toList())));
            }
            if (CollectionUtil.isNotEmpty(map.get("规格"))) {
                List<String> list = map.get("规格").stream().distinct().collect(Collectors.toList());
                captchaCacheService.set(PART_PROPERTY + "_规格", list.toString(), seconds);
            }
            if (CollectionUtil.isNotEmpty(map.get("型号"))) {
                List<String> list = map.get("型号").stream().distinct().collect(Collectors.toList());
                captchaCacheService.set(PART_PROPERTY + "_型号", list.toString(), seconds);
            }
            if (CollectionUtil.isNotEmpty(map.get("电压等级"))) {
                List<String> list = map.get("电压等级").stream().distinct().collect(Collectors.toList());
                captchaCacheService.set(PART_PROPERTY + "_电压等级", list.toString(), seconds);
            }
        }
    }
 
    /**
     * 添加主表信息(股份公司)
     *
     * @param selectTime 时间
     * @param token      token
     * @return
     */
    private R addCustomerFromOtcForJointStockCompany(String selectTime, String token) {
        try {
            Map<String, Object> map = new HashMap<>();
            if (StringUtils.isNotBlank(selectTime)) {
                map.put("selectTime", selectTime);
            }
            String str = HttpRequest.get(customerOrderClientConfigure.getOtcHost() + customerOrderClientConfigure.getOtcCustomerUrl())
                    .contentType("application/json")
                    .header("Authorization", "Bearer " + token).form(map).execute().body();
            JSONObject result = JSONObject.parseObject(str);
            //主表参数表
            List<OrderParam> orderParams = orderParamService.list();
            if (result.getInteger("code") == 0) {
                int num = 0;
                int detailNum = 0;
                JSONArray jsonArray = result.getJSONArray("data");
                for (Object obj : jsonArray) {
                    JSONObject customerJSONObject = JSONObject.parseObject(obj.toString());
                    //合同编号
                    String contractNo = customerJSONObject.getString("orderNo");
                    //主表在OTC中的状态
                    String otcMainStatus = customerJSONObject.getString("status");
                    //所属公司
                    String affiliatedCompany = customerJSONObject.getString("affiliatedCompany");
                    // 不在这几个状态中的数据就跳过
                    if (!Arrays.asList(CustomerOrderStateStringValues.GETOTCSTATE).contains(otcMainStatus)) {
                        continue;
                    }
                    CustomerForJointStockCompany customer = customerForJointStockCompanyMapper.selectOne(Wrappers.<CustomerForJointStockCompany>lambdaQuery().eq(CustomerForJointStockCompany::getContractNo, contractNo));
                    if (customer == null) {
                        customer = new CustomerForJointStockCompany();
                    }
                    //如果OTC中主表状态是取消那就跳过或者删除已经同步的数据
                    if (otcMainStatus.equals("已取消")) {
                        if (customer.getId() != null) {
                            customerForJointStockCompanyMapper.deleteById(customer.getId());
                            customerOrderForJointStockCompanyMapper.delete(Wrappers.<CustomerOrderForJointStockCompany>lambdaQuery().eq(CustomerOrderForJointStockCompany::getCustomerId, customer.getId()));
                        }
                        continue;
                    }
                    if (null == affiliatedCompany || !Arrays.asList("已审核", "已下达").contains(otcMainStatus) || !affiliatedCompany.equals("江苏中天科技股份有限公司")) {
                        continue;//只获取OTC中已审核的,且所属公司为股份公司的
                    }
                    //客户编号
                    customer.setCustomerNo(customerJSONObject.getString("customerNo"));
                    //合同号
                    customer.setContractNo(contractNo);
                    //客户合同号
                    customer.setCustomerContractNo(customerJSONObject.getString("customerContractNumber"));
                    //客户名称
                    customer.setCustomerName(customerJSONObject.getString("customerName"));
                    //工程名称
                    customer.setEntityName(customerJSONObject.getString("projectName"));
                    //交货日期
                    customer.setDeliveryDate(customerJSONObject.get("wantedDeliveryDate") != null ?
                            customerJSONObject.getDate("wantedDeliveryDate").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null);
                    //事业部
                    customer.setSalesDepartment(customerJSONObject.getString("division"));
                    //省份
                    customer.setProvince(customerJSONObject.getString("province"));
                    //业务员名称
                    customer.setSalesMan(customerJSONObject.getString("salesmanName"));
                    //业务员编号
                    customer.setSalerWorkCode(customerJSONObject.getString("salesmanNo"));
                    //正本状态
                    customer.setOriginalContractStatus(customerJSONObject.getString("originalStatus"));
                    //合同正本状态
                    customer.setReturnStatus(customerJSONObject.getString("returnStatus"));
                    //项目性质
                    customer.setIsCp(customerJSONObject.getString("natureOfProjectExecution"));
                    //下单日期
                    customer.setPlaceOrderDate(customerJSONObject.getDate("orderDate").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    //审核日期
                    customer.setVerifyDate(customerJSONObject.get("reviewTime") != null ?
                            customerJSONObject.getDate("reviewTime").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null);
                    //工厂下单日期
                    customer.setFactoryPlaceOrderDate(customerJSONObject.get("factoryOrderDate") != null ?
                            customerJSONObject.getDate("factoryOrderDate").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime() : null);
 
                    //备注
                    customer.setComment(customerJSONObject.getString("comment"));
 
                    if (customer.getId() == null) {
                        customerForJointStockCompanyMapper.insert(customer);
                    } else {
                        customerForJointStockCompanyMapper.updateById(customer);
                    }
                    num += 1;
 
                    detailNum += addCustomerOrderFromOtcForJointStockCompany(customerJSONObject, customer, token, orderParams);
                }
                return R.ok().setMsg("同步或更新合同主体" + num + "条,合同明细" + detailNum + "条!");
            } else {
                return R.failed("订单主体获取失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
 
    /**
     * 添加子表信息(股份公司)
     *
     * @param customer
     * @throws
     */
    private int addCustomerOrderFromOtcForJointStockCompany(JSONObject customerJSONObject, CustomerForJointStockCompany customer, String token, List<OrderParam> orderParamList) {
        int num = 0;
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("orderNo", customer.getContractNo());
            map.put("selectTime", "1899-12-31 23:59:59");
            JSONObject result = JSONObject.parseObject(HttpRequest.get(customerOrderClientConfigure.getOtcHost() + customerOrderClientConfigure.getOtcCustomerOrderUrl())
                    .contentType("application/json")
                    .header("Authorization", "Bearer " + token).form(map).execute().body());
            if (result.getInteger("code") == 0) {
                JSONArray jsonArray = result.getJSONArray("data");
                for (Object obj : jsonArray) {
                    JSONObject customerOrderJSONObject = JSONObject.parseObject(obj.toString());
                    String otcLoneId = customerOrderJSONObject.getLong("id").toString();
                    //OTC的订单状态
                    String otcOrderStatus = customerOrderJSONObject.getString("lineStatus").toString();
                    CustomerOrderForJointStockCompany customerOrder = customerOrderForJointStockCompanyMapper.selectOne(Wrappers.<CustomerOrderForJointStockCompany>lambdaQuery()
                            .eq(CustomerOrderForJointStockCompany::getOtcLineNo, otcLoneId));
                    if (customerOrder == null) {
                        customerOrder = new CustomerOrderForJointStockCompany();
                    }
                    //如果这个单子在OTC中取消状态 那就删除
                    if (otcOrderStatus.equals("已取消")) {
                        if (customer.getId() != null) {
                            customerOrderForJointStockCompanyMapper.deleteById(customer.getId());
                        }
                        continue;
                    }
                    //OTC合同号主表id
                    customerOrder.setOtcOrderId(customerOrderJSONObject.getLong("orderId"));
                    //otc行号
                    customerOrder.setOtcLineNo(otcLoneId);
                    //零件号
                    customerOrder.setSalesPartNo(customerOrderJSONObject.getString("partNo"));
                    //来源
                    customerOrder.setSourceId("OTC");
                    //合同号
                    customerOrder.setCustomerOrderNo(customer.getContractNo());
                    //客户号
                    customerOrder.setCustomerNo(customer.getCustomerNo());
                    //客户名称
                    customerOrder.setCustomerName(customer.getCustomerName());
                    //销售数量原先OTC的单位
                    customerOrder.setOtcQuantity(customerOrderJSONObject.getBigDecimal("quantity"));
                    //OTC单位
                    customerOrder.setOtcUnit(customerOrderJSONObject.getString("unit"));
                    //期望交货日期
                    customerOrder.setWantedDeliveryDate(customer.getDeliveryDate());
                    //主表id
                    customerOrder.setCustomerId(customer.getId());
                    //电压等级
                    customerOrder.setVoltAgeClass(customerOrderJSONObject.getString("voltageLevel"));
                    //外呼颜色
                    customerOrder.setOuterColor(customerOrderJSONObject.getString("outerSheathColor"));
                    //客户零件名称
                    customerOrder.setProductName(customerOrderJSONObject.getString("productName"));
                    //客户零件规格
                    customerOrder.setCustomerPartSpec(customerOrderJSONObject.getString("specificationModel"));
                    //订单版本
                    customerOrder.setVersion(customerOrderJSONObject.getInteger("version"));
                    //事业部
                    customerOrder.setDivision(customerOrderJSONObject.getString("division"));
                    //印字类型
                    customerOrder.setPrintType(customerOrderJSONObject.getString("printType"));
                    //印字要求
                    customerOrder.setPrintingRequirements(customerOrderJSONObject.getString("printingRequirements"));
                    //包装要求
                    customerOrder.setPackageRequire(customerOrderJSONObject.getString("packageRequire"));
                    //质量要求
                    customerOrder.setQualityRequire(customerOrderJSONObject.getString("qualityRequire"));
                    //生产需求说明
                    customerOrder.setOtherProductRequire(customerOrderJSONObject.getString("otherProductRequire"));
                    //系统
                    customerOrder.setDivisionSystem(customerOrderJSONObject.getString("divisionSystem"));
                    //收货地址
                    customerOrder.setShippingAddress(customerOrderJSONObject.getString("shippingAddress"));
                    //业务员
                    customerOrder.setSalesmanName(customer.getSalesMan());
                    //盘长要求
                    customerOrder.setLengthRequirement(customerOrderJSONObject.getString("lengthRequirement"));
                    //备注
                    customerOrder.setRemark(customerOrderJSONObject.getString("comment"));
                    //零件是否推送
                    customerOrder.setOtcPartSync(false);
                    // 默认为N 数据字典为:N:普通,S:样品,D:研发
                    customerOrder.setManufactureAttr("N");
 
                    if (customerOrder.getId() == null) {
                        //是否关联工艺文件为否
                        customerOrder.setIsDocument(false);
                        //状态为 01plan
                        customerOrder.setCoState(CustomerOrderStateStringValues.PARTUNCHECKED);
                        //审核状态为 01draft 草稿
                        customerOrder.setIsAudit(AuditStateStringValues.DRAFT);
                        customerOrderForJointStockCompanyMapper.insert(customerOrder);
                    } else {
                        customerOrderForJointStockCompanyMapper.updateById(customerOrder);
                    }
                    addCustomerParaForJointStockCompany(customerJSONObject, customerOrderJSONObject, customerOrder, orderParamList);
                    num += 1;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("订单行数据获取失败,原因:" + e.getMessage());
        }
        return num;
    }
 
 
    @Override
    public R checkOA(List<Long> ids) {
        List<CustomerOrder> customerOrderListByAudit = baseMapper.selectList(Wrappers.<CustomerOrder>lambdaQuery()
                .in(CustomerOrder::getId, ids)
                .and(i -> i.eq(CustomerOrder::getIsAudit, AuditStateStringValues.PENDING)
                        .or().eq(CustomerOrder::getIsAudit, AuditStateStringValues.ACCEPTED)));
        if (CollectionUtil.isNotEmpty(customerOrderListByAudit)) {
            throw new RuntimeException("审核状态不可以是审核中和通过");
        }
        List<CustomerOrder> customerOrderListByIds = baseMapper.selectBatchIds(ids);
        Set<String> orderNoSet = customerOrderListByIds.stream().map(CustomerOrder::getCustomerOrderNo).collect(Collectors.toSet());
        List<String> otcLineNoList = customerOrderListByIds.stream().map(CustomerOrder::getOtcLineNo).collect(Collectors.toList());
        if (orderNoSet.size() != 1) {
            throw new RuntimeException("订单号不唯一");
        }
        Iterator iterator = orderNoSet.iterator();
        String orderNo = (String) iterator.next();
        List<CustomerOrder> customerOrderList = baseMapper.selectList(Wrappers.<CustomerOrder>lambdaQuery().eq(CustomerOrder::getCustomerOrderNo, orderNo));
        List<String> otcLineNoBySearchList = customerOrderList.stream().map(CustomerOrder::getOtcLineNo).collect(Collectors.toList());
        if (otcLineNoList.size() == otcLineNoBySearchList.size()) {
            return R.ok(CheckOADTO.builder().success(Boolean.TRUE).build());
        } else {
            otcLineNoBySearchList.removeAll(otcLineNoList);
            if (CollectionUtil.isNotEmpty(otcLineNoBySearchList)) {
                return R.ok(CheckOADTO.builder().success(Boolean.FALSE).message("以下行号未勾选,是否继续提交" + otcLineNoBySearchList.toString()).build());
            }
            return R.ok(CheckOADTO.builder().success(Boolean.TRUE).build());
        }
 
    }
 
 
    @Override
    public List<OADetailDTO> getOADetailDTO(List<Long> ids) {
        return baseMapper.getOADetail(ids);
    }
 
    @Override
    public R getProcessConfigFiles(String customerOrderNo) {
        List<OrderProcessConfigFileDTO> configFiles = orderProcessConfigFileMapper.getProcessConfigFilesByOrderNo(customerOrderNo);
        return R.ok(configFiles);
    }
 
    @Override
    public R getTechnologyDocument(Long technologyDocumentId) {
        return R.ok(documentMapper.getBomRoutingDtoByDocId(technologyDocumentId));
    }
 
    @Override
    public R getDocumentJgt(Long technologyDocumentId) {
        return R.ok(documentJgtMapper.selectList(Wrappers.<DocumentJgt>lambdaQuery()
                .eq(DocumentJgt::getDocumentId, technologyDocumentId)));
    }
 
    @Override
    public Boolean validatePackageCodeSnCustomerOrder(PackagingDTO packagingDTO) {
        Packaging packaging = packagingMapper.selectById(packagingDTO.getId());
        PackageCodeCustomerOrderRelation relation =
                packageCodeCustomerOrderRelationMapper.selectOne(Wrappers.<PackageCodeCustomerOrderRelation>lambdaQuery()
                        .eq(PackageCodeCustomerOrderRelation::getPackageCode, packaging.getNo()));
        if (null == relation) {
            return Boolean.TRUE;
        }
        if (CollectionUtil.isNotEmpty(packagingDTO.getStockList())) {
            for (Stock stock : packagingDTO.getStockList()) {
                CustomerOrder customerOrder =
                        customerOrderMapper.getCustomerOrderByProductOutput(stock.getPartBatchNo());
                if (null == customerOrder) {
                    continue;
                }
                if (!relation.getCustomerOrderId().equals(customerOrder.getId())) {
                    throw new RuntimeException("当前SN与箱码对应销售订单不一致");
                }
            }
        }
        return Boolean.TRUE;
    }
 
    @Override
    public void pushPartNoToOtc(OACallBackResult callBackResult) {
        if (org.apache.commons.lang3.StringUtils.equals("customerOrder", callBackResult.getSource()) && org.apache.commons.lang3.StringUtils.equals("1", callBackResult.getResult())) {
            List<CustomerOrder> customerOrderList =
                    getBaseMapper().selectList(Wrappers.<CustomerOrder>lambdaQuery().eq(CustomerOrder::getOaWorkflowId
                            , callBackResult.getWorkflowId()));
            for (CustomerOrder customerOrder : customerOrderList) {
                try {
                    if (StringUtils.isNotBlank(customerOrder.getSalesPartNo())) {
                        String token = customerOrderUtil.getToken();
                        JSONArray jsonArray = new JSONArray().fluentAdd(new JSONObject()
                                .fluentPut("lineId", new Long(customerOrder.getOtcLineNo()))
                                .fluentPut("orderId", customerOrder.getOtcOrderId())
                                .fluentPut("partNo", customerOrder.getSalesPartNo())
                                .fluentPut("version", customerOrder.getVersion()));
                        String str =
                                HttpRequest.post(customerOrderClientConfigure.getOtcHost() + customerOrderClientConfigure.getOtcPushPartNoUrl())
                                        .contentType("application/json")
                                        .header("Authorization", "Bearer " + token).body(JSONArray.toJSONString(jsonArray)).execute().body();
                        JSONObject result = JSONObject.parseObject(str);
                        if (result.getInteger("code") == 0) {
                            customerOrder.setOtcPartSync(true);
                            baseMapper.updateById(customerOrder);
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException("token获取异常");
                }
            }
        }
 
 
    }
 
    @Override
    public void pushCustomersToOtc(List<Long> ids, String isAudit) {
        List<CustomerOrder> customerOrderList = baseMapper.selectList(Wrappers.<CustomerOrder>lambdaQuery().in(CustomerOrder::getId, ids).eq(CustomerOrder::getOtcPartSync, false));
        if (StrUtil.equals(isAudit, AuditStateStringValues.ACCEPTED)) {
            for (CustomerOrder customerOrder : customerOrderList) {
                if (StrUtil.equals(customerOrder.getSourceId(), "OTC")) {
                    pushotc(customerOrder);
                }
            }
        }
    }
 
 
    @Override
    public void sendWxMsgAuto() {
        List<CustomerOrder> customerOrderList = baseMapper.selectList(Wrappers.<CustomerOrder>lambdaQuery()
                .eq(CustomerOrder::getCoState, "01partUnCheck")
                .eq(CustomerOrder::getIsSend, false));
        String commonString = "您好,以下销售订单行状态为零件待选,请及时处理:<br/>";
        String[] split;
        if (CollectionUtil.isNotEmpty(customerOrderList)) {
            List<CustomerOrder> signList = customerOrderList.stream().filter(a -> "信号".equals(a.getProductGroup())).collect(Collectors.toList());
            List<CustomerOrder> radioList = customerOrderList.stream().filter(a -> "射频".equals(a.getProductGroup())).collect(Collectors.toList());
            List<CustomerOrder> assemblyList = customerOrderList.stream().filter(a -> "组件".equals(a.getProductGroup())).collect(Collectors.toList());
            List<CustomerOrder> electricList = customerOrderList.stream().filter(a -> "光电".equals(a.getProductGroup())).collect(Collectors.toList());
            List<CustomerOrder> fixtureList = customerOrderList.stream().filter(a -> "卡具".equals(a.getProductGroup())).collect(Collectors.toList());
            List<CustomerOrder> temperatureList = customerOrderList.stream().filter(a -> "高温".equals(a.getProductGroup())).collect(Collectors.toList());
            List<CustomerOrder> engineList = customerOrderList.stream().filter(a -> "机车".equals(a.getProductGroup())).collect(Collectors.toList());
            List<CustomerOrder> otherList = customerOrderList.stream().filter(a -> "其他".equals(a.getProductGroup())).collect(Collectors.toList());
 
            //根据分组发送给对应负责人
            sendMsgByGroup(signList, wechatProperty.getSign());
            sendMsgByGroup(radioList, wechatProperty.getRadio());
            sendMsgByGroup(assemblyList, wechatProperty.getAssembly());
            sendMsgByGroup(electricList, wechatProperty.getElectric());
            sendMsgByGroup(fixtureList, wechatProperty.getFixture());
            sendMsgByGroup(temperatureList, wechatProperty.getTemperature());
            sendMsgByGroup(engineList, wechatProperty.getEngine());
            sendMsgByGroup(otherList, wechatProperty.getOther());
 
            //更新发送状态
            for (CustomerOrder customerOrder : customerOrderList) {
                customerOrder.setIsSend(true);
            }
            updateBatchById(customerOrderList);
        }
    }
 
 
    /**
     * 根据分组发送给对应负责人
     *
     * @param groupList
     * @param chargePeople
     * @return
     */
    void sendMsgByGroup(List<CustomerOrder> groupList, String chargePeople) {
        String commonString = "您好,以下销售订单行状态为零件待选,请及时处理:<br/>";
        String[] split;
        if (groupList.size() != 0) {
            int num = groupList.size() / 20;
            //发送数量超过20条
            for (int i = 0; i < num; i++) {
                StringBuilder builder = new StringBuilder(commonString);
                for (int j = 0; j < 20; j++) {
                    builder.append("订单号:").append(groupList.get(j + i * 20).getCustomerOrderNo()).append("<br/>")
                            .append("OTC行号:").append(groupList.get(j + i * 20).getOtcLineNo()).append("<br/>")
                            .append("产品分组:").append(groupList.get(j + i * 20).getProductGroup()).append("<br/>")
                            .append("产品类型:").append(groupList.get(j + i * 20).getProductType()).append("<br/>");
                }
                if (StringUtils.isNotBlank(chargePeople)) {
                    split = chargePeople.split(",");
                    List<String> userList = Arrays.asList(split);
                    WechatMsgTips.sendOaNotice(userList, builder.toString(), "MES消息提醒:");
                }
            }
            //小于20条数据或者20条成倍数后多出来的数据
            StringBuilder builder = new StringBuilder(commonString);
            for (int j = 20 * num; j < groupList.size(); j++) {
                builder.append("订单号:").append(groupList.get(j).getCustomerOrderNo()).append("<br/>")
                        .append("OTC行号:").append(groupList.get(j).getOtcLineNo()).append("<br/>")
                        .append("产品分组:").append(groupList.get(j).getProductGroup()).append("<br/>")
                        .append("产品类型:").append(groupList.get(j).getProductType()).append("<br/>");
            }
            if (StringUtils.isNotBlank(chargePeople)) {
                split = chargePeople.split(",");
                List<String> userList = Arrays.asList(split);
                WechatMsgTips.sendOaNotice(userList, builder.toString(), "MES消息提醒:");
            }
 
        }
    }
 
 
    /**
     * 同步更新工艺配置单订单行待选列表
     *
     * @param customerOrderNo
     * @param id
     * @return
     */
    @Override
    public List<CustomerOrderDTO> getBeSelectedLineNoList(String customerOrderNo, Long id) {
        //查询该订单号下除原本编辑订单行外的其他订单行记录
        List<CustomerOrderDTO> customerOrderList = baseMapper.getByCustomerOrderNo(customerOrderNo, id);
        if (CollectionUtil.isNotEmpty(customerOrderList)) {
            //查询该订单号下已经配置过的订单行id
            List<ProcessConfig> processConfigList = processConfigMapper.selectList(Wrappers.<ProcessConfig>lambdaQuery()
                    .eq(ProcessConfig::getOrderNumber, customerOrderNo));
            if (CollectionUtil.isNotEmpty(processConfigList)) {
                List<Long> configuredIdList = processConfigList.stream().map(ProcessConfig::getOrderId).collect(Collectors.toList());
                for (CustomerOrderDTO customerOrderDTO : customerOrderList) {
                    if (configuredIdList.contains(customerOrderDTO.getId())) {
                        customerOrderDTO.setExistProcessConfig(true);
                    } else {
                        customerOrderDTO.setExistProcessConfig(false);
                    }
                }
            } else {
                customerOrderList.stream().forEach(o -> o.setExistProcessConfig(false));
            }
            //是否提交字段为前端使用判断
            customerOrderList.stream().forEach(o -> o.setCommonChecked(false));
            return customerOrderList;
        }
        return null;
    }
 
    @Override
    public boolean returnOrder(CustomerOrderDTO customerOrderDTO) {
        if (CollectionUtil.isNotEmpty(customerOrderDTO.getCustomerOrderIds())) {
            String staffNos = remoteParamService.getByKey(MO_RETURN_STAFF, SecurityConstants.FROM_IN).getData();
            if (StringUtils.isBlank(staffNos)) {
                throw new RuntimeException("请先在系统参数管理中配置退回通知人员");
            }
            List<CustomerOrder> customerOrderList = baseMapper.selectList(Wrappers.<CustomerOrder>lambdaQuery().in(CustomerOrder::getId, customerOrderDTO.getCustomerOrderIds()));
            this.baseMapper.update(null, Wrappers.<CustomerOrder>lambdaUpdate()
                    .set(CustomerOrder::getReturnUser, customerOrderDTO.getReturnUser())
                    .set(CustomerOrder::getReturnReason, customerOrderDTO.getReturnReason())
                    .in(CustomerOrder::getId, customerOrderDTO.getCustomerOrderIds()));
            StringBuilder content = new StringBuilder("您好,技术部有如下订单退回,请登录OTC系统进行处理:<br/>");
            for (CustomerOrder customerOrder : customerOrderList) {
                content.append("<br/>")
                        .append("订单编号:").append(customerOrder.getCustomerOrderNo()).append("<br/>")
                        .append("OTC行号:").append(customerOrder.getOtcLineNo()).append("<br/>")
                        .append("客户名称:").append(customerOrder.getCustomerName()).append("<br/>")
                        .append("退回原因:").append(customerOrderDTO.getReturnReason()).append("<br/>")
                        .append("退回人员:").append(customerOrderDTO.getReturnUser()).append("<br/>")
                        .append("退回时间:").append(DateUtil.now()).append("<br/>");
            }
            WechatMsgTips.sendOaNotice(Arrays.asList(staffNos), content.toString(), "MES消息提醒:");
        }
        return true;
    }
 
    @Override
    public boolean changeCheckState(List<Long> ids, String isAudit) {
        boolean isSuccess = false;
        try {
            isSuccess = changeAudit(ids, isAudit);
            if (BooleanUtil.isTrue(isSuccess)) {
                pushCustomersToOtc(ids, isAudit);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }
        return isSuccess;
    }
 
    @Override
    public long syncOrder(CustomOrderSyncDTO customOrderSyncDTO) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String syncErpUrl = environment.getProperty("erpUrl");
        HttpPost httpPost = new HttpPost(syncErpUrl);
        long count = 0;
        // 将参数转换为JSON字符串
        Map<String, String> params = new HashMap<>();
        params.put("startTime", customOrderSyncDTO.getStartTime());
        params.put("endTime", customOrderSyncDTO.getEndTime());
        String jsonParams = new Gson().toJson(params);
        // 设置请求体为JSON格式
        StringEntity requestEntity = new StringEntity(jsonParams, ContentType.APPLICATION_JSON);
        httpPost.setEntity(requestEntity);
        String responseString = null;
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity, "UTF-8");
            log.info(responseString);
            if (StringUtils.isNotBlank(responseString)) {
                R r = new Gson().fromJson(responseString, R.class);
                if (r.getCode() == 0) {
                    count = ((Double) r.getData()).longValue();
                }else{
                    throw new RuntimeException(r.getMsg());
                }
            }
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return count;
    }
 
    @Override
    public IPage<String> getAuditedOrderNoPage(String customerOrderNo, Page page) {
        return this.baseMapper.getAuditedOrderNoPage(customerOrderNo, page);
    }
 
    @Override
    public void dropByContractNo(String contractNo) {
        //1、删主表
        customerMapper.delete(new LambdaQueryWrapper<Customer>().eq(Customer::getContractNo, contractNo));
        //2、删子表
        customerOrderMapper.delete(new LambdaQueryWrapper<CustomerOrder>().eq(CustomerOrder::getCustomerOrderNo, contractNo));
    }
}