bug
jiangping
2023-11-07 64b432916af9c9218ab3f3eca614e26c542142ae
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
package doumeemes.service.ext.impl;
 
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import doumeemes.biz.system.SystemDictDataBiz;
import doumeemes.core.constants.ResponseStatus;
import doumeemes.core.exception.BusinessException;
import doumeemes.core.model.ApiResponse;
import doumeemes.core.model.LoginUserInfo;
import doumeemes.core.model.PageData;
import doumeemes.core.model.PageWrap;
import doumeemes.core.utils.Constants;
import doumeemes.core.utils.DateUtil;
import doumeemes.core.utils.redis.RedisUtil;
import doumeemes.dao.business.*;
import doumeemes.dao.business.model.*;
import doumeemes.dao.ext.*;
import doumeemes.dao.ext.bean.*;
import doumeemes.dao.ext.dto.*;
import doumeemes.dao.ext.vo.*;
import doumeemes.service.business.WOutboundService;
import doumeemes.service.business.WTransferService;
import doumeemes.service.ext.*;
import doumeemes.service.system.SystemUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 工单信息Service实现
 * @author 江蹄蹄
 * @date 2022/04/20 10:56
 */
@Service
public class WorkorderExtServiceImpl implements WorkorderExtService {
 
 
    @Autowired
    @Lazy
    private PlanHistoryExtMapper planHistoryExtMapper;
    @Autowired
    private BomExtMapper bomExtMapper;
    @Autowired
    private BomMapper bomMapper;
 
    @Autowired
    private DeviceExtMapper deviceExtMapper ;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserDeviceExtMapper userDeviceExtMapper;
    @Autowired
    private BarcodeParamExtService barcodeParamExtService;
    @Autowired
    private CompanyUserExtMapper companyUserExtMapper;
    @Autowired
    private DepartmentExtService departmentExtService;
    @Autowired
    private SystemUserService systemUserService;
 
    @Autowired
    private BomDetailExtMapper bomDetailExtMapper;
    @Autowired
    private WorkorderExtMapper workorderExtMapper;
    @Autowired
    private BackorderMapper backorderMapper;
    @Autowired
    private WorkorderMapper workorderMapper;
    @Autowired
    private WorkorderHistoryExtMapper workorderHistoryExtMapper;
    @Autowired
    private WorkorderRecordExtMapper workorderRecordExtMapper;
    @Autowired
    private WorkorderUserExtMapper workorderUserExtMapper;
    @Autowired
    private WTransferService wTransferService;
    @Autowired
    private WTransferExtService wTransferExtService;
    @Autowired
    private WTransferExtMapper wTransferExtMapper;
    @Autowired
    private WTransferDetailExtMapper wTransferDetailExtMapper;
    @Autowired
    private AppliancesExtMapper appliancesExtMapper;
    @Autowired
    private AppliancesMapper appliancesMapper;
    @Autowired
    private PlansExtMapper plansExtMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DepartmentExtMapper departmentExtMapper;
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
    @Autowired
    private WOutboundExtMapper wOutboundExtMapper;
    @Autowired
    private WOutboundService wOutboundService;
    @Autowired
    private WOutboundDetailExtMapper wOutboundDetailExtMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private WStockMapper wStockMapper;
    @Autowired
    private WOutboundRecordExtMapper wOutboundRecordExtMapper;
    @Autowired
    private ProceduresMapper proceduresMapper;
    @Autowired
    private NoticesExtService noticesExtService;
    @Autowired
    private CompanyUserMapper companyUserMapper;
    @Autowired
    private RouteProcedureExtMapper routeProcedureExtMapper;
    @Autowired
    private BackOrderDetailMapper backOrderDetailMapper;
    @Autowired
    private WHistoryMapper wHistoryMapper;
    @Autowired
    private WorkPlansExtMapper workPlansExtMapper;
    @Autowired
    private PlansMapper plansMapper;
 
    @Autowired
    private WStockRecordExtService wStockRecordExtService;
 
    public static WorkorderHistory initHistoryByModel(WorkorderExtListVO p,int userId, int status) {
            WorkorderHistory h = new WorkorderHistory();
            h.setDeleted(Constants.ZERO);
            h.setCreateTime(DateUtil.getCurrentDate());
            h.setCreateUser(userId);
            h.setDepartId(p.getDepartId());
            h.setRootDepartId(p.getRootDepartId());
            h.setOrderId(p.getId());
            h.setTitle(Constants.WORKORDER_STATUS.getTitleByStatus(p,status));
            h.setType(status);
            h.setInfo(Constants.WORKORDER_STATUS.getInfoByStatus(p,status));
            return h;
    }
 
    public static PlanHistory initPlanHistoryByModel(WorkPlans p, Integer userId, int status ) {
        PlanHistory h = new PlanHistory();
        h.setDeleted(Constants.ZERO);
        h.setCreateTime(DateUtil.getCurrentDate());
        h.setCreateUser(userId);
        h.setDepartId(p.getDepartId());
        h.setRootDepartId(p.getRootDepartId());
        h.setPlanId(p.getId());
        h.setRootDepartId(p.getRootDepartId());
        h.setDepartId(p.getDepartId());
        h.setTitle(Constants.WORKPLANHISTORY_TYPE.getTitleByStatus(p,status));
        h.setType(status);
        h.setInfo(Constants.WORKPLANHISTORY_TYPE.getInfoByStatus(p,status));
        h.setType(status);
 
        return h;
    }
 
    public static WorkorderHistory initHistoryByModel(Workorder p, int userId, int status) {
            WorkorderHistory h = new WorkorderHistory();
            h.setDeleted(Constants.ZERO);
            h.setCreateTime(DateUtil.getCurrentDate());
            h.setCreateUser(userId);
            h.setDepartId(p.getDepartId());
            h.setRootDepartId(p.getRootDepartId());
            h.setOrderId(p.getId());
            h.setTitle(Constants.WORKORDER_HISTORY_STATUS.getTitleByStatus(null,status));
            h.setType(status);
            h.setInfo(Constants.WORKORDER_HISTORY_STATUS.getInfoByStatus(null,status));
            return h;
    }
 
    @Override
    public PageData<WorkorderExtListVO> findPage(PageWrap<QueryWorkorderExtDTO> pageWrap) {
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        //只能查看当前根组织的数据
        pageWrap.getModel().setRootDepartId(user.getRootDepartment().getId());
//        if(!Constants.equalsInteger(user.getCurComDepartment().getId(),user.getRootDepartment().getId())){
            //如果当前选择的公司级组织非根组织信息,只能查看当前选择公司级组织数据
            pageWrap.getModel().setDepartId(user.getCurComDepartment().getId());
//        }
        //数据权限
//        pageWrap.getModel().setCreateUser(user.getId());
        List<Integer> dataPermission = user.getDepartPermissionList();
        if(dataPermission!=null){
            pageWrap.getModel().setDepartIds(dataPermission);
            pageWrap.getModel().setCreateUser(user.getId());
           /* if(dataPermission.size() == 0){
                //只能看自己的(生产人员信息)
                //  pageWrap.getModel().setProUserId(user.getId());
                //需求变更 查看数据权限范围内的数据(走创建人或者生产人员为我数据权限范围内);
                pageWrap.getModel().setCreateUser(user.getId());
            }else{
                //否则走数据权限
                pageWrap.getModel().setDepartIds(dataPermission);
            }*/
        }
        pageWrap.getModel().setDeleted(Constants.ZERO);
        PageHelper.startPage(pageWrap.getPage(), pageWrap.getCapacity());
        List<WorkorderExtListVO> result = workorderExtMapper.selectList(pageWrap.getModel());
        if(result!=null){
            List<DepartmentExtListVO> allDepartList = RedisUtil.getObject(redisTemplate,Constants.RedisKeys.COM_DEPART_LIST_KEY+user.getCompany().getId(),ArrayList.class);
            for(WorkorderExtListVO w : result){
                if(w.getOriginId()!=null){
                    w.setOriginName( systemDictDataBiz.queryCodeById(w.getOriginId()));
                }
//                BarcodeParamExtListVO code =barcodeParamExtService.getByCodeId(user.getCompany().getId(),user.getCurComDepartment().getId(),w.getQrcodeId());
//                String prex = code!=null? code.getPrefix():"";
//                w.setCode(prex+w.getCode());
//                initProUser(user,w,allDepartList);
                initProUserList(user,w,allDepartList);
                //根据工单查询BOM下一个工序
                /**
                 * BOM上的工序是投料工序,表示这个BOM在哪个工序上使用;
                 * 我要查询工单上的生产工序的后续工序:
                 * 1. 先用工单的物料+工厂去查BOM表,找到工艺路线;
                 * 2. 用工单的生产工序,比对工艺路线,找到后续的工序(此过程跟BOM主表上的工序没有任何关系);
                 */
                Bom b = bomExtMapper.selectOne(new QueryWrapper<Bom>()
                        .eq("MATERIAL_ID",w.getMaterialId())
                        .eq("DEPART_ID",w.getDepartId())
                        .eq("DELETED",Constants.ZERO)
//                        .eq("STATUS",Constants.ONE)
                );
                w.setPapercode(b!=null?b.getPapercode():null);
 
              /*  RouteProcedure currentRouteProcedure   = routeProcedureExtMapper.selectOne(new QueryWrapper<RouteProcedure>()
                        .eq("ROUTE_ID",b.getRouteId())
                        .eq("PROCEDURE_ID",b.getProcedureId())
                        .last(" limit 1 ")
                );*/
 
                RouteProcedure currentRouteProcedure   = routeProcedureExtMapper.selectOne(new QueryWrapper<RouteProcedure>()
                        .eq("ROUTE_ID",b.getRouteId())
                        .eq("PROCEDURE_ID",w.getProcedureId())
                        .last(" limit 1 ")
                );
                if(currentRouteProcedure!=null){
                    QueryRouteProcedureExtDTO queryrp=new QueryRouteProcedureExtDTO();
                    queryrp.setRouteId(b.getRouteId());
                    queryrp.setSortnum(currentRouteProcedure.getSortnum());
                    // queryrp.setDepartId(w.getDepartId());
                    queryrp.setDeleted(Constants.ZERO);
                    List<RouteProcedureExtListVO> routeProcedureList   = routeProcedureExtMapper.selectListByNext(queryrp);
                    w.setRouteProcedureList(routeProcedureList);
                }
                StringBuffer sbf = new StringBuffer();
                List<WorkorderUserExtListVO> proUserList = w.getProUserList();
                if(!Objects.isNull(proUserList)&&proUserList.size()>Constants.ZERO){
                    proUserList.forEach(i->{
                        sbf.append(i.getProUserDepartName()+";");
                    });
                }
                w.setProUserListStr(sbf.toString());
            }
        }
        return PageData.from(new PageInfo<>(result));
    }
 
 
 
    private void initProUser(LoginUserInfo user, WorkorderExtListVO data, List<DepartmentExtListVO> allDepartList) {
        if(data.getProUserId() ==null){
            return;
        }
        CompanyUser query=new CompanyUser();
        query.setUserId(data.getProUserId());
        query.setRootDepartId(user.getRootDepartment().getId());
        query.setDeleted(Constants.ZERO);
        CompanyUser comp= companyUserExtMapper.selectOne(new QueryWrapper<>(query).last(" limit 1"));
        if(comp!=null){
            DepartmentExtListVO d = departmentExtService.getModelById(user.getCompany().getId(),comp.getDepartmentId(),allDepartList);
            String dName =d==null?"":StringUtils.defaultString(d.getName(),"");
            data.setProUserDepartName(dName);
        }
    }
    private void initProUserOld(LoginUserInfo user, WorkorderExtListVO data, List<DepartmentExtListVO> allDepartList) {
        if(data.getProUserId() ==null){
            return;
        }
        CompanyUser query=new CompanyUser();
        query.setUserId(data.getProUserId());
        query.setRootDepartId(user.getRootDepartment().getId());
        query.setDeleted(Constants.ZERO);
        CompanyUser comp= companyUserExtMapper.selectOne(new QueryWrapper<>(query).last(" limit 1"));
        if(comp!=null){
            DepartmentExtListVO d = departmentExtService.getModelById(user.getCompany().getId(),comp.getDepartmentId(),allDepartList);
            String dName =d==null?"":StringUtils.defaultString(d.getName(),"");
            data.setProUserDepartName(dName);
        }
    }
 
    @Override
    public WorkorderExtListCountVO pageCount(QueryWorkorderExtDTO param){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        //只能查看当前根组织的数据
        param.setRootDepartId(user.getRootDepartment().getId());
//        if(!Constants.equalsInteger(user.getCurComDepartment().getId(),user.getRootDepartment().getId())){
        //如果当前选择的公司级组织非根组织信息,只能查看当前选择公司级组织数据
        param.setDepartId(user.getCurComDepartment().getId());
//        }
        //数据权限
//        param.setCreateUser(user.getId());
        List<Integer> dataPermission = user.getDepartPermissionList();
        if(dataPermission!=null){
            param.setCreateUser(user.getId());
            //否则走数据权限
            param.setDepartIds(dataPermission);
           /* if(dataPermission.size() == 0){
                //只能看自己的(生产人员信息)
                  param.setProUserId(user.getId());
                //需求变更 查看数据权限范围内的数据(走创建人或者生产人员为我数据权限范围内);
            }else{
                //否则走数据权限
                param.setDepartIds(dataPermission);
            }*/
        }
        WorkorderExtListCountVO result = new WorkorderExtListCountVO();
        //全部数量
        result.setAllNum(workorderExtMapper.selectCount(param));
        param.setStatusList(new ArrayList<>());
        param.getStatusList().add(Constants.WORKORDER_STATUS.create);
        param.getStatusList().add(Constants.WORKORDER_STATUS.material);
        //未完成数量
        result.setStartNum(workorderExtMapper.selectCount(param));
        param.setStatusList(new ArrayList<>());
        param.getStatusList().add(Constants.WORKORDER_STATUS.done);
        param.getStatusList().add(Constants.WORKORDER_STATUS.producing);
        param.getStatusList().add(Constants.WORKORDER_STATUS.check);
        //进行中数量
        result.setIngNum(workorderExtMapper.selectCount(param));
        param.setStatusList(new ArrayList<>());
        param.getStatusList().add(Constants.WORKORDER_STATUS.baogong);
        param.getStatusList().add(Constants.WORKORDER_STATUS.instock);
        param.getStatusList().add(Constants.WORKORDER_STATUS.cancel);
        //进行中数量
        result.setEndNum(workorderExtMapper.selectCount(param));
        return result;
    }
    @Override
    public List<WorkorderListModelVO> findByPlanId(PlansExtListH5VO plan,boolean isWorkorderList){
 
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        QueryWorkorderExtDTO pageWrap = new QueryWorkorderExtDTO();
        pageWrap.setDeleted(Constants.ZERO);
        pageWrap.setPlanId(plan.getId());
        List<WorkorderExtListVO> result = workorderExtMapper.selectList(pageWrap );
        QueryWorkorderRecordExtDTO rParam = new QueryWorkorderRecordExtDTO();
        rParam.setPlanId(pageWrap.getId());
        rParam.setDeleted(Constants.ZERO);
        //已完工数量
        plan.setDoneNum(0);
        //已分配数量
        plan.setDistributNum(0);
        //查询全部投料和产出
        List<WorkorderRecordExtListVO> recordList = workorderRecordExtMapper.selectAllList(rParam);
        List<WorkorderListModelVO> list = new ArrayList<>();
        if(result!=null){
            List<DepartmentExtListVO> allDepartList = RedisUtil.getObject(redisTemplate,Constants.RedisKeys.COM_DEPART_LIST_KEY+user.getCompany().getId(),ArrayList.class);
            for(WorkorderExtListVO w : result){
                //②计划完工数量=已报工工单(已报工、已入库)的完工数量(包括:合格、不良、报废);
                //①计划分配数量=已报工工单(已报工、已入库)的完工数量(包括:合格、不良、报废)+未报工工单(已创建、已备料、已检验、已完工)的已分配数量;
                if(Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.baogong) || Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.instock)){
                    plan.setDoneNum(Constants.formatIntegerNum(w.getUnqualifiedNum()) + Constants.formatIntegerNum(w.getQualifiedNum()) + plan.getDoneNum());
                    plan.setDistributNum(Constants.formatIntegerNum(w.getUnqualifiedNum()) + Constants.formatIntegerNum(w.getQualifiedNum()) + plan.getDistributNum());
                }else{
                    plan.setDistributNum(Constants.formatIntegerNum(w.getPlanNum()) + plan.getDistributNum());
                }
                initProUserList(user,w,allDepartList);
                if(isWorkorderList){
                    List<WorkorderRecordExtListVO> rList = getRecordListById(w.getId(),recordList);
                    WorkorderListModelVO tModle = new WorkorderListModelVO();
                    tModle.setId(w.getId());
                    BarcodeParamExtListVO pCode = barcodeParamExtService.getByCodeId(user.getCompany().getId(),user.getCurComDepartment().getId(),w.getQrcodeId());
                    String prex =pCode!=null?pCode.getPrefix(): "";
                    tModle.setCode(prex+w.getCode());
                    tModle.setCreateTime(w.getCreateTime());
                    tModle.setDistributeDate(w.getCreateTime());
                    tModle.setPaused(w.getPaused());
                    tModle.setProUserList(w.getProUserList());
                    tModle.setStatus(w.getStatus());
                    tModle.setPlanDate(w.getPlanDate());
                    tModle.setPlanNum(w.getPlanNum());
                    tModle.setMaterialList(new ArrayList<>());
                    tModle.setPlanNum(w.getPlanNum());
                    tModle.setUrgent(w.getUrgent());
                    tModle.setUpdateTime(w.getUpdateTime());
                    tModle.setRemark(w.getRemark());
                    tModle.setQualifiedNum(w.getQualifiedNum());
                    tModle.setUnqualifiedNum(w.getUnqualifiedNum());
                    tModle.setProUserId(w.getProUserId());
                    tModle.setProUserName(w.getProUserName());
                    tModle.setProUserName(w.getProUserName());
                    tModle.setCreateUser(w.getCreateUser());
                    tModle.setCreateUserName(w.getCreateUserName());
                    if(w.getProUserId()!=null){
                        //查询班组信息
                        QueryCompanyUserExtDTO queryCompanyUserExtDTO = new QueryCompanyUserExtDTO();
                        queryCompanyUserExtDTO.setUserId(w.getProUserId());
                        queryCompanyUserExtDTO.setRootDepartId(w.getRootDepartId());
                        CompanyUserExtListVO uModel = companyUserExtMapper.selectModel(queryCompanyUserExtDTO);
                        if(uModel!=null && uModel.getDmodel()!=null){
                            tModle.setProUserDepart(uModel.getDmodel().getName());
                        }
                    }
 
                    if(rList!=null){
                        for (WorkorderRecordExtListVO r : rList){
                            if(Constants.equalsInteger(r.getType(),Constants.WORKORDER_RECORD_TYPE.materail)){
                                if(tModle.getMaterialDate()==null){
                                    tModle.setMaterialDate(r.getCreateTime());
                                }
                                MaterialModelVo m = getMaterialModelFromList(tModle.getMaterialList(),r.getMaterialId());
                                if(m != null){
                                    //如果已经存在,分组统计累计数量
                                    m.setNum(m.getNum().add(Constants.formatBigdecimal(r.getNum())));
                                }else{
                                    //如果不存,添加新的分组
                                    m = new MaterialModelVo();
                                    m.setUnitName(r.getUmodel()!=null?r.getUmodel().getName():"");
                                    m.setNum(Constants.formatBigdecimal(r.getNum()));
                                    m.setId(r.getMaterialId());
                                    m.setName(r.getMmodel()!=null?r.getMmodel().getName():"");
                                    tModle.getMaterialList().add(m);
                                }
 
                            }else  if(Constants.equalsInteger(r.getType(),Constants.WORKORDER_RECORD_TYPE.produce)){
                                if(tModle.getProduceDate()==null){
                                    //产出日期
                                    tModle.setProduceDate(r.getCreateTime());
                                }
//                                if(Constants.equalsInteger(r.getDoneType(),Constants.ZERO)){
                                    //如果是合格产出
//                                    tModle.setQualifiedNum(tModle.getQualifiedNum()+Constants.formatBigdecimal(r.getNum()).intValue());
//                                }else{
                                    //如果是不良品
//                                    tModle.setUnqualifiedNum(tModle.getUnqualifiedNum()+Constants.formatBigdecimal(r.getNum()).intValue());
//                                }
                                //如果是合格产出
                                tModle.setQualifiedNum(tModle.getQualifiedNum());
                                //如果是不良品
                                tModle.setUnqualifiedNum(tModle.getUnqualifiedNum());
                            }
                        }
                    }
                    list.add(tModle);
                }
            }
        }
        plan.setLessDistributNum(plan.getNum()-plan.getDistributNum());//待分配数量
        return  list;
    }
 
    private MaterialModelVo getMaterialModelFromList(List<MaterialModelVo> materialList, Integer materialId) {
        if(materialList != null){
           for (MaterialModelVo m : materialList){
               if(Constants.equalsInteger(m.getId(),materialId)){
                   return  m;
               }
           }
        }
        return  null;
    }
 
    private List<WorkorderRecordExtListVO> getRecordListById(Integer id, List<WorkorderRecordExtListVO> recordList) {
        if(recordList==null  ){
            return null;
        }
        List<WorkorderRecordExtListVO> list = null;
        for(WorkorderRecordExtListVO r : recordList){
            if(Constants.equalsInteger(r.getWorkorderId(),id)){
                if(list == null){
                    list = new ArrayList<>();
                }
                list.add(r);
            }
        }
        return list;
    }
 
    @Override
    public  WorkorderExtListVO findById(Integer id){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        QueryWorkorderExtDTO pageWrap = new QueryWorkorderExtDTO();
 
        //只能查看当前根组织的数据
        pageWrap.setRootDepartId(user.getRootDepartment().getId());
        pageWrap.setId(id);
//        if(!Constants.equalsInteger(user.getCurComDepartment().getId(),user.getRootDepartment().getId())){
            //如果当前选择的公司级组织非根组织信息,只能查看当前选择公司级组织数据
//            pageWrap.setDepartId(user.getCurComDepartment().getId());
//        }
        //数据权限
//        List<Integer> dataPermission = user.getDepartPermissionList();
//        if(dataPermission!=null){
//            if(dataPermission.size() == 0){
//                //只能看自己的(生产人员信息)
//                pageWrap.setProUserId(user.getId());
//            }else{
//                //否则走数据权限
//                pageWrap.setDepartIds(dataPermission);
//            }
//        }
        WorkorderExtListVO result = workorderExtMapper.selectByModel(pageWrap);
        if(result == null){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,查询记录不存在!");
        }
        if(result.getOriginId()!=null){
            result.setOriginName( systemDictDataBiz.queryCodeById(result.getOriginId()));
        }
        BarcodeParamExtListVO code =barcodeParamExtService.getByCodeId(user.getCompany().getId(),user.getCurComDepartment().getId(),result.getQrcodeId());
        String prex = code!=null? code.getPrefix():"";
        result.setCode(prex+result.getCode());
       //查詢生产人员信息
        initProUserList(user,result, RedisUtil.getObject(redisTemplate,Constants.RedisKeys.COM_DEPART_LIST_KEY+user.getCompany().getId(),ArrayList.class));
 
        QueryBomExtDTO bb = new QueryBomExtDTO();
        bb.setDepartId(result.getDepartId());
        bb.setDeleted(Constants.ZERO);
        bb.setRootDepartId(user.getRootDepartment().getId());
        bb.setMaterialId(result.getMaterialId());
        bb.setProcedureId(result.getProcedureId());
        BomExtListVO versionBom = bomExtMapper.selectByModel( bb);
        if(versionBom == null || StringUtils.isBlank(versionBom.getVersion()) || versionBom.getBomVersionId() == null){
            result.setHasBom(Constants.ZERO);
        }else {
            result.setBomType(Constants.formatIntegerNum(versionBom.getType()));
            result.setHasBom(Constants.ONE);
        }
        return  result;
    }
 
    private void initProUserList(LoginUserInfo user, WorkorderExtListVO result, List<DepartmentExtListVO> allDepartList ) {
        QueryWorkorderUserExtDTO u = new QueryWorkorderUserExtDTO();
        u.setWorkorderId(result.getId());
        u.setDeleted(Constants.ZERO);
        //查询全部生产人员数据
        List<WorkorderUserExtListVO> uList = workorderUserExtMapper.selectListByOrder(u);
        if(uList!=null && uList.size()>0){
//            List<DepartmentExtListVO> allDepartList = RedisUtil.getObject(redisTemplate,Constants.RedisKeys.COM_DEPART_LIST_KEY+user.getCompany().getId(),ArrayList.class);
            for(WorkorderUserExtListVO uu : uList){
                initProUserNew(user,uu,allDepartList);
            }
        }
        result.setProUserList(uList);
    }
 
    private void initProUserNew(LoginUserInfo user, WorkorderUserExtListVO data, List<DepartmentExtListVO> allDepartList) {
        if(data.getProUserId() ==null){
            return;
        }
        CompanyUser query=new CompanyUser();
        query.setUserId(data.getProUserId());
        query.setRootDepartId(user.getRootDepartment().getId());
        query.setDeleted(Constants.ZERO);
        CompanyUser comp= companyUserExtMapper.selectOne(new QueryWrapper<>(query).last(" limit 1"));
        if(comp!=null){
            DepartmentExtListVO d = departmentExtService.getModelById(user.getCompany().getId(),comp.getDepartmentId(),allDepartList);
            String dName =d==null?"":StringUtils.defaultString(d.getName(),"");
            data.setProUserDepartName(comp.getName()+"-"+dName);
        }
    }
 
    @Override
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    public void distributeById(Workorder param) {
        if(param.getId()== null
                ||param.getPlanDate() == null
                || param.getProGroupId()==null
                || param.getProUserList()==null
                || param.getProUserList().size()==0  ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,请按要求填写和选择提交数据!");
        }
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        Workorder mp = new Workorder();
        mp.setDeleted(Constants.ZERO);
        mp.setId(param.getId());
        mp.setRootDepartId(user.getRootDepartment().getId());
        mp = workorderExtMapper.selectOne(mp);
        if(mp== null){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,该记录不存在!");
        }
        if(Constants.equalsInteger(mp.getPaused(),Constants.ONE)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,工单已暂停!");
        }
        if(!Constants.equalsInteger(mp.getStatus(),Constants.WORKORDER_STATUS.create)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该工单状态已流转,不能进行该操作!");
        }
        List<WorkorderHistory> whList = new ArrayList<>();
        Workorder order = new Workorder();
        order.setUpdateTime(DateUtil.getCurrentDate());
        order.setUpdateUser(user.getId());
        order.setId(param.getId());
        order.setRootDepartId(mp.getRootDepartId());
        order.setDepartId(mp.getDepartId());
        order.setPlanDate(param.getPlanDate());
        order.setUserDeivceId(param.getUserDeivceId());
        order.setPlanId(mp.getPlanId());
        order.setProGroupId(param.getProGroupId());
        order.setProUserList(param.getProUserList());
        //查询生产班组和人员是否合法
        checkUserAndGroup(order,user);
//        order.setProGroupId(null);
        order.setPlanId(null);
        order.setProUserList(null);
        workorderExtMapper.updateById(order);
        //工单历史数据
        whList.add(WorkorderExtServiceImpl.initHistoryByModel(order,user.getId(),Constants.WORKORDER_HISTORY_STATUS.redistribute));
        workorderHistoryExtMapper.insertBatch(whList);
 
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("WORKORDER_ID",param.getId());
        updateWrapper.eq("DELETED",Constants.ZERO);
        updateWrapper.set("DELETED",Constants.ONE);
        updateWrapper.set("UPDATE_TIME",DateUtil.getCurrentDate());
        updateWrapper.set("UPDATE_USER",user.getId());
        //删除原有的工单分配人员信息(逻辑删除)
        workorderUserExtMapper.update(null,updateWrapper);
        //插入生产人员分配关联表
        for( WorkorderUser wu :order.getWorkorderUserList()){
            wu.setWorkorderId(order.getId());
            //生产人员记录
            workorderUserExtMapper.insert(wu);
        }
      /*  WorkorderUser wu =new WorkorderUser();
        wu.setWorkorderId(order.getId());
        wu.setDeleted(Constants.ZERO);
        wu.setCreateTime(DateUtil.getCurrentDate());
        wu.setCreateUser(user.getId());
        wu.setDepartId(mp.getDepartId());
        wu.setRootDepartId(mp.getRootDepartId());
        wu.setPlanId(mp.getPlanId());
        wu.setProUserId(order.getProUserId());
        //历史生产人员记录
        workorderUserExtMapper.insert(wu);*/
    }
    @Override
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    public void closeById(Workorder param) {
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        if(param.getId()== null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,请按要求填写和选择提交数据!");
        }
        Workorder mp = new Workorder();
        mp.setDeleted(Constants.ZERO);
        mp.setId(param.getId());
        mp.setRootDepartId(user.getRootDepartment().getId());
        mp = workorderExtMapper.selectOne(mp);
        if(mp== null){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,该记录不存在!");
        }
        /* if(Constants.equalsInteger(mp.getPaused(),Constants.ONE)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,工单已暂停!");
        }*/
        if(!Constants.equalsInteger(mp.getStatus(),Constants.WORKORDER_STATUS.create)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该工单状态已流转,不能进行该操作!");
        }
        List<WorkorderHistory> whList = new ArrayList<>();
        Workorder order = new Workorder();
        order.setUpdateTime(DateUtil.getCurrentDate());
        order.setUpdateUser(user.getId());
        order.setRootDepartId(mp.getRootDepartId());
        order.setDepartId(mp.getDepartId());
        order.setPlanDate(param.getPlanDate());
        //已关闭
        order.setStatus(Constants.WORKORDER_STATUS.cancel);
        order.setId(param.getId());
        order.setUserDeivceId(param.getUserDeivceId());
        workorderExtMapper.updateById(order);
        //工单历史数据
        whList.add(WorkorderExtServiceImpl.initHistoryByModel(order,user.getId(),Constants.WORKORDER_HISTORY_STATUS.close));
        workorderHistoryExtMapper.insertBatch(whList);
    }
    @Override
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    public void cancelById(Workorder param) {
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        if(param.getId()== null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,请按要求填写和选择提交数据!");
        }
        Workorder mp = new Workorder();
        mp.setDeleted(Constants.ZERO);
        mp.setId(param.getId());
        mp.setRootDepartId(user.getRootDepartment().getId());
        mp = workorderExtMapper.selectOne(mp);
        if(mp== null){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,该记录不存在!");
        }
        //返回controller层,发送计划统计数据
        param.setPlanId(mp.getPlanId());
        WorkorderRecord wr = new WorkorderRecord();
        wr.setWorkorderId(mp.getId());
        wr.setDeleted(Constants.ZERO);
        if(workorderRecordExtMapper.selectCount(new QueryWrapper<>(wr)) >0){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,工单已经有投料或产出记录,不能取消!");
        }
        /* if(Constants.equalsInteger(mp.getPaused(),Constants.ONE)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,工单已暂停!");
        }*/
        if(!Constants.equalsInteger(mp.getStatus(),Constants.WORKORDER_STATUS.create)
                &&!Constants.equalsInteger(mp.getStatus(),Constants.WORKORDER_STATUS.material)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该工单状态已流转,不能进行该操作!");
        }
        List<WorkorderHistory> whList = new ArrayList<>();
        Workorder order = new Workorder();
        order.setUpdateTime(DateUtil.getCurrentDate());
        order.setUpdateUser(user.getId());
        order.setRootDepartId(mp.getRootDepartId());
        order.setDepartId(mp.getDepartId());
        order.setPlanDate(param.getPlanDate());
        //已关闭
        order.setStatus(Constants.WORKORDER_STATUS.cancel);
        order.setUserDeivceId(param.getUserDeivceId());
        order.setId(mp.getId());
        workorderExtMapper.updateById(order);
        //工单历史数据
        whList.add(WorkorderExtServiceImpl.initHistoryByModel(order,user.getId(),Constants.WORKORDER_HISTORY_STATUS.cancel));
        workorderHistoryExtMapper.insertBatch(whList);
    }
 
    /** 1.计划统计
     * 已分配未报工数量=未报工工单(工单状态:已创建、已备料、已检验、已完工)的计划生产数量之和;
     * 合格数量=已报工工单(工单状态:已报工、已入库)产出为合格的数量之和;
     * 不良数量=已报工工单(工单状态:已报工、已入库)产出为不良的数量之和;
     *
     * 2.工单统计
     * @param param
     */
    @Override
//    @Async
    public void statisticNum(Workorder param){
        if(param.getPlanId()== null){
            if(param.getId()== null){
                return;
            }
            Workorder wModel = new Workorder();
            wModel.setDeleted(Constants.ZERO);
            wModel.setId(param.getId());
            wModel = workorderExtMapper.selectOne(wModel);
            if(wModel== null){
                return;
            }
            param.setPlanId(wModel.getPlanId());
        }
        Plans plan = plansExtMapper.selectById(param.getPlanId());
        if(plan == null){
            return;
        }
        JSONObject json = new JSONObject();
        QueryWorkorderExtDTO qw = new QueryWorkorderExtDTO();
        qw.setPlanId(param.getPlanId());
        qw.setDeleted(Constants.ZERO);
        //查询全部工单数据
        List<WorkorderExtListVO> orderList = workorderExtMapper.selectList(qw);
        //已完工数量
        int doneNum=0;
        //已分配数量
        //已报工工单(包括工单状态:已报工、已入库)的完工数量(包括:合格、不良、报废)
        //+未报工工单(包括工单状态:已创建、已备料、已检验、已完工)的已分配数量
        int distributNum=0;
        //已分配未报工数量=未报工工单(工单状态:已创建、已备料、已检验、已完工)的计划生产数量之和;
        int distributeNoDoneNum=0;
        //合格数量=已报工工单(工单状态:已报工、已入库)产出为合格的数量之和;
        int qulifiedNum=0;
        //不良数量=已报工工单(工单状态:已报工、已入库)产出为不良的数量之和;
        int unqulifiedNum =0;
        int allOrderNum =0;
        if(orderList!=null && orderList.size()>0){
            QueryWorkorderRecordExtDTO rw = new QueryWorkorderRecordExtDTO();
            rw.setPlanId(param.getPlanId());
            rw.setDeleted(Constants.ZERO);
            //查询全部工单产出和投料数据
            List<WorkorderRecordExtListVO> allRecordList = workorderRecordExtMapper.selectListNew(rw);
            for(WorkorderExtListVO order : orderList){
                if(Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.cancel)){
                    //取消的工单不累计数量
                    continue;
                }
                if(Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.create)
                ||Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.material)
                ||Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.producing)
                ||Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.check)
                ||Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.done)){
                    //统计已分配未报工数量
                    distributeNoDoneNum += Constants.formatIntegerNum(order.getPlanNum());
                }
                if(Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.baogong)
                        ||Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.producing)
                        || Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.instock)){
                   doneNum += Constants.formatIntegerNum(order.getUnqualifiedNum()) + Constants.formatIntegerNum(order.getQualifiedNum());
                   int tNum =Constants.formatIntegerNum(order.getUnqualifiedNum()) + Constants.formatIntegerNum(order.getQualifiedNum());
                   distributNum += tNum;
                   allOrderNum += tNum;
                }else {
                    distributNum += Constants.formatIntegerNum(order.getPlanNum());
                }
 
                List<WorkorderRecordExtListVO> rList = getRecordListById(order.getId(),allRecordList);
                if(rList!=null){
                   for(WorkorderRecordExtListVO item : rList){
                        if(Constants.equalsInteger(item.getType(),Constants.WORKORDER_RECORD_TYPE.produce)
                            && item.getOmodel()!=null
                            && (Constants.equalsInteger(item.getOmodel().getStatus() ,Constants.WORKORDER_STATUS.baogong)
                            ||Constants.equalsInteger(item.getOmodel().getStatus() ,Constants.WORKORDER_STATUS.instock))){
                            //如果是合格产出,累计数量
                            qulifiedNum += Constants.formatBigdecimal(BigDecimal.valueOf(item.getQualifiedNum())).intValue();
                            //如果是不良产出,累计数量
                            unqulifiedNum += Constants.formatBigdecimal(BigDecimal.valueOf(item.getUnqualifiedNum())).intValue();
                        }
                    }
                }
            }
        }
        json.put(Constants.STATISTIC.distributeNoDone,distributeNoDoneNum);
        json.put(Constants.STATISTIC.done,doneNum);
        json.put(Constants.STATISTIC.distribute,distributNum);
        json.put(Constants.STATISTIC.qulified,qulifiedNum);
        json.put(Constants.STATISTIC.unqulified,unqulifiedNum);
 
        UpdateWrapper updateWrapper = new UpdateWrapper();
        Plans p = new Plans();
        p.setId(param.getPlanId());
        p.setStatisticInfo(json.toJSONString());
        p.setUpdateTime(DateUtil.getCurrentDate());
        if( Constants.formatIntegerNum(plan.getNum())  <= allOrderNum){
            //如果满足计划已完工,更新计划状态
            p.setStatus(Constants.PLAN_STATUS.done);
            if(!Objects.isNull(plan.getWorkPlansId())){
                //更新主订单数据信息
               if(plansMapper.selectCount(new QueryWrapper<Plans>()
                        .in("STATUS",0,1,4,5)
                        .eq("DELETED",Constants.ZERO)
                        .ne("id",p.getId())
                        .eq("WORK_PLANS_ID",plan.getWorkPlansId()))<=Constants.ZERO){
                   WorkPlans  workPlans = workPlansExtMapper.selectById(plan.getWorkPlansId());
                   if(!Objects.isNull(workPlans)){
                       workPlans.setStatus(Constants.WORKPLANHISTORY_TYPE.done);
                       workPlans.setUpdateTime(new Date());
                       workPlansExtMapper.updateById(workPlans);
                       planHistoryExtMapper.insert(initPlanHistoryByModel(workPlans,null,Constants.WORKPLANHISTORY_TYPE.done));
                   }
               };
            }
            //
            plan.getWorkPlansId();
 
            updateWrapper.set("STATUS",p.getStatus());
            if(Constants.equalsInteger(plan.getStatus(),Constants.PLAN_STATUS.distribute)){
              //如果已分配
              planHistoryExtMapper.insertBatch(Arrays.asList(PlansExtServiceImpl.initHistoryByModel(plan,null,Constants.PLANHISTORY_TYPE.done)));
          }
//          planHistoryService.create(PlansExtServiceImpl.initHistoryByModel(plan,null,Constants.PLANHISTORY_TYPE.done));
        }
        //更新统计信息
//        plansExtMapper.updateById(p);
        updateWrapper.eq("ID",param.getPlanId());
        updateWrapper.set("STATISTIC_INFO",json.toJSONString());
        updateWrapper.set("UPDATE_TIME",DateUtil.getCurrentDate());
        plansExtMapper.update(null,updateWrapper);
//        Workorder order = new Workorder();
//        order.setUpdateTime(DateUtil.getCurrentDate());
//        //已关闭
//        order.setId(param.getId());
//        workorderExtMapper.updateById(order);
 
    }
 
 
 
    @Override
    @Async
    public void statisticNumAsync(Workorder param){
        if(param.getPlanId()== null){
            if(param.getId()== null){
                return;
            }
            Workorder wModel = new Workorder();
            wModel.setDeleted(Constants.ZERO);
            wModel.setId(param.getId());
            wModel = workorderExtMapper.selectOne(wModel);
            if(wModel== null){
                return;
            }
            param.setPlanId(wModel.getPlanId());
        }
        Plans plan = plansExtMapper.selectById(param.getPlanId());
        if(plan == null){
            return;
        }
        JSONObject json = new JSONObject();
        QueryWorkorderExtDTO qw = new QueryWorkorderExtDTO();
        qw.setPlanId(param.getPlanId());
        qw.setDeleted(Constants.ZERO);
        //查询全部工单数据
        List<WorkorderExtListVO> orderList = workorderExtMapper.selectList(qw);
        //已完工数量
        int doneNum=0;
        //已分配数量
        //已报工工单(包括工单状态:已报工、已入库)的完工数量(包括:合格、不良、报废)
        //+未报工工单(包括工单状态:已创建、已备料、已检验、已完工)的已分配数量
        int distributNum=0;
        //已分配未报工数量=未报工工单(工单状态:已创建、已备料、已检验、已完工)的计划生产数量之和;
        int distributeNoDoneNum=0;
        //合格数量=已报工工单(工单状态:已报工、已入库)产出为合格的数量之和;
        int qulifiedNum=0;
        //不良数量=已报工工单(工单状态:已报工、已入库)产出为不良的数量之和;
        int unqulifiedNum =0;
        int allOrderNum =0;
        if(orderList!=null && orderList.size()>0){
            QueryWorkorderRecordExtDTO rw = new QueryWorkorderRecordExtDTO();
            rw.setPlanId(param.getPlanId());
            rw.setDeleted(Constants.ZERO);
            //查询全部工单产出和投料数据
            List<WorkorderRecordExtListVO> allRecordList = workorderRecordExtMapper.selectListNew(rw);
            for(WorkorderExtListVO order : orderList){
                if(Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.cancel)){
                    //取消的工单不累计数量
                    continue;
                }
                if(Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.create)
                        ||Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.material)
                        ||Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.producing)
                        ||Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.check)
                        ||Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.done)){
                    //统计已分配未报工数量
                    distributeNoDoneNum += Constants.formatIntegerNum(order.getPlanNum());
                }
                if(Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.baogong)
                        ||Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.producing)
                        || Constants.equalsInteger(order.getStatus(),Constants.WORKORDER_STATUS.instock)){
                    doneNum += Constants.formatIntegerNum(order.getUnqualifiedNum()) + Constants.formatIntegerNum(order.getQualifiedNum());
                    int tNum =Constants.formatIntegerNum(order.getUnqualifiedNum()) + Constants.formatIntegerNum(order.getQualifiedNum());
                    distributNum += tNum;
                    allOrderNum += tNum;
                }else {
                    distributNum += Constants.formatIntegerNum(order.getPlanNum());
                }
 
                List<WorkorderRecordExtListVO> rList = getRecordListById(order.getId(),allRecordList);
                if(rList!=null){
                    for(WorkorderRecordExtListVO item : rList){
                        if(Constants.equalsInteger(item.getType(),Constants.WORKORDER_RECORD_TYPE.produce)
                                && item.getOmodel()!=null
                                && (Constants.equalsInteger(item.getOmodel().getStatus() ,Constants.WORKORDER_STATUS.baogong)
                                ||Constants.equalsInteger(item.getOmodel().getStatus() ,Constants.WORKORDER_STATUS.instock))){
                            //如果是合格产出,累计数量
                            qulifiedNum += Constants.formatBigdecimal(BigDecimal.valueOf(item.getQualifiedNum())).intValue();
                            //如果是不良产出,累计数量
                            unqulifiedNum += Constants.formatBigdecimal(BigDecimal.valueOf(item.getUnqualifiedNum())).intValue();
                        }
                    }
                }
            }
        }
        json.put(Constants.STATISTIC.distributeNoDone,distributeNoDoneNum);
        json.put(Constants.STATISTIC.done,doneNum);
        json.put(Constants.STATISTIC.distribute,distributNum);
        json.put(Constants.STATISTIC.qulified,qulifiedNum);
        json.put(Constants.STATISTIC.unqulified,unqulifiedNum);
 
        UpdateWrapper updateWrapper = new UpdateWrapper();
        Plans p = new Plans();
        p.setId(param.getPlanId());
        p.setStatisticInfo(json.toJSONString());
        p.setUpdateTime(DateUtil.getCurrentDate());
        if( Constants.formatIntegerNum(plan.getNum())  <= allOrderNum){
            //如果满足计划已完工,更新计划状态
            p.setStatus(Constants.PLAN_STATUS.done);
            if(!Objects.isNull(plan.getWorkPlansId())){
                //更新主订单数据信息
                if(plansMapper.selectCount(new QueryWrapper<Plans>()
                        .in("STATUS",0,1,4,5)
                        .eq("DELETED",Constants.ZERO)
                        .ne("id",p.getId())
                        .eq("WORK_PLANS_ID",plan.getWorkPlansId()))<=Constants.ZERO){
                    WorkPlans  workPlans = workPlansExtMapper.selectById(plan.getWorkPlansId());
                    if(!Objects.isNull(workPlans)){
                        workPlans.setStatus(Constants.WORKPLANHISTORY_TYPE.done);
                        workPlans.setUpdateTime(new Date());
                        workPlansExtMapper.updateById(workPlans);
                        planHistoryExtMapper.insert(initPlanHistoryByModel(workPlans,null,Constants.WORKPLANHISTORY_TYPE.done));
                    }
                };
            }
            //
            plan.getWorkPlansId();
 
            updateWrapper.set("STATUS",p.getStatus());
            if(Constants.equalsInteger(plan.getStatus(),Constants.PLAN_STATUS.distribute)){
                //如果已分配
                planHistoryExtMapper.insertBatch(Arrays.asList(PlansExtServiceImpl.initHistoryByModel(plan,null,Constants.PLANHISTORY_TYPE.done)));
            }
//          planHistoryService.create(PlansExtServiceImpl.initHistoryByModel(plan,null,Constants.PLANHISTORY_TYPE.done));
        }
        //更新统计信息
//        plansExtMapper.updateById(p);
        updateWrapper.eq("ID",param.getPlanId());
        updateWrapper.set("STATISTIC_INFO",json.toJSONString());
        updateWrapper.set("UPDATE_TIME",DateUtil.getCurrentDate());
        plansExtMapper.update(null,updateWrapper);
//        Workorder order = new Workorder();
//        order.setUpdateTime(DateUtil.getCurrentDate());
//        //已关闭
//        order.setId(param.getId());
//        workorderExtMapper.updateById(order);
 
    }
 
    /**
     * 检测数据有效性
     * @param param
     * @param user
     * @throws BusinessException
     */
    private void checkUserAndGroup(Workorder param, LoginUserInfo user) throws BusinessException{
        QueryDeviceExtDTO ud = new QueryDeviceExtDTO();
        ud.setDeleted(Constants.ZERO);
        ud.setId(param.getProGroupId());
        ud.setRootDepartId(user.getRootDepartment().getId());
        //查询用户设备关联关系
        DeviceExtListVO d = deviceExtMapper.selectByModel( ud );
        if(d == null){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,生产设备信息不正确,请刷新页面重试!");
        }
 
        QueryUserDeviceExtDTO t = new QueryUserDeviceExtDTO();
        t.setDeleted(Constants.ZERO);
        t.setUserIdList(param.getProUserList());
        t.setDeviceId(param.getProGroupId());
        //查询班组的公司级部门编码和计划公司级编码一致
        t.setUmodelComDepartId(param.getDepartId());
        //查询用户设备关联关系
        List<UserDeviceExtListVO> ulist = userDeviceExtMapper.selectList( t );
        if(ulist == null){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,生产人员信息不正确,请刷新页面重试!");
        }
        if(ulist.size() < param.getProUserList().size()){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,存在生产人员信息不正确,请刷新页面重试!");
        }
        List<WorkorderUser> userList = new ArrayList<>();
        for(UserDeviceExtListVO uModel : ulist){
            WorkorderUser u = new WorkorderUser();
            u.setProUserId(uModel.getUserId());
            u.setPlanId(param.getId());
            u.setCreateUser(user.getId());
            u.setDeleted(Constants.ZERO);
            u.setCreateTime(DateUtil.getCurrentDate());
            u.setRootDepartId(param.getRootDepartId());
            u.setDepartId(param.getDepartId());
            userList.add(u);
        }
        param.setWorkorderUserList(userList);
    }
    /**
     * 检测数据有效性
     * @param param
     * @param user
     * @throws BusinessException
     */
    private void checkUserAndGroupOld(Workorder param, LoginUserInfo user) throws BusinessException{
        QueryUserDeviceExtDTO ud = new QueryUserDeviceExtDTO();
        ud.setDeleted(Constants.ZERO);
        ud.setId(param.getUserDeivceId());
        //查询用户设备关联关系
        UserDeviceExtListVO uModel = userDeviceExtMapper.selectByModel( ud );
        if(uModel == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,生产人员及设备信息不正确,请刷新页面重试!");
        }
        //查询人员部门信息
        DepartmentExtListVO depart = departmentExtService.getModelById(user.getCompany().getId(),uModel.getUmodel().getDepartmentId());
        if(depart == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,生产人员班组信息不存在,请刷新页面重试!");
        }
        /* if(!Constants.equalsInteger(depart.getType(),Constants.DEPART_TYPE.group)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,选择班组错误,请刷新页面重试!");
        }*/
        //查询班组的公司级部门编码和计划公司级编码是否一致,不一致则报错
        Integer comDepartId = departmentExtService.getComDepartId(depart);
        if(!Constants.equalsInteger(comDepartId,param.getDepartId())){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,班组非计划所属公司组织,请刷新页面重试!");
        }
        //生产班组(设备)
        param.setProGroupId(uModel.getDeviceId());
        //生产人员
        param.setProUserId(uModel.getUserId());
    }
 
    @Override
    @Transactional
    public ApiResponse preparationWTransfer(String ids, LoginUserInfo userInfo){
        //根据 工单 查询所有工单需要生成转库单
        List<WTransferBean> wTransferBeanList = wTransferExtMapper.selectListByWorkorder(ids,userInfo.getId());
        if(wTransferBeanList.size()==Constants.ZERO){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,未查询转换转库单信息!");
        }
 
        //根据工单查询所有工单生产需要备料 物料信息
        List<WTransferDetailForWOrderBean> wTransferDetailBeanList = wTransferDetailExtMapper.selectListByWorkorder(ids);
        if(wTransferDetailBeanList.size()==Constants.ZERO){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,未查询到需要备料物料!");
        }
        List<WTransferDetailForWOrderBean> saveBeanList = new ArrayList<>();
        for (WTransferBean i:wTransferBeanList ) {
            //如果是正常工单,分有BOM 和无BOM组成的情况
            if(StringUtils.isBlank(i.getWorkorderId())){
                //排除工单编码为空的情况
                continue;
            }
            List<WTransferDetailBean> wTransferDetailBeans = new ArrayList<>();
            if(i.getBackOrderId() !=null){
                //如果是返工返修工单,根据其申请篮筐数据进行备料,(按照篮筐的物料编码和工序编码去重备料)
                Backorder backorder  = new Backorder();
                backorder.setId(i.getBackOrderId());
                backorder=  backorderMapper.selectByModel(backorder);
                if(backorder == null){
                    throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,查询关联返修申请单有误,请联系管理员!");
                }
                String[] orderIds = i.getWorkorderId().split(",");
                int tnum = 0;
                for(String s : orderIds){
                    //查询全部工单,统计数据
                    Workorder mp = new Workorder();
                    mp.setDeleted(Constants.ZERO);
                    mp.setId(Integer.parseInt(s));
                    mp.setRootDepartId(userInfo.getRootDepartment().getId());
                    mp = workorderExtMapper.selectOne(mp);
                    tnum += Constants.formatIntegerNum(mp.getPlanNum());
                }
                WTransferDetailBean wTransferDetailBean = new WTransferDetailBean();
                wTransferDetailBean.setOutPlanNum(new BigDecimal(tnum));
                wTransferDetailBean.setInWarehouseId(i.getInWarehouseId());
                wTransferDetailBean.setInLocationId(i.getInLocationId());
                wTransferDetailBean.setOutWarehouseId(i.getOutWarehouseId());
                wTransferDetailBean.setInUserId(i.getInUserId());
                wTransferDetailBean.setProcedureId(backorder.getProcedureId());
                wTransferDetailBean.setMaterialId(backorder.getMaterialId());
                wTransferDetailBean.setUnitId(backorder.getUnitId());
                wTransferDetailBean.setQualityType(Constants.ONE);
                wTransferDetailBeans.add(wTransferDetailBean);
            }else{
                String[] orderIds = i.getWorkorderId().split(",");
                List<WTransferDetailBean> tempBomList = new ArrayList<>();
                List<WTransferDetailBean> tempNoBomList = new ArrayList<>();
                for(String s : orderIds){
                    //遍历工单查询工单的明细,生成转库明细
                    //查询全部bom组成数据,如果有BOM配置,按照BOM组成进行投料,如果没有BOM配置,则投料物料为待生产库位的物料本身
                    Workorder mp = new Workorder();
                    mp.setDeleted(Constants.ZERO);
                    mp.setId(Integer.parseInt(s));
                    mp.setRootDepartId(userInfo.getRootDepartment().getId());
                    mp = workorderExtMapper.selectOne(mp);
                    QueryBomDetailExtDTO bdparam = initBomParam(userInfo,mp);
                    if(bdparam!=null){
                        //如果有bom配置,安装物料组成进行备料
                        List<BomDetailExtListVO> bomDetailList  = bomDetailExtMapper.selectList(bdparam);
                        if(bomDetailList!=null && bomDetailList.size()>0){
                            for(BomDetailExtListVO dm : bomDetailList){
                                // 如果物料和工序都相同,产生一条转出库明细
                                WTransferDetailBean tBean = getExistedDateFromList(dm.getMaterialId(),null,tempBomList);
                                if(tBean ==null){
                                    WTransferDetailBean wTransferDetailBean = new WTransferDetailBean();
                                    wTransferDetailBean.setOutPlanNum(Constants.formatBigdecimal(dm.getNum()).multiply(new BigDecimal(Constants.formatIntegerNum(mp.getPlanNum()))));
                                    wTransferDetailBean.setInWarehouseId(i.getInWarehouseId());
                                    wTransferDetailBean.setInLocationId(i.getInLocationId());
                                    wTransferDetailBean.setOutWarehouseId(i.getOutWarehouseId());
                                    wTransferDetailBean.setInUserId(i.getInUserId());
                                    wTransferDetailBean.setMaterialId(dm.getMaterialId());
                                    this.dealProcedure(wTransferDetailBean);
//                                    wTransferDetailBean.setProceduresId(dm.getProcedureId());
                                    wTransferDetailBean.setUnitId(dm.getUnitId());
                                    wTransferDetailBean.setQualityType(Constants.ZERO);
                                    tempBomList.add(wTransferDetailBean);
                                }else{
                                    tBean.setOutPlanNum(tBean.getOutPlanNum().add(Constants.formatBigdecimal(dm.getNum()).multiply(new BigDecimal(Constants.formatIntegerNum(mp.getPlanNum())))));
                                }
                            }
                        }
                    }else{
                        //如果没有bom,进行上一道工序的物料备料
                        Integer lastPId = getLastProcudureId(mp.getProcedureId(),mp);
                        if(lastPId==null){
                            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "未查询到生产物料上一道工序数据");
                        }
                        // 如果物料和工序都相同,产生一条转出库明细
                        WTransferDetailBean tBean = getExistedDateFromList(mp.getMaterialId(),lastPId,tempNoBomList);
                        if(tBean ==null){
                            WTransferDetailBean wTransferDetailBean = new WTransferDetailBean();
                            wTransferDetailBean.setOutPlanNum(new BigDecimal(Constants.formatIntegerNum(mp.getPlanNum())));
                            wTransferDetailBean.setInWarehouseId(i.getInWarehouseId());
                            wTransferDetailBean.setInLocationId(i.getInLocationId());
                            wTransferDetailBean.setOutWarehouseId(i.getOutWarehouseId());
                            wTransferDetailBean.setInUserId(i.getInUserId());
                            wTransferDetailBean.setProcedureId(lastPId);
                            wTransferDetailBean.setMaterialId(mp.getMaterialId());
                            wTransferDetailBean.setUnitId(mp.getUnitId());
                            wTransferDetailBean.setQualityType(Constants.ZERO);
                            tempNoBomList.add(wTransferDetailBean);
                        }else{
                            tBean.setOutPlanNum(tBean.getOutPlanNum().add(Constants.formatBigdecimal(new BigDecimal(Constants.formatIntegerNum(mp.getPlanNum())))));
                        }
                    }
                }
                if(tempBomList.size()>0){
                    wTransferDetailBeans.addAll(tempBomList);
                }
                if(tempNoBomList.size()>0){
                    wTransferDetailBeans.addAll(tempNoBomList);
                }
            }
 
            i.setOrigin(Constants.ZERO);
            i.setOriginType(Constants.ONE);
            i.setOriginId(i.getWorkorderId());
            i.setOriginCode(i.getWorkorderCode());
            i.setWTransferDetailBeanList(wTransferDetailBeans);
            wTransferService.saveBean(i,userInfo);
            saveBeanList.clear();
        };
        //更新工单状态
        List<WorkorderHistory> whList = new ArrayList<>();
        for (String s:ids.split(",")) {
            Workorder workorder = new Workorder();
            workorder.setId(Integer.parseInt(s));
            workorder.setUpdateUser(userInfo.getId());
            workorder.setUpdateTime(DateUtil.getCurrentDate());
            workorder.setStatus(Constants.WORKORDER_STATUS.material);
            //工单历史数据
            whList.add(WorkorderExtServiceImpl.initHistoryByModel(workorder,userInfo.getId(),Constants.WORKORDER_HISTORY_STATUS.material));
            workorderMapper.updateById(workorder);
        }
        if(whList.size()>0){
            workorderHistoryExtMapper.insertBatch(whList);
        }
 
        return ApiResponse.success("创建成功");
    }
 
    private Integer getLastProcudureId(Integer proceduresId, Workorder mp) {
        List<RouteProcedure> rpList = null;
        if (mp.getBomModel() != null && mp.getBomModel().getRouteId() != null) {
            //
            if (mp.getBomModel().getRouteId() != null) {
                RouteProcedure rp = new RouteProcedure();
                rp.setDeleted(Constants.ZERO);
                rp.setRouteId(mp.getBomModel().getRouteId());
                rp.setDepartId(mp.getFactoryId());
                rpList = routeProcedureExtMapper.selectList(new QueryWrapper<>(rp).orderByAsc("SORTNUM"));
            }
        } else {
            //没有bom的情况
            RouteProcedure rp = new RouteProcedure();
            rp.setDeleted(Constants.ZERO);
            rp.setDepartId(mp.getFactoryId());
            rpList = routeProcedureExtMapper.selectList(new QueryWrapper<>(rp).exists("select bom.id from bom where bom.material_id=" + mp.getMaterialId() + " and bom.route_id =route_procedure.route_id and bom.deleted=0").orderByAsc("SORTNUM"));
 
        }
        if (rpList != null && rpList.size() > 0) {
            for (int i = 0; i < rpList.size(); i++) {
                RouteProcedure r = rpList.get(i);
                if (Constants.equalsInteger(r.getProcedureId(), proceduresId)) {
                    //如果工序相同,找下一工序
                    if (i >0) {
                        return rpList.get(i - 1).getProcedureId();
                    }
                }
            }
        }
    return null;
    }
 
    private QueryBomDetailExtDTO initBomParam(LoginUserInfo user, Workorder mp)  throws BusinessException{
        QueryBomExtDTO bb = new QueryBomExtDTO();
        bb.setDepartId(mp.getDepartId());
        bb.setDeleted(Constants.ZERO);
        bb.setRootDepartId(user.getRootDepartment().getId());
        bb.setMaterialId(mp.getMaterialId());
        bb.setProcedureId(mp.getProcedureId());
        BomExtListVO versionBom = bomExtMapper.selectByModel( bb);
        if(versionBom == null || StringUtils.isBlank(versionBom.getVersion()) || versionBom.getBomVersionId() == null){
            return  null;
            // throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,该工单物料BOM信息配置有误,请联系管理员!");
        }
        mp.setBomModel(versionBom);
        QueryBomDetailExtDTO  bom = new QueryBomDetailExtDTO();
        bom.setDeleted(Constants.ZERO);
        bom.setBomId(versionBom.getBomVersionId());
//        bom.setProcedureId(mp.getProcedureId());
        bom.setWorkorderId(mp.getId());
        return bom;
    }
 
    /**
     * 如果物料和工序都相同,产生一条转出库明细
     * @param mId
     * @param tempList
     * @return
     */
    private WTransferDetailBean getExistedDateFromList(Integer mId,Integer pId, List<WTransferDetailBean> tempList) {
        for(WTransferDetailBean tBean : tempList){
            if((pId!=null && Constants.equalsInteger(tBean.getProcedureId(),pId))&& Constants.equalsInteger(mId,tBean.getMaterialId())){
                return tBean;
            }
            if(pId==null && Constants.equalsInteger(mId,tBean.getMaterialId())){
                return tBean;
            }
        }
        return null;
    }
 
    //    @Override
    @Transactional
    public ApiResponse preparationWTransferOld(String ids, LoginUserInfo userInfo){
        List<Workorder> workorderList = workorderMapper.selectList(new QueryWrapper<Workorder>()
                .apply(" 1 = 1 and  find_in_set( workorder.id ,'"+ids+"') and status = 0  ")
        );
        if(workorderList.size()==Constants.ZERO){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,未查询到工单信息!");
        }
        //根据 工单 查询所有工单需要生成转库单
        List<WTransferBean> wTransferBeanList = wTransferExtMapper.selectListByWorkorder(ids,userInfo.getId());
        if(wTransferBeanList.size()==Constants.ZERO){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,未查询转换转库单信息!");
        }
        //判断是否存在多个转出仓库
        if(this.verifyProceduresId(wTransferBeanList)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,当前备料工序存在多个!");
        };
        //根据工单查询所有工单生产需要备料 物料信息
        List<WTransferDetailForWOrderBean> wTransferDetailBeanList = wTransferDetailExtMapper.selectListByWorkorder(ids);
        if(wTransferDetailBeanList.size()==Constants.ZERO){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,未查询到需要备料物料!");
        }
        List<WTransferDetailForWOrderBean> saveBeanList = new ArrayList<>();
        for (WTransferBean i:wTransferBeanList ) {
            StringBuffer sbf_id = new StringBuffer();
            StringBuffer sbf_code = new StringBuffer();
 
            for (Workorder j:workorderList) {
                    sbf_id.append(","+j.getId());
                    sbf_code.append(","+j.getCode());
            }
 
            List<WTransferDetailBean> wTransferDetailBeans = new ArrayList<>();
            for (WTransferDetailForWOrderBean j:wTransferDetailBeanList) {
                if(Objects.equals(i.getInUserId(),j.getInUserId())&&Objects.equals(i.getInWarehouseId(),j.getInWarehouseId())&&Objects.equals(i.getInLocationId(),j.getInLocationId())){
                    WTransferDetailBean wTransferDetailBean = new WTransferDetailBean();
                    wTransferDetailBean.setOutPlanNum(j.getOutPlanNum());
                    wTransferDetailBean.setInWarehouseId(j.getInWarehouseId());
                    wTransferDetailBean.setInLocationId(j.getInLocationId());
                    wTransferDetailBean.setOutWarehouseId(j.getOutWarehouseId());
                    wTransferDetailBean.setInUserId(j.getInUserId());
                    wTransferDetailBean.setProceduresId(j.getProceduresId());
                    //查询出对象数据 转换
                    if(Objects.isNull(j.getMaterialId())){
                        wTransferDetailBean.setMaterialId(j.getWorkorderMaterialId());
                        wTransferDetailBean.setUnitId(j.getWorkorderUnitlId());
                        //根据工单生产物料 查询BOM 获取工艺路线  配合当前工单工序 查询到上一个工序
                        this.dealProcedureId(wTransferDetailBean);
                    }else{
                        wTransferDetailBean.setMaterialId(j.getMaterialId());
                        wTransferDetailBean.setUnitId(j.getUnitId());
//                        wTransferDetailBean.setProcedureId(j.getProceduresId());
                    }
                    if(j.getType() == Constants.ZERO){
                        wTransferDetailBean.setQualityType(Constants.ZERO);
                    }else{
                        wTransferDetailBean.setQualityType(Constants.ONE);
                    }
                    wTransferDetailBeans.add(wTransferDetailBean);
                }
            }
            i.setOrigin(Constants.ZERO);
            i.setOriginType(Constants.ONE);
            i.setOriginId(sbf_id.toString().substring(1,sbf_id.length()));
            i.setOriginCode(sbf_code.toString().substring(1,sbf_code.length()));
            i.setWTransferDetailBeanList(wTransferDetailBeans);
            wTransferService.saveBean(i,userInfo);
            saveBeanList.clear();
        };
        //更新工单状态
        for (Workorder j:workorderList) {
             j.setStatus(Constants.ONE);
             workorderMapper.updateById(j);
        }
 
        return ApiResponse.success("创建成功");
    }
 
 
    public void dealProcedureId(WTransferDetailBean wTransferDetailBean){
        Bom b = bomExtMapper.selectOne(new QueryWrapper<Bom>()
                .eq("MATERIAL_ID",wTransferDetailBean.getMaterialId())
                .eq("DELETED",Constants.ZERO)
                .eq("STATUS",Constants.ONE)
        );
        if(Objects.isNull(b)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "未查询到生产物料BOM数据");
        }
        RouteProcedure currentRouteProcedure   = routeProcedureExtMapper.selectOne(new QueryWrapper<RouteProcedure>()
                .eq("ROUTE_ID",b.getRouteId())
                .eq("PROCEDURE_ID",wTransferDetailBean.getProceduresId())
                .last(" limit 1 ")
        );
 
        if(Objects.isNull(currentRouteProcedure)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "未查询到生产物料工艺路线数据");
        }
        RouteProcedure  previousRouteProcedure = routeProcedureExtMapper.selectOne(new QueryWrapper<RouteProcedure>()
                .eq("ROUTE_ID",b.getRouteId())
                .apply(" SORTNUM <  "+currentRouteProcedure.getSortnum()+" ")
                .orderByDesc(" SORTNUM ")
                .last(" limit 1 ")
        );
        wTransferDetailBean.setProcedureId(previousRouteProcedure.getProcedureId());
 
 
    }
 
    @Override
    public synchronized  String  getNextCode(Integer comId ){
        String prefix =   DateUtil.getDate(new Date(),"yyyyMMdd") +"-";
        Integer countNum  = RedisUtil.getObject(redisTemplate, Constants.RedisKeys.COM_WORKORDER_CODE_KEY+comId,Integer.class);
        countNum = Constants.formatIntegerNum(countNum)+1;
        //更新缓存
        RedisUtil.addObject(redisTemplate,Constants.RedisKeys.COM_WORKORDER_CODE_KEY+comId,countNum);
        String nextIndex =Integer.toString( countNum);
        return prefix + StringUtils.leftPad(nextIndex,4,"0");
    }
 
    public Boolean verifyProceduresId(List<WTransferBean> wTransferBenaList){
        Boolean flag = false;
        String proceduresId = "";
        Integer type = Constants.ZERO ;
        for (WTransferBean w:wTransferBenaList) {
            if(proceduresId.contains(w.getProceduresId()+"")){
                continue;
            }else{
                proceduresId+=Constants.formatIntegerNum(w.getProceduresId())+",";
                type = type + Constants.ONE;
            }
        }
        if(type > Constants.ONE){
            flag = true;
        }
        return flag;
    }
 
 
    /**
     *
     * @param deviceIds 设备主键 ,分割
     * @param inIds  入库单主键 ,分割
     * @param userInfo 用户信息
     * @return
     */
    @Override
    public ApiResponse<FinishedInBean> finishedDetail(String deviceIds,String inIds,LoginUserInfo userInfo){
        //根据设备主键获取设备信息
        List<Device> deviceList = deviceMapper.selectList(
                new QueryWrapper<Device>()
                        .eq("deleted",Constants.ZERO)
                        .apply(" find_in_set(id,'"+deviceIds+"') ")
        );
        if(deviceList.size()==Constants.ZERO){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,未查询到设备信息!");
        }
        CompanyUser companyUser  = companyUserExtMapper.selectOne(new QueryWrapper<CompanyUser>()
                .eq("USER_ID",userInfo.getId())
                .eq("ROOT_DEPART_ID",userInfo.getRootDepartment().getId())
                .eq("deleted",0)
        );
        if(Objects.isNull(companyUser)){
            throw new BusinessException(ResponseStatus.OBJECT_EMP.getCode(), "未查询到操作员工信息");
        }
        Department department = departmentExtMapper.selectById(companyUser.getDepartmentId());
        if(Objects.isNull(department)){
            throw new BusinessException(ResponseStatus.OBJECT_EMP.getCode(), "未查询到操作员工班组信息");
        }
 
        //待生产货位
        StringBuffer produceLocationIds = new StringBuffer();
        //已完工货位
        StringBuffer finishLocationIds = new StringBuffer();
        //全部货位
        StringBuffer allIds = new StringBuffer();
        for (int i = 0; i < deviceList.size(); i++) {
            if(i==Constants.ZERO){
                allIds.append(deviceList.get(i).getProduceWarehouseLocationId());
                allIds.append(","+deviceList.get(i).getFinishWarehouseLocationId());
                produceLocationIds.append(deviceList.get(i).getProduceWarehouseLocationId());
                finishLocationIds.append(deviceList.get(i).getFinishWarehouseLocationId());
            }else{
                allIds.append(","+deviceList.get(i).getProduceWarehouseLocationId());
                allIds.append(","+deviceList.get(i).getFinishWarehouseLocationId());
                produceLocationIds.append(","+deviceList.get(i).getProduceWarehouseLocationId());
                finishLocationIds.append(","+deviceList.get(i).getFinishWarehouseLocationId());
            }
        }
        FinishedInBean finishedInBean = new FinishedInBean();
        finishedInBean.setWorker(companyUser.getName());
        finishedInBean.setGroupName(department.getName());
        finishedInBean.setDeviceList(deviceList);
        finishedInBean.setFinishedQualified(
                appliancesExtMapper.getTypeNumByLocationId(finishLocationIds.toString(),Constants.APPLIANCES_TYPE_LABLE.qualified,null,null));
        finishedInBean.setFinishedUndesirable(
                appliancesExtMapper.getTypeNumByLocationId(finishLocationIds.toString(),Constants.APPLIANCES_TYPE_LABLE.rejects,null,null));
        finishedInBean.setFinishedScrap(
                appliancesExtMapper.getTypeNumByLocationId(finishLocationIds.toString(),Constants.APPLIANCES_TYPE_LABLE.scrap,null,null));
        finishedInBean.setQualified(
                appliancesExtMapper.getTypeNumByLocationId(produceLocationIds.toString(),Constants.APPLIANCES_TYPE_LABLE.qualified,null,inIds));
        finishedInBean.setUndesirable(
                appliancesExtMapper.getTypeNumByLocationId(produceLocationIds.toString(),Constants.APPLIANCES_TYPE_LABLE.rejects,null,inIds));
        finishedInBean.setSurplus(appliancesExtMapper.getNumByInIds(inIds));
        List<AppliancesMaterialBean> appliancesMaterialBeanList = appliancesExtMapper.getMaterialByLocationId(allIds.toString());
        for (AppliancesMaterialBean appliancesMaterialBean:appliancesMaterialBeanList) {
            appliancesMaterialBean.setFinishedQualified(
                    appliancesExtMapper.getTypeNumUnitByLocationId(finishLocationIds.toString(),Constants.APPLIANCES_TYPE_LABLE.qualified,appliancesMaterialBean.getMaterialId(),null));
            appliancesMaterialBean.setFinishedUndesirable(
                    appliancesExtMapper.getTypeNumUnitByLocationId(finishLocationIds.toString(),Constants.APPLIANCES_TYPE_LABLE.rejects,appliancesMaterialBean.getMaterialId(),null));
            appliancesMaterialBean.setFinishedScrap(
                    appliancesExtMapper.getTypeNumUnitByLocationId(finishLocationIds.toString(),Constants.APPLIANCES_TYPE_LABLE.scrap,appliancesMaterialBean.getMaterialId(),null));
            appliancesMaterialBean.setQualified(
                    appliancesExtMapper.getTypeNumUnitByLocationId(produceLocationIds.toString(),Constants.APPLIANCES_TYPE_LABLE.qualified,appliancesMaterialBean.getMaterialId(),inIds));
            appliancesMaterialBean.setUndesirable(
                    appliancesExtMapper.getTypeNumUnitByLocationId(produceLocationIds.toString(),Constants.APPLIANCES_TYPE_LABLE.rejects,appliancesMaterialBean.getMaterialId(),inIds));
        }
        finishedInBean.setAppliancesMaterialBeanList(appliancesMaterialBeanList);
        if(StringUtils.isNotBlank(inIds)){
            List<FinishedInBillBean> finishedInBillBeanList = wOutboundExtMapper.finishedInBill(null,inIds);
            for (FinishedInBillBean finishedInBillBean:finishedInBillBeanList) {
                List<AppliancesMaterialBean>  appliancesMaterialBeans =  appliancesExtMapper.getMaterialByInIdLocationIds(finishedInBillBean.getId(),produceLocationIds.toString());
                for (AppliancesMaterialBean appliancesMaterialBean:appliancesMaterialBeans) {
                    appliancesMaterialBean.setQualified(appliancesExtMapper.getMaterialNumTypeByInIdLocationIds(finishedInBillBean.getId(),produceLocationIds.toString(),Constants.APPLIANCES_TYPE_LABLE.qualified,appliancesMaterialBean.getMaterialId()));
                    appliancesMaterialBean.setUndesirable(appliancesExtMapper.getMaterialNumTypeByInIdLocationIds(finishedInBillBean.getId(),produceLocationIds.toString(),Constants.APPLIANCES_TYPE_LABLE.rejects,appliancesMaterialBean.getMaterialId()));
                }
                finishedInBillBean.setAppliancesMaterialBeanList(appliancesMaterialBeans);
            }
            finishedInBean.setFinishedInBillBeanList(finishedInBillBeanList);
        }
        finishedInBean.setProduceLocationIds(produceLocationIds.toString());
 
        return ApiResponse.success(finishedInBean);
    }
 
 
    @Override
    @Transactional
    public ApiResponse<Integer> dataToWtWO(String deviceIds,String inIds,LoginUserInfo userInfo){
        //根据设备主键获取设备信息
        List<Device> deviceList = deviceMapper.selectList(
                new QueryWrapper<Device>()
                        .select( " * , ( select w.WAREHOUSE_ID from warehouse_location w where w.id = device.PRODUCE_WAREHOUSE_LOCATION_ID limit 1  ) as produceWarehouseId ,  ( select w.WAREHOUSE_ID  from warehouse_location w where w.id = device.FINISH_WAREHOUSE_LOCATION_ID limit 1  ) as finishWarehouseId  " )
                        .eq("deleted",Constants.ZERO)
                        .apply(" find_in_set(id,'"+deviceIds+"') ")
        );
        if(deviceList.size()==Constants.ZERO){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,未查询到设备信息!");
        }
        CompanyUser companyUser  = companyUserExtMapper.selectOne(
                new QueryWrapper<CompanyUser>()
                        .eq("USER_ID",userInfo.getId())
                        .eq("root_depart_id",userInfo.getRootDepartment().getId())
                        .eq("DELETED",Constants.ZERO)
        );
        if(Objects.isNull(companyUser)){
            throw new BusinessException(ResponseStatus.OBJECT_EMP.getCode(), "未查询到操作员工信息");
        }
        Department department = departmentExtMapper.selectById(companyUser.getDepartmentId());
        if(Objects.isNull(department)){
            throw new BusinessException(ResponseStatus.OBJECT_EMP.getCode(), "未查询到操作员工班组信息");
        }
        Integer produceId = null;
        //待生产货位
        StringBuffer produceLocationIds = new StringBuffer();
        //已完工货位
        StringBuffer finishLocationIds = new StringBuffer();
        //全部货位
        StringBuffer allIds = new StringBuffer();
        //全部仓库
        Set<Integer> allWareHouse = new HashSet<>();
        for (int i = 0; i < deviceList.size(); i++) {
            allWareHouse.add(deviceList.get(i).getFinishWarehouseId());
            allWareHouse.add(deviceList.get(i).getProduceWarehouseId());
            if(i==Constants.ZERO){
                produceId = deviceList.get(i).getProcedureId();
                allIds.append(deviceList.get(i).getProduceWarehouseLocationId());
                allIds.append(","+deviceList.get(i).getFinishWarehouseLocationId());
                produceLocationIds.append(deviceList.get(i).getProduceWarehouseLocationId());
                finishLocationIds.append(deviceList.get(i).getFinishWarehouseLocationId());
            }else{
                allIds.append(","+deviceList.get(i).getProduceWarehouseLocationId());
                allIds.append(","+deviceList.get(i).getFinishWarehouseLocationId());
                produceLocationIds.append(","+deviceList.get(i).getProduceWarehouseLocationId());
                finishLocationIds.append(","+deviceList.get(i).getFinishWarehouseLocationId());
            }
        }
        List<AppliancesFroWTransferBean> appliancesFroWTransferBeanList =
                appliancesExtMapper.getDataToWTransferNew(produceId,allIds.toString(),inIds);
                //appliancesExtMapper.getDataToWTransfer(produceId,produceLocationIds.toString(),finishLocationIds.toString(),inIds,Constants.APPLIANCES_TYPE_LABLE.qualified,Constants.APPLIANCES_TYPE_LABLE.rejects,Constants.APPLIANCES_TYPE_LABLE.scrap);
        if(appliancesFroWTransferBeanList.size() == Constants.ZERO){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,未查询到转库数据信息!");
        }
        //创建转库单 w_transfer
        WTransfer wTransfer = new WTransfer();
        wTransfer.setOrigin(Constants.ONE);
//        wTransfer.setOriginType(Constants.TWO);
        wTransfer.setRootDepartId(userInfo.getRootDepartment().getId());
        wTransfer.setOutDepartId(userInfo.getCurComDepartment().getId());
        wTransfer.setInDepartId(userInfo.getCurComDepartment().getId());
        wTransfer.setOutWarehouseId(appliancesFroWTransferBeanList.get(Constants.ZERO).getOutWarehouseId());
//        wTransfer.setInWarehouseId(appliancesFroWTransferBeanList.get(Constants.ZERO).getInWarehouseId());
        wTransfer.setOutUserId(userInfo.getId());
        //根据工序 得到入库仓库
        Procedures procedures = proceduresMapper.selectById(produceId);
        if(Objects.isNull(procedures)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,未查询到工序信息(创建转库单)!");
        }
        Warehouse warehouseForIn = warehouseMapper.selectById(procedures.getProduceWarehouseId());
        if(Objects.isNull(warehouseForIn)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,未查询到入库仓库信息(创建转库单)!");
        }
        wTransfer.setInUserId(warehouseForIn.getManagerId());
        wTransfer.setOutPlandate(new Date());
        wTransfer.setInPlandate(new Date());
        wTransfer.setType(4);
        wTransfer.setOutActdate(new Date());
        wTransfer.setCreateTime(new Date());
        wTransfer.setCreateUser(userInfo.getId());
        wTransfer.setCode(wTransferService.getNextCode(userInfo.getCompany().getId()));
        wTransfer.setValidDate(new Date());
        wTransfer.setStatus(Constants.ONE);
        wTransferExtMapper.insert(wTransfer);
 
        //创建转库单明细 w_transfer_detail
        for (AppliancesFroWTransferBean appliancesFroWTransferBean:appliancesFroWTransferBeanList) {
            WTransferDetail wTransferDetail = new WTransferDetail();
            wTransferDetail.setUnitId(appliancesFroWTransferBean.getUnitId());
            wTransferDetail.setMaterialId(appliancesFroWTransferBean.getMaterialId());
            if(StringUtils.isNotBlank(appliancesFroWTransferBean.getBatch())){
                wTransferDetail.setBatch(appliancesFroWTransferBean.getBatch());
            }
            wTransferDetail.setOutPlannum(appliancesFroWTransferBean.getOutNum());
            wTransferDetail.setOutActnum(appliancesFroWTransferBean.getOutNum());
            wTransferDetail.setOutWarehouseId(appliancesFroWTransferBean.getOutWarehouseId());
            wTransferDetail.setInWarehouseId(appliancesFroWTransferBean.getInWarehouseId());
            wTransferDetail.setCreateUser(userInfo.getId());
            wTransferDetail.setRootDepartId(userInfo.getRootDepartment().getId());
            wTransferDetail.setTransferId(wTransfer.getId());
            wTransferDetail.setOutDepartId(wTransfer.getOutDepartId());
            wTransferDetail.setInDepartId(wTransfer.getInDepartId());
            wTransferDetail.setOutLocationId(appliancesFroWTransferBean.getOutLocationId());
            wTransferDetail.setOutActdate(new Date());
            wTransferDetail.setQualityType(appliancesFroWTransferBean.getQualityType());
            if(Constants.equalsInteger(wTransferDetail.getQualityType(),Constants.QUALITIY_TYPE.scrap)){
                wTransferDetail.setInWarehouseId(appliancesFroWTransferBean.getInScrapWarehouseId());
            }else if(Constants.equalsInteger(wTransferDetail.getQualityType(),Constants.QUALITIY_TYPE.unqulified)){
                wTransferDetail.setInWarehouseId(appliancesFroWTransferBean.getInBadWarehouseId());
            } else{
                wTransferDetail.setInWarehouseId(appliancesFroWTransferBean.getInWarehouseId());
            }
            wTransferDetail.setProcedureId(appliancesFroWTransferBean.getProcedureId());
            wTransferDetailExtMapper.insert(wTransferDetail);
        }
 
        //转库单操作记录
        WHistory wHistoryTransfer = wTransfer.toWHistory(userInfo);
        wHistoryMapper.insert(wHistoryTransfer);
 
        List<Appliances> outWarehouseIdList = appliancesMapper.selectList(new QueryWrapper<Appliances>()
                .select(" WAREHOUSE_ID as warehouseId ")
                .apply(" find_in_set( LOCATION_ID , '"+allIds+"' ) " +
                        " and   not exists ( select 1  from w_outbound_record r inner join appliances ap " +
                        "      on r.APPLIANCES_ID = ap.ID " +
                        "      where 1 = 1 and  FIND_IN_SET(r.OUTBOUND_ID, '"+inIds+"' ) " +
                        "      and ap.id  = appliances.id  ) ")
                .apply("    not exists (  select 1 from workorder wo inner join workorder_record wr on wo.id = wr.WORKORDER_ID " +
                        " where wo.status in ( 0 , 1 , 3 ) and wr.TYPE = 0 and wr.APPLIANCES_ID = appliances.id and  wr.DELETED = 0 )  ")
                .groupBy(" WAREHOUSE_ID ")
        );
 
        List<Appliances> outDetailList = appliancesMapper.selectList(new QueryWrapper<Appliances>()
                .select(" WAREHOUSE_ID as warehouseId  , LOCATION_ID as locationId , MATERIAL_ID as materialId , " +
                        " ( select m.UNIT_ID from material_distribute m where m.id = appliances.MATERIAL_ID limit 1  ) as unitId ," +
                        " ifNull(sum(appliances.NUM),0) as num , BATCH , PROCEDURE_ID , QUALITY_TYPE ")
                .apply(" find_in_set( LOCATION_ID , '"+allIds+"' ) " +
                        " and   not exists ( select 1  from w_outbound_record r inner join appliances ap " +
                        "      on r.APPLIANCES_ID = ap.ID " +
                        "      where 1 = 1 and  FIND_IN_SET(r.OUTBOUND_ID, '"+inIds+"' ) " +
                        "      and ap.id  = appliances.id   ) ")
                .apply("    not exists (  select 1 from workorder wo inner join workorder_record wr on wo.id = wr.WORKORDER_ID " +
                        " where wo.status in ( 0 , 1 , 3 ) and wr.TYPE = 0 and wr.APPLIANCES_ID = appliances.id and  wr.DELETED = 0  )  ")
                .groupBy(" WAREHOUSE_ID ,LOCATION_ID , MATERIAL_ID , WORKORDER_ID ,PROCEDURE_ID , QUALITY_TYPE ,BATCH ")
        );
 
        List<Appliances> appliancesList = appliancesMapper.selectList(new QueryWrapper<Appliances>()
                .apply(" find_in_set( LOCATION_ID , '"+allIds+"' ) " +
                        " and   not exists ( select 1  from w_outbound_record r inner join appliances ap " +
                        "      on r.APPLIANCES_ID = ap.ID " +
                        "      where 1 = 1 and  FIND_IN_SET(r.OUTBOUND_ID, '"+inIds+"' ) " +
                        "      and ap.id  = appliances.id   ) ")
                .apply("    not exists (  select 1 from workorder wo inner join workorder_record wr on wo.id = wr.WORKORDER_ID " +
                        " where wo.status in ( 0 , 1 , 3 ) and wr.TYPE = 0 and wr.APPLIANCES_ID = appliances.id  and  wr.DELETED = 0 )  ")
        );
 
        for (Appliances i:outWarehouseIdList) {
            //生成出库单单头
            WOutbound wOutbound = new WOutbound();
            wOutbound.setCreateUser(userInfo.getId());
            wOutbound.setCreateTime(new Date());
            wOutbound.setRootDepartId(userInfo.getRootDepartment().getId());
            wOutbound.setBillType(Constants.WOUTBOUND_BILLTYPE.finish);
            wOutbound.setDepartId(userInfo.getComDepartment().getId());
            wOutbound.setCode(wOutboundService.getNextOutCode(userInfo.getCompany().getId()));
            wOutbound.setOrigin(Constants.ONE);
            wOutbound.setValidDate(new Date());
            wOutbound.setType(Constants.ZERO);
            wOutbound.setOriginType(Constants.WOUTBOUND_ORIGIN_TYPE.transfer);
            wOutbound.setOriginCode(wTransfer.getCode());
            wOutbound.setOriginId(wTransfer.getId());
            wOutbound.setUserId(userInfo.getId());
            wOutbound.setWarehouseId(i.getWarehouseId());
            wOutbound.setDealDate(new Date());
            wOutbound.setStatus(Constants.ONE);
            wOutbound.setPlanDate(wTransfer.getOutPlandate());
            //TODO 工序编码 wOutbound.setProcedureId();
            wOutboundExtMapper.insert(wOutbound);
            //获取仓库信息
            Warehouse warehouse = warehouseMapper.selectById(i.getWarehouseId());
            if(Objects.isNull(warehouse)){
                throw new BusinessException(ResponseStatus.OBJECT_EMP.getCode(), "未查询到仓库数据【" + i.getId() + "】");
            }
            for (Appliances j:outDetailList) {
                if(Objects.equals(j.getWarehouseId(),i.getWarehouseId())){
                    //更新库存
                    List<WStock> wStockList = wStockMapper.selectList(new QueryWrapper<WStock>()
                            .eq("ROOT_DEPART_ID", wOutbound.getRootDepartId())
                            .eq("MATERIAL_ID", j.getMaterialId())
                            .eq("WAREHOUSE_ID", i.getWarehouseId())
                            .eq(j.getProcedureId()!= null,"PROCEDURE_ID", j.getProcedureId())
                            .eq(j.getQualityType()!= null,"QUALITY_TYPE", j.getQualityType())
                            .eq(!StringUtils.isBlank(j.getBatch()),"BATCH", j.getBatch())
                            .isNull(j.getProcedureId()== null,"PROCEDURE_ID" )
                            .isNull(j.getQualityType()== null,"QUALITY_TYPE" )
                            .isNull(StringUtils.isBlank(j.getBatch()),"BATCH" )
                            .eq("DELETED",Constants.ZERO)
                            .eq(warehouse.getUseLocation()==Constants.ONE,"LOCATION_ID", j.getLocationId())
                    );
                    if (wStockList.size()<=Constants.ZERO) {
                        throw new BusinessException(ResponseStatus.OBJECT_EMP.getCode(), "未查询到仓库/货位库存信息【" + i.getWarehouseId() + "】");
                    }else if(wStockList.size()>1){
                        throw new BusinessException(ResponseStatus.OBJECT_EMP.getCode(), "库存数据异常,存在多条库存信息,请检查库存数据【" + i.getWarehouseId() + "】");
                    }
                    WStock wStock = wStockList.get(0);
                    if (wStock.getNum().compareTo(j.getNum()) < Constants.ZERO) {
                        throw new BusinessException(ResponseStatus.OBJECT_EMP.getCode(), "当前货位库存数量不足;剩余数量【" + wStock.getNum() + "】;出库数量【" + j.getNum() + "】");
                    }
                    WOutboundDetail wOutboundDetail = new WOutboundDetail();
                    wOutboundDetail.setCreateUser(userInfo.getId());
                    wOutboundDetail.setCreateTime(new Date());
                    wOutboundDetail.setRootDepartId(userInfo.getRootDepartment().getId());
                    wOutboundDetail.setOutboundId(wOutbound.getId());
                    wOutboundDetail.setMaterialId(j.getMaterialId());
                    wOutboundDetail.setUnitId(j.getUnitId());
                    wOutboundDetail.setNum(j.getNum());
                    wOutboundDetail.setBatch(j.getBatch());
                    wOutboundDetail.setDoneDate(new Date());
                    wOutboundDetail.setWarehouseId(j.getWarehouseId());
                    wOutboundDetail.setLocationId(j.getLocationId());
                    wOutboundDetail.setStatus(Constants.ONE);
                    wOutboundDetail.setDoneNum(j.getNum());
                    wOutboundDetail.setQualityType(j.getQualityType());
                    wOutboundDetail.setProcedureId(j.getProcedureId());
                    wOutboundDetailExtMapper.insert(wOutboundDetail);
 
                    //记录库存变动记录
                    wStockRecordExtService.saveRecord(Constants.ZERO,wOutboundDetail.getId(),userInfo);
 
                    for (Appliances k:appliancesList ) {
                        if(Objects.equals(j.getLocationId(),k.getLocationId())
                                &&Objects.equals(j.getMaterialId(), k.getMaterialId())
                                &&Objects.equals( j.getBatch(), k.getBatch())
                                &&Objects.equals(j.getQualityType(),k.getQualityType())
                                &&Objects.equals(j.getProcedureId(),k.getProcedureId())
                        ){
                            k.setWarehouseId(null);
                            k.setLocationId(null);
                            k.setCurObjId(wOutbound.getId());
                            k.setCurObjType(0);
                            appliancesExtMapper.updateById(k);
                            WOutboundRecord wOutboundRecord = wOutboundDetail.toRecord(k,userInfo);
                            wOutboundRecordExtMapper.insert(wOutboundRecord);
                        }
                    }
                    wStock.setNum(wStock.getNum().subtract(j.getNum()));
                    wStockMapper.updateById(wStock);
                }
            }
 
            WHistory wHistory = wOutbound.toWHistory(userInfo.getId());
            wHistoryMapper.insert(wHistory);
        }
 
        //发送通知
        Notices notices = new Notices();
        CompanyUser cUser = companyUserMapper.selectOne(new QueryWrapper<CompanyUser>()
                .eq("USER_ID",warehouseForIn.getManagerId())
                .eq("DELETED",0)
                .eq("ROOT_DEPART_ID",wTransfer.getRootDepartId())
        );
        Constants.Notices_Type_Transfer  noticesTypeTransfer=  Constants.Notices_Type_Transfer.title4;
        notices.setCompanyUserId(cUser.getId());
        notices.setType(noticesTypeTransfer.getNoticeInType());
        notices.setContent("【"+wTransfer.getCode()+"】" + noticesTypeTransfer.getContent().replace("{optType}","入库"));
        notices.setObjId(wTransfer.getId());
        notices.setTitle(noticesTypeTransfer.getTitle());
        notices.setUrl(Constants.getNoticeUrl(userInfo.getCompany(),Constants.DINGDING_NOTICE_URL.in).replace("{id}",wTransfer.getId().toString()));
//        notices.setUrl(systemDictDataBiz.queryByCode(Constants.ROUTE_CONFIG,Constants.IN_TYPE_URL).getCode().replace("{id}",wTransfer.getId().toString()));
        noticesExtService.sendNotice(notices);
 
        return ApiResponse.success(wTransfer.getId());
    }
 
 
 
    @Override
    public ApiResponse<FinishedInNewBean> finishedDetailNew(String deviceIds,String inIds,LoginUserInfo userInfo){
        //根据设备主键获取设备信息
        List<Device> deviceList = deviceMapper.selectList(
                new QueryWrapper<Device>()
                        .eq("deleted",Constants.ZERO)
                        .apply(" find_in_set(id,'"+deviceIds+"') ")
        );
        if(deviceList.size()==Constants.ZERO){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,未查询到设备信息!");
        }
        CompanyUser companyUser  = companyUserExtMapper.selectOne(new QueryWrapper<CompanyUser>()
                .eq("USER_ID",userInfo.getId())
                .eq("ROOT_DEPART_ID",userInfo.getRootDepartment().getId())
                .eq("deleted",0)
        );
        if(Objects.isNull(companyUser)){
            throw new BusinessException(ResponseStatus.OBJECT_EMP.getCode(), "未查询到操作员工信息");
        }
        Department department = departmentExtMapper.selectById(companyUser.getDepartmentId());
        if(Objects.isNull(department)){
            throw new BusinessException(ResponseStatus.OBJECT_EMP.getCode(), "未查询到操作员工班组信息");
        }
 
        FinishedInNewBean finishedInBean = new FinishedInNewBean();
        finishedInBean.setWorker(companyUser.getName());
        finishedInBean.setGroupName(department.getName());
        finishedInBean.setDeviceList(deviceList);
 
        List<Integer> produceLocationIds = deviceList.stream().map(x -> x.getProduceWarehouseLocationId()).collect(Collectors.toList());
        List<Integer> allIds = deviceList.stream().map(x -> x.getFinishWarehouseLocationId()).collect(Collectors.toList());
        allIds.addAll(produceLocationIds);
        finishedInBean.setQualifiedBeanList(
                wTransferDetailExtMapper.wTransferConfirmDetailNew(allIds,Integer.toString(Constants.QUALITIY_TYPE.normal),inIds,produceLocationIds)
        );
        finishedInBean.setRejectsBeanList(
                wTransferDetailExtMapper.wTransferConfirmDetailNew(allIds,Integer.toString(Constants.QUALITIY_TYPE.unqulified),inIds,produceLocationIds)
        );
        finishedInBean.setScrapBeanList(
                wTransferDetailExtMapper.wTransferConfirmDetailNew(allIds,Integer.toString(Constants.QUALITIY_TYPE.scrap),inIds,produceLocationIds)
        );
 
        finishedInBean.setProduceLocationIds(produceLocationIds);
        if(StringUtils.isNotBlank(inIds)){
            List<FinishedInBillBean> finishedInBillBeanList = wOutboundExtMapper.finishedInBill(null,inIds);
            for (FinishedInBillBean finishedInBillBean:finishedInBillBeanList) {
                finishedInBillBean.setReserveMaterialBeanList(appliancesExtMapper.reserveMaterialBeanList(finishedInBillBean.getId(),produceLocationIds));
            }
            finishedInBean.setFinishedInBillBeanList(finishedInBillBeanList);
        }
 
        return ApiResponse.success(finishedInBean);
    }
 
 
    //查询物料是否存在bom 存在bom为提供的数据绑定返回工艺路线的最后一道工序
    public void dealProcedure(WTransferDetailBean tBean){
        Bom bom = bomMapper.selectOne(new QueryWrapper<Bom>()
                .eq("MATERIAL_ID",tBean.getMaterialId())
                .eq("DELETED",Constants.ZERO)
                .eq("TYPE",0)
        );
        if(Objects.isNull(bom)){
            tBean.setProcedureId(null);
        }else{
            RouteProcedure routeProcedure = routeProcedureExtMapper.selectOne(new QueryWrapper<RouteProcedure>()
                    .eq("DELETED",Constants.ZERO)
                    .eq("ROUTE_ID",bom.getRouteId())
                    .orderByDesc(" SORTNUM ").last(" limit 1  ")
            );
            tBean.setProcedureId(routeProcedure.getProcedureId());
        }
    }
 
 
 
 
}