jiangping
2023-08-18 6ccb04d9bfb5cc638f221453d2b5b47039de9ddd
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
package doumeemes.service.ext.impl;
 
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.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.excel.EasyExcelUtil;
import doumeemes.core.utils.redis.RedisUtil;
import doumeemes.dao.business.PlansMapper;
import doumeemes.dao.business.UnqualifiedRecordMapper;
import doumeemes.dao.business.WorkorderMapper;
import doumeemes.dao.business.dto.*;
import doumeemes.dao.business.model.*;
import doumeemes.dao.ext.*;
import doumeemes.dao.ext.dto.*;
import doumeemes.dao.ext.vo.*;
import doumeemes.service.ext.*;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
 
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
 
/**
 * 生产计划Service实现
 * @author 江蹄蹄
 * @date 2022/04/20 11:01
 */
@Service
public class PlansExtServiceImpl implements PlansExtService {
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private BarcodeParamExtService barcodeParamExtService;
    @Autowired
    private PlansExtMapper plansExtMapper;
    @Autowired
    private WorkorderExtService workorderExtService;
    @Autowired
    private WorkorderExtMapper workorderExtMapper;
    @Autowired
    private WorkorderUserExtMapper workorderUserExtMapper;
    @Autowired
    private WorkorderHistoryExtMapper workorderHistoryExtMapper;
    @Autowired
    private WorkorderRecordExtMapper workorderRecordExtMapper;
    @Autowired
    private WorkorderMapper workorderMapper;
    @Autowired
    private RouteProcedureExtMapper routeProcedureExtMapper;
    @Autowired
    private PlansMapper plansMapper;
    @Autowired
    private UserDeviceExtMapper userDeviceExtMapper;
    @Autowired
    private PlanHistoryExtMapper planHistoryExtMapper;
    @Autowired
    private PlanImportExtMapper planImportExtMapper;
    @Autowired
    private ProceduresExtMapper proceduresExtMapper;
    @Autowired
    private DepartmentExtService departmentExtService;
    @Autowired
    private DeviceExtMapper deviceExtMapper ;
    @Autowired
    private BomExtMapper bomExtMapper;
    @Autowired
    private MaterialDistributeExtMapper materialDistributeExtMapper;
    @Autowired
    private WStockExtService  wStockExtService;
    @Autowired
    private WorkorderRecordStandardService workorderRecordStandardService;
    @Autowired
    private UnqualifiedRecordMapper unqualifiedRecordMapper;
 
    @Override
    public  PlansExtListVO findById(Integer id){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        if(id==null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,请求参数不正确!");
        }
        QueryPlansExtDTO pageWrap = new QueryPlansExtDTO();
        pageWrap.setDeleted(Constants.ZERO);
        pageWrap.setId(id);
        //只能查看当前根组织的数据
        pageWrap.setRootDepartId(user.getRootDepartment().getId());
//        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.setUserId(user.getId());
            }else{
                //否则走数据权限
                pageWrap.setDepartIds(dataPermission);
            }
        }
        if(user.getProcedureIds()!=null){
            pageWrap.setProcedureIds(user.getProcedureIds());
        }else{
            pageWrap.setUserId(user.getId());
        }
        List<PlansExtListVO> result = plansExtMapper.selectList(pageWrap);
        if(result==null||result.size()==0){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,计划信息不存在");
        }
        PlansExtListVO plan = result.get(0);
        initPlanStatisticInfo(plan);
//        plan.setDistributNum(Constants.formatIntegerNum(plan.getDistributNum()));
//        QueryWorkorderExtDTO param = new QueryWorkorderExtDTO();
//        param.setPlanId(plan.getId());
//        param.setDeleted(Constants.ZERO);
//        //统计已分配数量
//        plan.setDistributNum(workorderExtMapper.sumOrderNum(param));
//        //统计已完工数量
//        param.setStatus(Constants.WORKORDER_STATUS.done);
//        plan.setDoneNum(workorderExtMapper.sumOrderNum(param));
        QueryBomExtDTO bb = new QueryBomExtDTO();
        bb.setDepartId(plan.getDepartId());
        bb.setDeleted(Constants.ZERO);
        bb.setRootDepartId(user.getRootDepartment().getId());
        bb.setMaterialId(plan.getMaterialId());
        bb.setProcedureId(plan.getProcedureId());
        BomExtListVO versionBom = bomExtMapper.selectByModel( bb);
        if(versionBom == null || StringUtils.isBlank(versionBom.getVersion()) || versionBom.getBomVersionId() == null){
            plan.setHasBom(Constants.ZERO);
        }else {
            plan.setBomType(Constants.formatIntegerNum(versionBom.getType()));
            plan.setHasBom(Constants.ONE);
        }
        return plan;
    }
 
    @Override
    public PlansExtListH5VO findByIdH5(Integer id){
        PlansExtListVO t = findById(id);
        initPlanStatisticInfo(t);
        PlansExtListH5VO plan = new PlansExtListH5VO();
        BeanUtils.copyProperties(t,plan);
//        plan.setDoneNum();
        plan.setWorkorderList(workorderExtService.findByPlanId(plan,true));
        return plan;
    }
    @Override
    public PageData<PlansExtListVO> findPage(PageWrap<QueryPlansExtDTO> pageWrap) {
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        pageWrap.getModel().setDeleted(Constants.ZERO);
        //只能查看当前根组织的数据
        pageWrap.getModel().setRootDepartId(user.getRootDepartment().getId());
//        if(!Constants.equalsInteger(user.getCurComDepartment().getId(),user.getRootDepartment().getId())){
            //如果当前选择的公司级组织非根组织信息,只能查看当前选择公司级组织数据
            pageWrap.getModel().setDepartId(user.getCurComDepartment().getId());
//        }
        //数据权限
        List<Integer> dataPermission = user.getDepartPermissionList();
        if(dataPermission!=null){
            //只能看自己的
            pageWrap.getModel().setCreateUser(user.getId());
            //否则走数据权限
            pageWrap.getModel().setDepartIds(dataPermission);
         /*   if(dataPermission.size() == 0){
                //只能看自己的
                pageWrap.getModel().setCreateUser(user.getId());
            }else{
 
            }*/
        }
        if(user.getProcedureIds()!=null){
            pageWrap.getModel().setProcedureIds(user.getProcedureIds());
        }else{
           // pageWrap.getModel().setUserId(user.getId());
            pageWrap.getModel().setCreateUser(user.getId());
        }
        PageHelper.startPage(pageWrap.getPage(), pageWrap.getCapacity());
        List<PlansExtListVO> result = plansExtMapper.selectList(pageWrap.getModel());
        if(result!=null){
            for(PlansExtListVO p : result){
                initPlanStatisticInfo(p);
//                PlansExtListH5VO tp = new PlansExtListH5VO();
//                tp.setId(p.getId());
//                //统计功能已分配数量和完工数量
//                tp.setNum(p.getNum());
//                workorderExtService.findByPlanId(tp,false);
//                p.setDistributNum(tp.getDistributNum());
//                p.setDoneNum(tp.getDoneNum());
                p.setIsStock(wStockExtService.isStockForPlan(p));
                p.setHasExpire(false);
                p.setStatus(Constants.formatIntegerNum(p.getStatus()));
                if ( !p.getStatus().equals(Constants.PLAN_STATUS.done) &&
                        !p.getStatus().equals(Constants.PLAN_STATUS.close)){
                    if (Objects.nonNull(p.getPlanDate())){
                        p.setHasExpire(DateUtil.toDateLocalDateTime(p.getWorkPlanPlanDate()).toLocalDate().isBefore(LocalDate.now()));
                    }
                }
            }
        }
        return PageData.from(new PageInfo<>(result));
    }
 
 
    @Override
    public List<PlansExtListVO> getListByWorkPlan(Integer workPlanId){
        QueryPlansExtDTO queryPlansExtDTO = new QueryPlansExtDTO();
        queryPlansExtDTO.setWorkPlanId(workPlanId);
        List<PlansExtListVO> result = plansExtMapper.selectList(queryPlansExtDTO);
        if(result!=null){
            for(PlansExtListVO p : result){
                initPlanStatisticInfo(p);
                p.setIsStock(wStockExtService.isStockForPlan(p));
            }
        }
        return result;
    }
 
 
    private void initPlanStatisticInfo(PlansExtListVO p) {
        p.setDistributNum(0);
        p.setDistributNoDoneNum(0);
        p.setDoneNum(0);
        p.setQulifiedNum(0);
        p.setUnqulifiedNum(0);
        try {
            JSONObject json = JSONObject.parseObject(p.getStatisticInfo());
            p.setDistributNum(Constants.formatIntegerNum(json.getInteger(Constants.STATISTIC.distribute)));
            p.setDistributNoDoneNum(Constants.formatIntegerNum(json.getInteger(Constants.STATISTIC.distributeNoDone)));
            p.setDoneNum(Constants.formatIntegerNum(json.getInteger(Constants.STATISTIC.done)));
            p.setQulifiedNum(Constants.formatIntegerNum(json.getInteger(Constants.STATISTIC.qulified)));
            p.setUnqulifiedNum(Constants.formatIntegerNum(json.getInteger(Constants.STATISTIC.unqulified)));
        }catch (Exception e){
 
        }
    }
 
    @Override
    public PlansExtListCountVO pageCount(QueryPlansExtDTO param){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        param.setDeleted(Constants.ZERO);
        //只能查看当前根组织的数据
        param.setRootDepartId(user.getRootDepartment().getId());
//        if(!Constants.equalsInteger(user.getCurComDepartment().getId(),user.getRootDepartment().getId())){
            //如果当前选择的公司级组织非根组织信息,只能查看当前选择公司级组织数据
            param.setDepartId(user.getCurComDepartment().getId());
//        }
        //数据权限
        List<Integer> dataPermission = user.getDepartPermissionList();
        if(dataPermission!=null){
            if(dataPermission.size() == 0){
                //只能看自己的
                param.setCreateUser(user.getId());
            }else{
                //否则走数据权限
                param.setDepartIds(dataPermission);
            }
        }
        if(user.getProcedureIds()!=null){
            param.setProcedureIds(user.getProcedureIds());
        }else{
            param.setCreateUser(user.getId());
        }
        PlansExtListCountVO result = new PlansExtListCountVO();
        //全部数量
        result.setAllNum(plansExtMapper.selectCount(param));
        param.setStatusList(new ArrayList<>());
        param.getStatusList().add(Constants.PLAN_STATUS.create);
        //未完成数量
        result.setStartNum(plansExtMapper.selectCount(param));
        param.setStatusList(new ArrayList<>());
        param.getStatusList().add(Constants.PLAN_STATUS.distribute);
        param.getStatusList().add(Constants.PLAN_STATUS.publish);
        //进行中数量
        result.setIngNum(plansExtMapper.selectCount(param));
        param.setStatusList(new ArrayList<>());
        param.getStatusList().add(Constants.PLAN_STATUS.done);
        param.getStatusList().add(Constants.PLAN_STATUS.instock);
        param.getStatusList().add(Constants.PLAN_STATUS.cancel);
        param.getStatusList().add(Constants.PLAN_STATUS.close);
        //进行中数量
        result.setEndNum(plansExtMapper.selectCount(param));
        return result;
    }
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public  Integer create(Plans p)  {
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
 
        //检查数据有效性
        p.setCreateTime(DateUtil.getCurrentDate());
        p.setCreateUser(user.getId());
        p.setDeleted(Constants.ZERO);
        p.setDepartId(user.getCurComDepartment().getId());
        p.setRootDepartId(user.getRootDepartment().getId());
        p.setUserId(user.getId());
        p.setOrigin(Constants.PLAS_ORIGIN.user);
        p.setStatus(Constants.PLAN_STATUS.create);
        p.setType(Constants.PLAN_TYPE.normal);
        checkData(p,user);
        //插入数据
        plansExtMapper.insert(p);
        //历史数据
        planHistoryExtMapper.insert(initHistoryByModel(p,user.getId(),Constants.PLANHISTORY_TYPE.create));
        return p.getId();
    }
 
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public  Integer insertForWorkPlan(Plans p)  {
        //插入数据
        plansExtMapper.insert(p);
        return p.getId();
    }
 
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public  Integer createDirect(Plans p)  {
        //插入数据
        plansExtMapper.insert(p);
        //历史数据
        planHistoryExtMapper.insert(initHistoryByModel(p,p.getCreateUser(),Constants.PLANHISTORY_TYPE.create));
        return p.getId();
    }
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void autoClose(){
        //插入数据
        QueryPlansExtDTO param = new QueryPlansExtDTO();
        param.setDeleted(Constants.ZERO);
        //已分配
        param.setStatus(Constants.PLAN_STATUS.distribute);
        //查询全部已分配未关闭数据
        List<PlansExtListVO> planList = plansExtMapper.selectList(param);
        if(planList!=null && planList.size()>0){
            for(PlansExtListVO model : planList){
                //遍历全部计划,针对已分配状态的计划,当前计划的(合格数量+不良数量,按照现在统计的结果)+同物料同批次号前置工序的报废数量(工单状态为已报工) >=计划当前计划数量,
                // 系统自动关闭计划,将计划状态置为【已关闭】状态;
                initPlanStatisticInfo(model);
                //合格数量
                int hgNum = Constants.formatIntegerNum(model.getQulifiedNum());
                //不良数量
                int blNum = Constants.formatIntegerNum(model.getUnqulifiedNum());
                //前置工序计划的报废数量
                int bfNum = getScrapProNum(model);
                if(hgNum+blNum+bfNum >= Constants.formatIntegerNum(model.getNum())){
                    Plans p = new Plans();
                    p.setId(model.getId());
                    //检查数据有效性
                    p.setUpdateTime(DateUtil.getCurrentDate());
//                    p.setUpdateUser(user.getId());
                    p.setStatus(Constants.PLAN_STATUS.close);
                    p.setRootDepartId(model.getRootDepartId());
                    p.setDepartId(model.getDepartId());
                    //更新计划数据
                    plansExtMapper.updateById(p);
                    //历史数据,关闭
                    planHistoryExtMapper.insert(initHistoryByModel(p,null,Constants.PLANHISTORY_TYPE.close,"系统自动关闭"));
                }
            }
        }
    }
 
    private int getScrapProNum(PlansExtListVO model) {
 
      /*  QueryBomExtDTO bb = new QueryBomExtDTO();
        bb.setDepartId(model.getDepartId());
        bb.setDeleted(Constants.ZERO);
        bb.setRootDepartId(model.getRootDepartId());
        bb.setMaterialId(model.getMaterialId());
        bb.setProcedureId(model.getProcedureId());
        BomExtListVO versionBom = bomExtMapper.selectByModel( bb);*/
        Bom bb = new Bom();
        bb.setDepartId(model.getDepartId());
        bb.setDeleted(Constants.ZERO);
        bb.setRootDepartId(model.getRootDepartId());
        bb.setMaterialId(model.getMaterialId());
        Bom versionBom = bomExtMapper.selectOne(new QueryWrapper<>(bb).exists("select route.id from route where bom.route_id=route.id and route.depart_id="+model.getFactoryId()).last("limit 1") );
        if(versionBom == null || StringUtils.isBlank(versionBom.getVersion())  || versionBom.getRouteId() == null){
           //如果没有bom或者没有绑定工艺路线
            return 0;
        }
        //如果有bom,根据bom的工艺路线查询全部前置工序数据
        RouteProcedure rp = new RouteProcedure();
        rp.setDeleted(Constants.ZERO);
        rp.setDepartId(model.getFactoryId());
        rp.setRouteId(versionBom.getRouteId());
        List<RouteProcedure> rpList = routeProcedureExtMapper.selectList(new QueryWrapper<>(rp).orderByAsc("SORTNUM"));
        List<Integer> producreIds = null;
        boolean isValid = false;
        if(rpList!=null && rpList.size()>0){
            for(int i=0;i<rpList.size();i++){
                RouteProcedure r = rpList.get(i);
                if(Constants.equalsInteger(r.getProcedureId(),model.getProcedureId())){
                    //如果工序相同,找下一工序
                    isValid =true;
                    break;
                }
                if(producreIds == null){
                    producreIds = new ArrayList<>();
                }
                producreIds.add(r.getProcedureId());
            }
        }
        if(!isValid){
            //如果计划工序未配置在工艺路线中,不做处理
            producreIds = null;
        }
 
        if(producreIds!= null && producreIds.size()>0){
            WorkorderRecord wr = new WorkorderRecord();
            wr.setDeleted(Constants.ZERO);
            wr.setRootDepartId(model.getRootDepartId());
            wr.setType(Constants.WORKORDER_RECORD_TYPE.produce);
            wr.setMaterialDonetype(Constants.QUALITIY_TYPE.scrap);
            List<WorkorderRecord> rList = workorderRecordExtMapper.selectList(new QueryWrapper<>(wr)
                    .exists("select workorder.id   from workorder where workorder_record.WORKORDER_ID=workorder.id and workorder.status in(4,5)")
                    .in("PROCEDURE_ID",producreIds)
            );
            if(rList !=null){
                BigDecimal num = new BigDecimal(0);
                for(WorkorderRecord r : rList){
                    num =  num.add(Constants.formatBigdecimal(r.getNum()));
                }
                return  num.intValue();
            }
        }
        return 0;
    }
 
    @Override
    public List<Plans> getPlansList(QueryWrapper queryWrapper){
        return plansMapper.selectList(queryWrapper);
    }
 
 
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void updateById(Plans p){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        if(p.getId()== null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,记录不存在!");
        }
        Plans mp = new Plans();
        mp.setDeleted(Constants.ZERO);
        mp.setId(p.getId());
        mp.setRootDepartId(user.getRootDepartment().getId());
        mp = plansExtMapper.selectOne(new QueryWrapper<>(mp));
        if(mp== null){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,该记录不存在!");
        }
        //检查数据有效性
        p.setUpdateTime(DateUtil.getCurrentDate());
        p.setUpdateUser(user.getId());
        p.setDeleted(Constants.ZERO);
        p.setStatus(null);//状态不能改
        p.setDepartId(user.getComDepartment().getId());
        p.setRootDepartId(user.getRootDepartment().getId());
        p.setUserId(user.getId());
        checkData(p,user);
        //更新数据
        plansExtMapper.updateById(p);
    }
 
 
 
 
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void updateForPlan(Plans p){
        plansExtMapper.updateById(p);
    }
 
    /**
     * 将计划行、计划分配和相关工单状态全部置为“已关闭”,终止该计划行的一切生产操作,但不影响已生产的入库操作;
     * @param p
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void closeById(Plans p){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        if(p.getId()== null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,记录不存在!");
        }
        Plans mp = new Plans();
        mp.setDeleted(Constants.ZERO);
        mp.setId(p.getId());
        mp.setRootDepartId(user.getRootDepartment().getId());
        mp = plansExtMapper.selectOne(new QueryWrapper<>(mp));
        if(mp== null){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,该记录不存在!");
        }
        if(!Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.distribute)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该计划状态已流转,当前不能关闭!");
        }
       /* if(Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.close)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该计划已关闭!");
        }*/
        Plans model = new Plans();
        model.setId(p.getId());
        //检查数据有效性
        model.setUpdateTime(DateUtil.getCurrentDate());
        model.setUpdateUser(user.getId());
        model.setStatus(Constants.PLAN_STATUS.close);
        model.setRootDepartId(mp.getRootDepartId());
        model.setDepartId(mp.getDepartId());
        //更新计划数据
        plansExtMapper.updateById(model);
        //历史数据,关闭
        planHistoryExtMapper.insert(initHistoryByModel(model,user.getId(),Constants.PLANHISTORY_TYPE.close));
        /*
        QueryWorkorderExtDTO qw = new QueryWorkorderExtDTO();
        qw.setPlanId(p.getId());
        qw.setDeleted(Constants.ZERO);
        List<Integer> ids = new ArrayList<>();
        List<WorkorderHistory> whList = new ArrayList<>();
        List<WorkorderExtListVO> orderList = workorderExtMapper.selectList(qw);
        if(orderList != null){
            for(WorkorderExtListVO w : orderList){
                if(Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.instock)){
                    throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,该计划不满足关闭条件!");
                }
                if(!Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.instock)
                        &&!Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.done)
                        &&!Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.close)
                        &&!Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.check) ){
                    whList.add(WorkorderExtServiceImpl.initHistoryByModel(w,user.getId(),Constants.WORKORDER_HISTORY_STATUS.close));
                    //操作集合
                    ids.add(w.getId());
                }
            }
        }
        //关闭全部相关工单
        if(ids.size()>0){
            Workorder order = new Workorder();
            order.setPlanId(p.getId());
            order.setUpdateTime(model.getUpdateTime());
            order.setUpdateUser(model.getUpdateUser());
            order.setIds(ids);
            order.setStatus(Constants.WORKORDER_STATUS.close);
            //关闭工单
            workorderExtMapper.updateByPlan(order);
            workorderHistoryExtMapper.insertBatch(whList);
        }*/
    }
    /**
     * 分配工单
     * @param param
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void distributeById(Workorder param  ){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        distributeDone(user, param,param.getPlanNum());
    }
 
    private Workorder distributeDone(LoginUserInfo user,  Workorder param,int thisPlanNum) {
        if(param.getPlanId()== null
                ||param.getPlanDate() == null
                || param.getProGroupId()==null
                || param.getProUserList()==null
                || param.getProUserList().size()==0
                || Constants.formatIntegerNum(param.getPlanNum())<=0){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,请按要求填写和选择提交数据!");
        }
 
        QueryPlansExtDTO mpp = new QueryPlansExtDTO();
        mpp.setDeleted(Constants.ZERO);
        mpp.setId(param.getPlanId());
        mpp.setRootDepartId(user.getRootDepartment().getId());
        PlansExtListVO mp = plansExtMapper.selectByModel(mpp);
        initPlanStatisticInfo(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.formatIntegerNum(mp.getWorkorderDistributNum())+thisPlanNum > Constants.formatIntegerNum(mp.getNum())){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,累计分配数量大于计划数量!");
        }
        if(!Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.publish)&&!Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.distribute)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该计划非待分配状态!");
        }
        Plans model = new Plans();
        model.setId(mp.getId());
        //检查数据有效性
        model.setUpdateTime(DateUtil.getCurrentDate());
        model.setUpdateUser(user.getId());
        model.setStatus(Constants.PLAN_STATUS.distribute);
        model.setRootDepartId(mp.getRootDepartId());
        model.setDepartId(mp.getDepartId());
        //更新计划数据
        plansExtMapper.updateById(model);
        //历史数据,关闭
        planHistoryExtMapper.insert(initHistoryByModel(model,user.getId(),Constants.PLANHISTORY_TYPE.distribute));
 
        List<WorkorderHistory> whList = new ArrayList<>();
        Workorder order = new Workorder();
        order.setCreateTime(DateUtil.getCurrentDate());
        order.setCreateUser(user.getId());
        order.setDeleted(Constants.ZERO);
        order.setStatus(Constants.WORKORDER_STATUS.create);
        order.setPlanId(mp.getId());
        order.setRootDepartId(mp.getRootDepartId());
        order.setDepartId(mp.getDepartId());
        order.setPaused(Constants.ZERO);
//        order.set
        //正常工单
        order.setType(mp.getType());
        order.setMaterialId(mp.getMaterialId());
        order.setProcedureId(mp.getProcedureId());
        order.setCode(param.getCode());
        order.setPlanDate(param.getPlanDate());
        order.setPlanNum(param.getPlanNum());
        order.setUnitId(mp.getUnitId());
        order.setBatch(mp.getBatch());
        order.setUrgent(mp.getUrgent());
        order.setFactoryId(mp.getFactoryId());
        order.setBackorderId(mp.getBackorderId());
        order.setUnqualifiedNum(param.getUnqualifiedNum());
        order.setQualifiedNum(param.getQualifiedNum());
        order.setOriginId(systemDictDataBiz.queryByCode(Constants.WORKORDER_SOURCE,Constants.WORKORDER_SOURCE_PLAN).getId());
        //工单编码
        order.setCode(workorderExtService.getNextCode(user.getCompany().getId()));
        order.setUserDeivceId(param.getUserDeivceId());
        order.setQrcodeId(barcodeParamExtService.getByType(user.getCompany().getId(),mp.getDepartId(),Constants.BARCODEPARAM_TYPE.workorder));
        order.setProUserList(param.getProUserList());
        order.setProGroupId(param.getProGroupId());
        workorderExtMapper.insert(order);
        //查询生产班组和人员是否合法
        checkUserAndGroupNew(order,mp,user);
        //工单历史数据
        whList.add(WorkorderExtServiceImpl.initHistoryByModel(order,user.getId(),Constants.WORKORDER_HISTORY_STATUS.create));
        workorderHistoryExtMapper.insertBatch(whList);
        //插入生产人员分配关联表
        for( WorkorderUser wu :order.getWorkorderUserList()){
            wu.setWorkorderId(order.getId());
            //生产人员记录
            workorderUserExtMapper.insert(wu);
        }
        return order;
    }
 
 
    private void checkUserAndGroupNew(Workorder param, PlansExtListVO  model,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(), "对不起,生产设备信息不正确,请刷新页面重试!");
        }
 
        List<WorkorderUser> userList = new ArrayList<>();
        for(Integer userId : param.getProUserList()){
            WorkorderUser u = new WorkorderUser();
            u.setProUserId(userId);
            u.setPlanId(model.getId());
            u.setCreateUser(user.getId());
            u.setDeleted(Constants.ZERO);
            u.setCreateTime(DateUtil.getCurrentDate());
            u.setRootDepartId(model.getRootDepartId());
            u.setDepartId(model.getDepartId());
            userList.add(u);
        }
        param.setWorkorderUserList(userList);
 
    }
 
    private void checkUserAndGroup(Workorder param, PlansExtListVO  model,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(model.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(model.getId());
            u.setCreateUser(user.getId());
            u.setDeleted(Constants.ZERO);
            u.setCreateTime(DateUtil.getCurrentDate());
            u.setRootDepartId(model.getRootDepartId());
            u.setDepartId(model.getDepartId());
            userList.add(u);
        }
        param.setWorkorderUserList(userList);
 
    }
    private void checkUserAndGroupOld(Workorder param, PlansExtListVO  model,LoginUserInfo user) throws BusinessException{
        QueryUserDeviceExtDTO ud = new QueryUserDeviceExtDTO();
        ud.setDeleted(Constants.ZERO);
        ud.setId(param.getUserDeivceId());
        //查询用户设备关联关系
        UserDeviceExtListVO uModel = userDeviceExtMapper.selectByModel( ud );
        if(uModel == null || uModel.getUmodel() == null){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,生产人员及设备信息不正确,请刷新页面重试!");
        }
        //查询人员部门信息
        DepartmentExtListVO depart = departmentExtService.getModelById(user.getCompany().getId(),uModel.getUmodel().getDepartmentId());
        if(depart == null){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,生产人员班组信息不存在,请刷新页面重试!");
        }
        /* if(!Constants.equalsInteger(depart.getType(),Constants.DEPART_TYPE.group)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,选择班组错误,请刷新页面重试!");
        }*/
        //查询班组的公司级部门编码和计划公司级编码是否一致,不一致则报错
        Integer comDepartId = departmentExtService.getComDepartId(depart);
        if(!Constants.equalsInteger(comDepartId,model.getDepartId())){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,班组非计划所属公司组织,请刷新页面重试!");
        }
        //生产班组(设备)
        param.setProGroupId(uModel.getDeviceId());
        //生产人员
        param.setProUserId(uModel.getUmodel().getUserId());
    }
 
    /**
     * 取消计划
     * @param p
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void cancelById(Plans p){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        if(p.getId()== null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,记录不存在!");
        }
 
        Plans mp = new Plans();
        mp.setDeleted(Constants.ZERO);
        mp.setId(p.getId());
        mp.setRootDepartId(user.getRootDepartment().getId());
        mp = plansExtMapper.selectOne(new QueryWrapper<>(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.PLAN_STATUS.cancel)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该计划已取消!");
        }
 
 
        if(!(Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.create)
            ||Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.publish)
            ||Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.distribute))){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该计划状态已流转,不能取消!");
        }*/
        //已分配状态支持取消操作
        if(!Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.distribute)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该计划状态已流转,不能进行该操作!");
        }
        /*QueryWorkorderRecordExtDTO qr = new QueryWorkorderRecordExtDTO();
        qr.setPlanId(p.getId());
        qr.setDeleted(Constants.ZERO);
        qr.setType(Constants.WORKORDER_RECORD_TYPE.materail);
        if(workorderRecordExtMapper.selectOne(new QueryWrapper(qr)) !=null){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该计划已有工单进行投料,不能取消!");
        }*/
        Plans model = new Plans();
        model.setId(p.getId());
        //检查数据有效性
        model.setUpdateTime(DateUtil.getCurrentDate());
        model.setUpdateUser(user.getId());
        model.setStatus(Constants.PLAN_STATUS.cancel);
        model.setRootDepartId(mp.getRootDepartId());
        model.setDepartId(mp.getDepartId());
        //更新计划数据
        plansExtMapper.updateById(model);
        //历史数据,关闭
        planHistoryExtMapper.insert(initHistoryByModel(model,user.getId(),Constants.PLANHISTORY_TYPE.close));
 
 
        QueryWorkorderExtDTO qw = new QueryWorkorderExtDTO();
        qw.setPlanId(p.getId());
        qw.setDeleted(Constants.ZERO);
        qw.setCheckTouliao(Constants.ONE);
        List<Integer> ids = new ArrayList<>();
        List<WorkorderHistory> whList = new ArrayList<>();
        List<WorkorderExtListVO> orderList = workorderExtMapper.selectList(qw);
        if(orderList != null){
            for(WorkorderExtListVO w : orderList){
                /*if(Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.instock)){
                    throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该计划不满足关闭条件!");
                }*/
                //工单为已创建、已备料状态,且无投料记录,工单状态改为取消,已有投料记录往后状态工单状态不变
                if(( Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.create)
                       ||Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.material))
                        && w.getTouliaoId()==null ){
                    whList.add(WorkorderExtServiceImpl.initHistoryByModel(w,user.getId(),Constants.WORKORDER_HISTORY_STATUS.cancel));
                    //操作集合
                    ids.add(w.getId());
                }
            }
        }
        //取消相关工单
        if(ids.size()>0){
            Workorder order = new Workorder();
            order.setPlanId(p.getId());
            order.setUpdateTime(model.getUpdateTime());
            order.setUpdateUser(model.getUpdateUser());
            order.setIds(ids);
            order.setStatus(Constants.WORKORDER_STATUS.cancel);
            //关闭工单
            workorderExtMapper.updateByPlan(order);
            workorderHistoryExtMapper.insertBatch(whList);
        }
 
    }
 
    /**
     * 批量发布计划
     * @param idList
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void publishByIdInBatch(List<Integer> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return;
        }
        for(Integer id : idList){
            Plans p = new Plans();
            p.setId(id);
            publishById(p);
        }
    }
    /**
     * 批量删除计划
     * @param idList
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public  void deleteByIdInBatch(List<Integer> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return;
        }
        for(Integer id : idList){
            deleteById(id);
        }
    }
    /**
     * 批量撤回计划
     * @param idList
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void backByIdInBatch(List<Integer> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return;
        }
        for(Integer id : idList){
            Plans p = new Plans();
            p.setId(id);
            backById(p);
        }
    }
 
    /**
     * 撤回计划,“已发布”和“已分配”可以使用,点击后先询问用户是否撤回,确认后,删除发布和分配记录,计划状态置为“已生成”
     * @param p
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void backById(Plans p){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        if(p.getId()== null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,记录不存在!");
        }
        Plans mp = new Plans();
        mp.setDeleted(Constants.ZERO);
        mp.setId(p.getId());
        mp.setRootDepartId(user.getRootDepartment().getId());
        mp = plansExtMapper.selectOne(new QueryWrapper<>(mp));
        if(mp== null){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,计划不存在!");
        }
        if( Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.cancel) ){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该计划状态已撤回,无需重复操作!");
        }
        if(Constants.equalsInteger(mp.getPaused(),Constants.ONE)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,计划已暂停!");
        }
        Plans model = new Plans();
        model.setId(p.getId());
        //检查数据有效性
        model.setUpdateTime(DateUtil.getCurrentDate());
        model.setUpdateUser(user.getId());
        model.setStatus(Constants.PLAN_STATUS.create);
        model.setRootDepartId(mp.getRootDepartId());
        model.setDepartId(mp.getDepartId());
        //更新计划数据
        plansExtMapper.updateById(model);
        //历史数据,关闭
        planHistoryExtMapper.insert(initHistoryByModel(model,user.getId(),Constants.PLANHISTORY_TYPE.create));
 
        QueryWorkorderExtDTO qw = new QueryWorkorderExtDTO();
        qw.setPlanId(p.getId());
        qw.setDeleted(Constants.ZERO);
        List<Integer> ids = new ArrayList<>();
        List<WorkorderHistory> whList = new ArrayList<>();
        List<WorkorderExtListVO> orderList = workorderExtMapper.selectList(qw);
        if(orderList != null){
            for(WorkorderExtListVO w : orderList){
                if(!(Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.create)||
                        Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.cancel))){
                    throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,该计划不满足撤回条件!");
                }
                whList.add(WorkorderExtServiceImpl.initHistoryByModel(w,user.getId(),Constants.WORKORDER_HISTORY_STATUS.cancel));
                //操作集合
                ids.add(w.getId());
            }
        }
        //取消全部相关工单
        if(ids.size()>0){
            Workorder order = new Workorder();
            order.setPlanId(p.getId());
            order.setUpdateTime(model.getUpdateTime());
            order.setUpdateUser(model.getUpdateUser());
            order.setIds(ids);
            order.setStatus(Constants.WORKORDER_STATUS.cancel);
            //取消工单
            workorderExtMapper.updateByPlan(order);
            workorderHistoryExtMapper.insertBatch(whList);
        }
 
    }
    /**
     * 暂停计划 计划已经发布并且未取消、未撤回、未关闭 暂停成功,对应工单也暂停投料,已投料的可以继续完成报工
     * @param p
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void pauseById(Plans p){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        if(p.getId()== null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,记录不存在!");
        }
        Plans mp = new Plans();
        mp.setDeleted(Constants.ZERO);
        mp.setId(p.getId());
        mp.setRootDepartId(user.getRootDepartment().getId());
        mp = plansExtMapper.selectOne(new QueryWrapper<>(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(), "对不起,该计划已暂停,无需重复操作!");
        }
        Plans model = new Plans();
        model.setId(p.getId());
        //检查数据有效性
        model.setUpdateTime(DateUtil.getCurrentDate());
        model.setUpdateUser(user.getId());
        model.setPaused(Constants.ONE);
        model.setRootDepartId(mp.getRootDepartId());
        model.setDepartId(mp.getDepartId());
        //更新计划数据
        plansExtMapper.updateById(model);
        //历史数据,关闭
        planHistoryExtMapper.insert(initHistoryByModel(model,user.getId(),Constants.PLANHISTORY_TYPE.pause));
 
        QueryWorkorderExtDTO qw = new QueryWorkorderExtDTO();
        qw.setPlanId(p.getId());
        qw.setDeleted(Constants.ZERO);
        List<Integer> ids = new ArrayList<>();
        List<WorkorderHistory> whList = new ArrayList<>();
        List<WorkorderExtListVO> orderList = workorderExtMapper.selectList(qw);
        if(orderList != null){
            for(WorkorderExtListVO w : orderList){
                if( Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.create)||
                        Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.material)||
                        Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.baogong) ){
                    //已创建、已投料和已报工的工单暂停
                    whList.add(WorkorderExtServiceImpl.initHistoryByModel(w,user.getId(),Constants.WORKORDER_HISTORY_STATUS.pause));
                    //操作集合
                    ids.add(w.getId());
                }
            }
        }
        //暂停全部相关工单
        if(ids.size()>0){
            Workorder order = new Workorder();
            order.setPlanId(p.getId());
            order.setUpdateTime(model.getUpdateTime());
            order.setUpdateUser(model.getUpdateUser());
            order.setIds(ids);
            order.setPaused(Constants.ONE);
            //取消工单
            workorderExtMapper.updateByPlan(order);
            workorderHistoryExtMapper.insertBatch(whList);
        }
 
    }
    /**
     * 恢复计划
     * @param p
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void regainById(Plans p){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        if(p.getId()== null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,记录不存在!");
        }
        Plans mp = new Plans();
        mp.setDeleted(Constants.ZERO);
        mp.setId(p.getId());
        mp.setRootDepartId(user.getRootDepartment().getId());
        mp = plansExtMapper.selectOne(new QueryWrapper<>(mp));
        if(mp== null){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,计划不存在!");
        }
        //已暂停的计划不需重复操作
        if(!Constants.equalsInteger(mp.getPaused(),Constants.ONE) ){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,该计划已恢复,无需重复操作!");
        }
        Plans model = new Plans();
        model.setId(p.getId());
        //检查数据有效性
        model.setUpdateTime(DateUtil.getCurrentDate());
        model.setUpdateUser(user.getId());
        model.setPaused(Constants.ZERO);
        model.setRootDepartId(mp.getRootDepartId());
        model.setDepartId(mp.getDepartId());
        //更新计划数据
        plansExtMapper.updateById(model);
        //历史数据,关闭
        planHistoryExtMapper.insert(initHistoryByModel(model,user.getId(),Constants.PLANHISTORY_TYPE.reagain));
 
        QueryWorkorderExtDTO qw = new QueryWorkorderExtDTO();
        qw.setPlanId(p.getId());
        qw.setDeleted(Constants.ZERO);
        //查询全部已暂停的工单数据
        qw.setPaused(Constants.ONE);
        List<Integer> ids = new ArrayList<>();
        List<WorkorderHistory> whList = new ArrayList<>();
        List<WorkorderExtListVO> orderList = workorderExtMapper.selectList(qw);
        if(orderList != null){
            for(WorkorderExtListVO w : orderList){
                if( Constants.equalsInteger(w.getPaused(),Constants.ONE) ){
                    //已暂停的工单全部恢复
                    whList.add(WorkorderExtServiceImpl.initHistoryByModel(w,user.getId(),Constants.WORKORDER_HISTORY_STATUS.reagain));
                    //操作集合
                    ids.add(w.getId());
                }
            }
        }
        //暂停全部相关工单
        if(ids.size()>0){
            Workorder order = new Workorder();
            order.setPlanId(p.getId());
            order.setUpdateTime(model.getUpdateTime());
            order.setUpdateUser(model.getUpdateUser());
            order.setIds(ids);
            order.setPaused(Constants.ZERO);
            //取消工单
            workorderExtMapper.updateByPlan(order);
            workorderHistoryExtMapper.insertBatch(whList);
        }
 
    }
    /**
     * 删除计划
     * @param id
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void deleteById(Integer id){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        if(id== null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,记录不存在!");
        }
        Plans mp = new Plans();
        mp.setDeleted(Constants.ZERO);
        mp.setId(id);
        mp.setRootDepartId(user.getRootDepartment().getId());
        mp = plansExtMapper.selectOne(new QueryWrapper<>(mp));
        if(mp== null){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,计划不存在!");
        }
        //已暂停的计划不需重复操作
        if(!Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.create) &&!Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.publish) ){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,该计划状态已流转,不能删除!");
        }
        Plans model = new Plans();
        model.setId(id);
        //检查数据有效性
        model.setUpdateTime(DateUtil.getCurrentDate());
        model.setUpdateUser(user.getId());
        model.setDeleted(Constants.ONE);
        model.setRootDepartId(mp.getRootDepartId());
        model.setDepartId(mp.getDepartId());
        //更新计划数据
        plansExtMapper.updateById(model);
        //历史数据,关闭
        planHistoryExtMapper.insert(initHistoryByModel(model,user.getId(),Constants.PLANHISTORY_TYPE.delete));
    }
    /**
     * 恢复计划
     * @param orders
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public   void distributeByBatch(List<Workorder> orders){
        if(orders == null || orders.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(), "对不起,您无权限进行该操作!");
        }
        for(Workorder order : orders){
            distributeDone(user, order,getThisPlanNum(order.getPlanId(),orders));
        }
    }
 
    private int getThisPlanNum(Integer planId, List<Workorder> orders) {
        int num = 0;
        for(Workorder order : orders){
           if(Constants.equalsInteger(planId,order.getPlanId())){
               num += Constants.formatIntegerNum(order.getPlanNum());
           }
        }
        return num;
    }
 
    /**
     * 发布计划,只有已生成和已撤回的计划可以发布
     * @param p
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void publishById(Plans p){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!"  );
        }
        if(p.getId()== null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,记录不存在!");
        }
        Plans mp = new Plans();
        mp.setDeleted(Constants.ZERO);
        mp.setId(p.getId());
        mp.setRootDepartId(user.getRootDepartment().getId());
        mp = plansExtMapper.selectOne(new QueryWrapper<>(mp));
        if(mp== null){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,该记录不存在!");
        }
        if(Constants.equalsInteger(mp.getPaused(),Constants.ONE)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,计划已暂停!");
        }
        //只有已生成和已撤回的计划可以发布
        if(!Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.create)
        &&!Constants.equalsInteger(mp.getStatus(),Constants.PLAN_STATUS.back)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(), "对不起,该计划状态已流转,不能进行发布!");
        }
        Plans model = new Plans();
        model.setId(p.getId());
        //检查数据有效性
        model.setUpdateTime(DateUtil.getCurrentDate());
        model.setUpdateUser(user.getId());
        model.setPublishDate(DateUtil.getCurrentDate());
        model.setStatus(Constants.PLAN_STATUS.publish);
        model.setRootDepartId(mp.getRootDepartId());
        model.setDepartId(mp.getDepartId());
        //更新计划数据
        plansExtMapper.updateById(model);
        //历史数据,关闭
        planHistoryExtMapper.insert(initHistoryByModel(model,user.getId(),Constants.PLANHISTORY_TYPE.publish));
    }
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void importPlans(MultipartFile file)  {
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!Constants.equalsInteger(user.getType(),Constants.USERTYPE.COM)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "对不起,您无权限进行该操作!");
        }
        //解析excel
        List<Plans> plansList = EasyExcelUtil.importExcel(file, 1, 1, Plans.class);
        if(plansList == null || plansList.size()==0){
            throw new BusinessException(ResponseStatus.SERVER_ERROR.getCode(), "导入数据内容有误!");
        }
        PlanImport ip = new PlanImport();
        ip.setDeleted(Constants.ZERO);
        ip.setCreateTime(DateUtil.getCurrentDate());
        ip.setCreateUser(user.getId());
        ip.setFileName(file.getOriginalFilename());
        ip.setRootDepartId(user.getRootDepartment().getId());
        ip.setDepartId(user.getComDepartment().getId());
        //计划文件上传记录
        planImportExtMapper.insert(ip);
        int index = 1;
        List<PlanHistory> historyList = new ArrayList<>();
        for(Plans p : plansList){
            p.setType(Constants.PLAN_TYPE.normal);
            p.setCreateTime(DateUtil.getCurrentDate());
            p.setCreateUser(user.getId());
            p.setDeleted(Constants.ZERO);
            p.setDepartId(user.getCurComDepartment().getId());
            p.setRootDepartId(ip.getRootDepartId());
            p.setImportId(ip.getId());
            p.setStatus(Constants.PLAN_STATUS.create);
            p.setOrigin(Constants.PLAS_ORIGIN.imports);
            p.setUserId(user.getId());
//            p.setFactoryId(user.getDepartment().getId());
            //检查数据有效性
            checkData(p,index,user);
            plansExtMapper.insert(p);
            historyList.add(initHistoryByModel(p,user.getId(),Constants.PLANHISTORY_TYPE.create));
            index++;
        }
          //批量导入计划数据
        //plansExtMapper.insertBatch(plansList);
        planHistoryExtMapper.insertBatch(historyList);
    }
 
    public static PlanHistory initHistoryByModel(Plans p,Integer userId,int status,String remark) {
        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.PLANHISTORY_TYPE.getTitleByStatus(p,status));
        h.setType(status);
        h.setInfo(Constants.PLANHISTORY_TYPE.getInfoByStatus(p,status));
        h.setRemark(remark);
        return h;
    }
 
    public static PlanHistory initHistoryByModel(Plans 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.PLANHISTORY_TYPE.getTitleByStatus(p,status));
        h.setType(status);
        h.setInfo(Constants.PLANHISTORY_TYPE.getInfoByStatus(p,status));
        return h;
    }
 
    /**
     * 数据有效性检查
     * @param p
     * @param index
     * @param user
     * @throws BusinessException
     */
    private void checkData(Plans p, int index,LoginUserInfo user) throws BusinessException{
        if(Constants.formatIntegerNum(p.getNum())<=0){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【计划生产数量】数据错误!");
        }
        if(p.getPlanDate() == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【计划日期】数据错误,正确格式为:yyyy-MM-dd(如2022-06-07)!");
        }
        if(StringUtils.isBlank(p.getMaterialCode())){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【产品编码】数据错误!");
        }
        if(p.getFactoryName() == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【生产工厂】数据错误!");
        }
        if(p.getBatch() == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【生产批次】数据错误!");
        }
        if(p.getProcedureCode() == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【生产工序】数据错误!");
        }
 
        Date pDate = DateUtil.getDateFromString(DateUtil.getShortTime(p.getPlanDate()) +" 00:00:00");
        Date nDate =  DateUtil.getDateFromString(DateUtil.getShortTime(DateUtil.getCurrentDate()) +" 00:00:00");
        if( nDate.getTime() > pDate.getTime()){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,计划生产日期必须为今天以后的日期!");
        }
        p.setMaterialCode(p.getMaterialCode().trim());
        p.setFactoryName(p.getFactoryName().trim());
        p.setProcedureCode(p.getProcedureCode().trim());
        p.setBatch(p.getBatch().trim());
        Procedures t = new Procedures();
        t.setDeleted(Constants.ZERO);
        t.setName(p.getProcedureCode());
        t.setRootDepartId(p.getRootDepartId());
        t.setDepartId(p.getDepartId());
        //查询工序信息
        t = proceduresExtMapper.selectOne(new QueryWrapper<>(t).last(" limit 1"));
        if(t == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【生产工序】数据不存在!");
        }
        p.setProcedureId(t.getId());
        QueryMaterialDistributeExtDTO d = new QueryMaterialDistributeExtDTO();
        d.setDeleted(Constants.ZERO);
        d.setMmodelCode(p.getMaterialCode());
        d.setRootDepartId(p.getRootDepartId());
        d.setDepartId(p.getDepartId());
        //查询产品信息
        MaterialDistributeExtListVO mm = materialDistributeExtMapper.selectByModel(d);
        if(mm == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【产品编码】数据不存在!");
        }
        if(Constants.equalsInteger(mm.getStatus(),Constants.ZERO)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【产品】已失效,无法进行生产!");
        }
        //存储物料分配表主键
        p.setMaterialId(mm.getId());
        //单位编码
        p.setUnitId(mm.getUnitId());
        if(Constants.equalsInteger(mm.getStatus(),Constants.ZERO)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【产品编码】不能安排生产计划!");
        }
        Bom bom = new Bom();
        bom.setDeleted(Constants.ZERO);
        bom.setMaterialId(mm.getId());
        bom.setRootDepartId(mm.getRootDepartId());
        bom = bomExtMapper.selectOne(new QueryWrapper<>(bom).last(" limit 1"));
        if(bom == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【产品】BOM未配置数据!");
        }
        if(!Constants.equalsInteger(bom.getStatus(),Constants.ONE)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【产品】BOM已失效,无法进行生产!");
        }
        DepartmentExtListVO f = departmentExtService.getModelByName(user.getCompany().getId(),p.getFactoryName());
        if(f==null || !Constants.equalsInteger(f.getType(),Constants.DEPART_TYPE.factory) ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【生产工厂】数据非工厂组织,请检查!");
        }
        if(Constants.equalsInteger(f.getStatus(),Constants.ONE) ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【生产工厂】当前状态不正确!");
        }
        if(!Constants.equalsInteger(p.getDepartId(),departmentExtService.getComDepartId(f))){
            //如果工厂与公司级组织不对应
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,第【"+(index+2)+"】行【生产工厂】数据非当前公司组织,请检查!");
        }
        p.setFactoryId(f.getId());
    }
    /**
     * 数据有效性检查
     * @param p
     * @param user
     * @throws BusinessException
     */
    private void checkData(Plans p,  LoginUserInfo user) throws BusinessException{
        if(Constants.formatIntegerNum(p.getNum())<=0
                ||p.getPlanDate() == null
                ||StringUtils.isBlank(p.getBatch())
                ||p.getFactoryId() == null
                ||p.getMaterialId() == null
                ||p.getProcedureId() == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,请按要求填写提交数据!");
        }
 
        Date pDate = DateUtil.getDateFromString(DateUtil.getShortTime(p.getPlanDate()) +" 00:00:00");
        Date nDate =  DateUtil.getDateFromString(DateUtil.getShortTime(DateUtil.getCurrentDate()) +" 00:00:00");
        if( nDate .getTime() > pDate.getTime()){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "对不起,计划生产日期必须为今天以后的日期!");
        }
        Procedures t = new Procedures();
        t.setDeleted(Constants.ZERO);
        t.setId(p.getProcedureId());
        t.setRootDepartId(p.getRootDepartId());
        t.setDepartId(p.getDepartId());
        //查询工序信息
        t = proceduresExtMapper.selectOne(new QueryWrapper<>(t));
        if(t == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,生产工序不存在!");
        }
 
        QueryMaterialDistributeExtDTO d = new QueryMaterialDistributeExtDTO();
        d.setDeleted(Constants.ZERO);
        d.setId(p.getMaterialId());
        d.setRootDepartId(p.getRootDepartId());
        d.setDepartId(p.getDepartId());
        //查询产品信息
        MaterialDistributeExtListVO mm = materialDistributeExtMapper.selectByModel(d);
        if(mm == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,产品编码数据不存在!");
        }
        if(Constants.equalsInteger(mm.getStatus(),Constants.ZERO)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,产品已失效,无法进行生产!");
        }
        //单位编码
        p.setUnitId(mm.getUnitId());
        if(Constants.equalsInteger(mm.getStatus(),Constants.ZERO)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,产品编码当前不能安排生产计划!");
        }
        Bom bom = new Bom();
        bom.setDeleted(Constants.ZERO);
        bom.setMaterialId(mm.getId());
        bom.setRootDepartId(mm.getRootDepartId());
        bom = bomExtMapper.selectOne(new QueryWrapper<>(bom).last(" limit 1"));
        if(bom == null){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,产品BOM未配置数据!");
        }
        if(!Constants.equalsInteger(bom.getStatus(),Constants.ONE)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,产品BOM已失效,无法进行生产!");
        }
        DepartmentExtListVO f = departmentExtService.getModelById(user.getCompany().getId(),p.getFactoryId());
        if(!Constants.equalsInteger(f.getType(),Constants.DEPART_TYPE.factory)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,生产工厂数据非工厂组织,请检查!");
        }
        if(Constants.equalsInteger(f.getStatus(),Constants.ONE) ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起,生产工厂当前状态不正确!");
        }
        if(!Constants.equalsInteger(p.getDepartId(),departmentExtService.getComDepartId(f))){
            //如果工厂与公司级组织不对应
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"对不起, 生产工厂数据非当前公司组织,请检查!");
        }
    }
 
    @Override
    public synchronized  String  getNextCode(Integer comId ){
        String prefix =   DateUtil.getDate(new Date(),"yyyyMMdd") +"-";
        Integer countNum  = RedisUtil.getObject(redisTemplate, Constants.RedisKeys.COM_PLANS_CODE_KEY+comId,Integer.class);
        countNum = Constants.formatIntegerNum(countNum)+1;
        //更新缓存
        RedisUtil.addObject(redisTemplate,Constants.RedisKeys.COM_PLANS_CODE_KEY+comId,countNum);
        String nextIndex =Integer.toString( countNum);
        return prefix + StringUtils.leftPad(nextIndex,4,"0");
    }
    @Override
    public synchronized  String  getNextBatch(Integer comId ){
        String prefix =  "FX-"+ DateUtil.getDate(new Date(),"yyyyMMdd") +"-";
        Integer countNum  = RedisUtil.getObject(redisTemplate, Constants.RedisKeys.COM_PLAN_BATCH_KEY+comId,Integer.class);
        countNum = Constants.formatIntegerNum(countNum)+1;
        //更新缓存
        RedisUtil.addObject(redisTemplate,Constants.RedisKeys.COM_PLAN_BATCH_KEY+comId,countNum);
        String nextIndex =Integer.toString( countNum);
        return prefix + StringUtils.leftPad(nextIndex,4,"0");
    }
 
 
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void pauseByIdForStandard(Plans model,LoginUserInfo userInfo){
 
        model.setUpdateTime(DateUtil.getCurrentDate());
        model.setUpdateUser(userInfo.getId());
        model.setPaused(Constants.ONE);
        //更新计划数据
        plansExtMapper.updateById(model);
 
        QueryWorkorderExtDTO qw = new QueryWorkorderExtDTO();
        qw.setPlanId(model.getId());
        qw.setDeleted(Constants.ZERO);
        List<Integer> ids = new ArrayList<>();
        List<WorkorderHistory> whList = new ArrayList<>();
        List<WorkorderExtListVO> orderList = workorderExtMapper.selectList(qw);
        if(orderList != null){
            for(WorkorderExtListVO w : orderList){
                if( Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.create)||
                        Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.material)||
                        Constants.equalsInteger(w.getStatus(),Constants.WORKORDER_STATUS.baogong) ){
                    //已创建、已投料和已报工的工单暂停
                    whList.add(WorkorderExtServiceImpl.initHistoryByModel(w,userInfo.getId(),Constants.WORKORDER_HISTORY_STATUS.pause));
                    //操作集合
                    ids.add(w.getId());
                }
            }
        }
        //暂停全部相关工单
        if(ids.size()>0){
            Workorder order = new Workorder();
            order.setPlanId(model.getId());
            order.setUpdateTime(model.getUpdateTime());
            order.setUpdateUser(model.getUpdateUser());
            order.setIds(ids);
            order.setPaused(Constants.ONE);
            //取消工单
            workorderExtMapper.updateByPlan(order);
            workorderHistoryExtMapper.insertBatch(whList);
        }
 
    }
    /**
     * 恢复计划
     * @param
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void regainByIdForStandard(Plans model,LoginUserInfo userInfo){
        model.setUpdateTime(DateUtil.getCurrentDate());
        model.setUpdateUser(userInfo.getId());
        model.setPaused(Constants.ZERO);
        //更新计划数据
        plansExtMapper.updateById(model);
        QueryWorkorderExtDTO qw = new QueryWorkorderExtDTO();
        qw.setPlanId(model.getId());
        qw.setDeleted(Constants.ZERO);
        //查询全部已暂停的工单数据
        qw.setPaused(Constants.ONE);
        List<Integer> ids = new ArrayList<>();
        List<WorkorderHistory> whList = new ArrayList<>();
        List<WorkorderExtListVO> orderList = workorderExtMapper.selectList(qw);
        if(orderList != null){
            for(WorkorderExtListVO w : orderList){
                if( Constants.equalsInteger(w.getPaused(),Constants.ONE) ){
                    //已暂停的工单全部恢复
                    whList.add(WorkorderExtServiceImpl.initHistoryByModel(w,userInfo.getId(),Constants.WORKORDER_HISTORY_STATUS.reagain));
                    //操作集合
                    ids.add(w.getId());
                }
            }
        }
        //暂停全部相关工单
        if(ids.size()>0){
            Workorder order = new Workorder();
            order.setPlanId(model.getId());
            order.setUpdateTime(model.getUpdateTime());
            order.setUpdateUser(model.getUpdateUser());
            order.setIds(ids);
            order.setPaused(Constants.ZERO);
            //取消工单
            workorderExtMapper.updateByPlan(order);
            workorderHistoryExtMapper.insertBatch(whList);
        }
 
    }
 
 
    /**
     * 一键报工
     * @param user
     */
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    @Override
    public void autoWorkReport(LoginUserInfo user, AutoWorkReportDTO autoWorkReportDTO){
        if(Objects.isNull(autoWorkReportDTO)
            || Objects.isNull(autoWorkReportDTO.getCreateWorkorderRecordDTO())
            || Objects.isNull(autoWorkReportDTO.getCreateWorkorderRecordDTO().getUnQualifiedNum())|| autoWorkReportDTO.getCreateWorkorderRecordDTO().getUnQualifiedNum().compareTo(BigDecimal.ZERO) < Constants.ZERO
            || Objects.isNull(autoWorkReportDTO.getCreateWorkorderRecordDTO().getQualifiedNum())|| autoWorkReportDTO.getCreateWorkorderRecordDTO().getQualifiedNum().compareTo(BigDecimal.ZERO) < Constants.ZERO){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        //查询工工序计划状态
        Plans plans = plansExtMapper.selectById(autoWorkReportDTO.getPlansId());
        if(Objects.isNull(plans)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到工序计划数据");
        }
        if(!(plans.getStatus().equals(Constants.PLAN_STATUS.create)||plans.getStatus().equals(Constants.PLAN_STATUS.publish)||plans.getStatus().equals(Constants.PLAN_STATUS.distribute))){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"工序计划已流转,无法操作");
        }
        if(plans.getPaused().equals(Constants.ONE)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"工序计划已暂停,无法操作");
        }
        if(Objects.isNull(autoWorkReportDTO.getCreateWorkorderRecordDTO())){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"参数错误:产出数据");
        }
        //查询工序计划已分配数量
        List<Workorder> workorderList = workorderMapper.selectList(new QueryWrapper<Workorder>().eq("PLAN_ID",plans.getId())
                .eq("STATUS",Constants.WORKORDER_STATUS.baogong));
        //本次产出数量
        BigDecimal num = autoWorkReportDTO.getCreateWorkorderRecordDTO().getQualifiedNum().add(autoWorkReportDTO.getCreateWorkorderRecordDTO().getUnQualifiedNum());
        if(num.compareTo(BigDecimal.ZERO)<=Constants.ZERO){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"参数错误:产出数据");
        }
        //工单已分配数量
        Integer produceNum = workorderList.stream().map(s -> s.getPlanNum()).reduce(Constants.ZERO, Integer::sum);
        Integer surplusNum = plans.getNum() - produceNum;
        if(num.compareTo(BigDecimal.valueOf(surplusNum))>0){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"超出当前工序计划可报工数量");
        }
        Workorder param = new Workorder();
        param.setPlanId(autoWorkReportDTO.getPlansId());
        param.setPlanDate(new Date());
        param.setProGroupId(autoWorkReportDTO.getProGroupId());
        param.setProUserList(autoWorkReportDTO.getProUserList());
        param.setPlanNum(num.intValue());
        //生成工单信息
        param.setUnqualifiedNum(autoWorkReportDTO.getCreateWorkorderRecordDTO().getUnQualifiedNum().intValue());
        param.setQualifiedNum(autoWorkReportDTO.getCreateWorkorderRecordDTO().getQualifiedNum().intValue());
        Workorder workorder = this.distributeDone(user,param,num.intValue());
        //工单投料记录
        CreateMaterialDTO createMaterialDTO = new CreateMaterialDTO();
        if(!Objects.isNull(autoWorkReportDTO.getRecordList())&&autoWorkReportDTO.getRecordList().size()>Constants.ZERO){
            createMaterialDTO.setId(workorder.getId());
            createMaterialDTO.setRecordList(autoWorkReportDTO.getRecordList());
            workorderRecordStandardService.createMaterialStandard(createMaterialDTO);
        }
        //工单产出记录
        autoWorkReportDTO.getCreateWorkorderRecordDTO().setWorkorderId(workorder.getId());
        WorkorderRecord workorderRecord = workorderRecordStandardService.createWorkorderRecord(autoWorkReportDTO.getCreateWorkorderRecordDTO(),user,autoWorkReportDTO.getProUserList().get(Constants.ZERO));
        //工单报工
        workorderRecordStandardService.comfirmDone(workorder,false);
        //更新工单状态
        if(num.compareTo(BigDecimal.valueOf(surplusNum))==Constants.ZERO){
            plans.setStatus(Constants.PLAN_STATUS.done);
        }else{
            if(plans.getStatus().equals(Constants.PLAN_STATUS.create)){
                plans.setStatus(Constants.PLAN_STATUS.distribute);
            }
        }
        plansExtMapper.updateById(plans);
        //发送消息队列处理分享操作
        workorderExtService.statisticNum(workorder);
        //存储报工不良项数据
        if(autoWorkReportDTO.getCreateWorkorderRecordDTO().getUnQualifiedNum().compareTo(BigDecimal.ZERO)<=Constants.ZERO){
            if(!Objects.isNull(autoWorkReportDTO.getCreateUnqualifiedDTOList())&&autoWorkReportDTO.getCreateUnqualifiedDTOList().size()>Constants.ZERO){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"不良项错误:请检查不良项数据");
            }
        }else{
            List<CreateUnqualifiedDTO> createUnqualifiedDTOList = autoWorkReportDTO.getCreateUnqualifiedDTOList();
            BigDecimal unqualified = createUnqualifiedDTOList.stream().map(s -> s.getUnQualifiedNum()).reduce(BigDecimal.ZERO, BigDecimal::add);
            if(unqualified.compareTo(autoWorkReportDTO.getCreateWorkorderRecordDTO().getUnQualifiedNum())!=Constants.ZERO){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"不良项错误:请检查不良项数据");
            }
            for (CreateUnqualifiedDTO createUnqualifiedDTO:createUnqualifiedDTOList) {
                if(createUnqualifiedDTO.getUnQualifiedNum().compareTo(BigDecimal.ZERO)==Constants.ZERO
                ||Objects.isNull(createUnqualifiedDTO.getCategoryId())){
                    throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"不良项错误:请检查不良项数据");
                }
                UnqualifiedRecord unqualifiedRecord = new UnqualifiedRecord();
                unqualifiedRecord.setDeleted(Constants.ZERO);
                unqualifiedRecord.setCreateUser(user.getId());
                unqualifiedRecord.setCreateTime(new Date());
                unqualifiedRecord.setRootDepartId(plans.getRootDepartId());
                unqualifiedRecord.setDepartId(plans.getDepartId());
                unqualifiedRecord.setWorkorderId(workorder.getId());
                unqualifiedRecord.setRecordId(workorderRecord.getId());
                unqualifiedRecord.setCategoryId(createUnqualifiedDTO.getCategoryId());
                unqualifiedRecord.setUnqualifiedNum(createUnqualifiedDTO.getUnQualifiedNum());
                unqualifiedRecordMapper.insert(unqualifiedRecord);
            }
        }
    }
 
 
}