李林
2023-10-07 658d4927d468c47208fd012d9128b09249c07eff
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
package com.chinaztt.mes.production.state.productmain;
 
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chinaztt.ifs.api.feign.IfsFeignClient;
import com.chinaztt.mes.basic.entity.Location;
import com.chinaztt.mes.basic.entity.Part;
import com.chinaztt.mes.basic.entity.Workstation;
import com.chinaztt.mes.basic.entity.WorkstationLocation;
import com.chinaztt.mes.basic.mapper.LocationMapper;
import com.chinaztt.mes.basic.mapper.PartMapper;
import com.chinaztt.mes.basic.mapper.WorkstationLocationMapper;
import com.chinaztt.mes.basic.mapper.WorkstationMapper;
import com.chinaztt.mes.common.handler.StateMachineHandler;
import com.chinaztt.mes.common.util.StateResult;
import com.chinaztt.mes.plan.dto.ManufacturingOrderDTO;
import com.chinaztt.mes.plan.entity.ManufacturingOrder;
import com.chinaztt.mes.plan.entity.MoRoutingOperation;
import com.chinaztt.mes.plan.entity.MoStructureComponent;
import com.chinaztt.mes.plan.mapper.ManufacturingOrderMapper;
import com.chinaztt.mes.plan.mapper.MoRoutingOperationMapper;
import com.chinaztt.mes.plan.mapper.MoStructureComponentMapper;
import com.chinaztt.mes.plan.state.manufacturing.ManufacturingOrderStateMachineConfig;
import com.chinaztt.mes.plan.state.manufacturing.constant.ManufacturingOrderEvents;
import com.chinaztt.mes.plan.state.manufacturing.constant.ManufacturingOrderStateStringValues;
import com.chinaztt.mes.plan.state.manufacturing.constant.ManufacturingOrderStates;
import com.chinaztt.mes.production.dto.*;
import com.chinaztt.mes.production.entity.*;
import com.chinaztt.mes.production.mapper.*;
import com.chinaztt.mes.production.service.MouldUseRecordService;
import com.chinaztt.mes.production.service.ProductMainIfsLogService;
import com.chinaztt.mes.production.state.operationtask.constant.OperationTaskStateStringValues;
import com.chinaztt.mes.production.state.productmain.constant.ProductMainEvents;
import com.chinaztt.mes.production.state.productmain.constant.ProductMainStateStringValues;
import com.chinaztt.mes.production.state.productout.constant.ProductOutStateStringValues;
import com.chinaztt.mes.quality.dto.ApplyDTO;
import com.chinaztt.mes.quality.dto.ApplyPartDTO;
import com.chinaztt.mes.quality.entity.Apply;
import com.chinaztt.mes.quality.entity.ApplyPart;
import com.chinaztt.mes.quality.entity.Result;
import com.chinaztt.mes.quality.entity.TestRule;
import com.chinaztt.mes.quality.mapper.ApplyMapper;
import com.chinaztt.mes.quality.mapper.ApplyPartMapper;
import com.chinaztt.mes.quality.mapper.ResultMapper;
import com.chinaztt.mes.quality.mapper.TestRuleMapper;
import com.chinaztt.mes.quality.service.ApplyService;
import com.chinaztt.mes.quality.state.result.constant.ResultStateStringValues;
import com.chinaztt.mes.quality.utils.ResultUtils;
import com.chinaztt.mes.quality.utils.TestApplyRuleUtils;
import com.chinaztt.mes.technology.entity.RoutingOperation;
import com.chinaztt.mes.technology.mapper.RoutingOperationMapper;
import com.chinaztt.mes.warehouse.dto.StockAddDTO;
import com.chinaztt.mes.warehouse.entity.Stock;
import com.chinaztt.mes.warehouse.mapper.StockMapper;
import com.chinaztt.mes.warehouse.service.impl.JoinStockOrderServiceImpl;
import com.chinaztt.mes.warehouse.util.StockUtils;
import com.chinaztt.mes.warehouse.util.TransactionType;
import com.chinaztt.ztt.common.core.util.R;
import com.chinaztt.ztt.common.security.component.PermissionService;
import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
 
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
 
 
/**
 * @Author: zhangxy
 * @Date: 2020-08-24 9:51
 */
@Slf4j
@AllArgsConstructor
@Component
@WithStateMachine(id = "productMainStateMachine")
public class ProductMainStateListener {
 
    private ProductMainMapper productMainMapper;
    private WorkstationMapper workstationMapper;
    private WorkstationLocationMapper workstationLocationMapper;
    private OperationTaskMapper operationTaskMapper;
    private ProductOutputMapper productOutputMapper;
    private RoutingOperationMapper routingOperationMapper;
    private ResultMapper resultMapper;
    private PartMapper partMapper;
    private TestRuleMapper testRuleMapper;
    private PermissionService permissionService;
    private ApplyService applyService;
    private ResultUtils resultUtils;
    private OperationTaskMaterialMapper operationTaskMaterialMapper;
    private JoinStockOrderServiceImpl joinStockOrderService;
    private StockUtils stockUtils;
    private StockMapper stockMapper;
    private MouldUseRecordService mouldUseRecordService;
    private ManufacturingOrderMapper manufacturingOrderMapper;
    private ProductInputMapper productInputMapper;
    private IfsFeignClient ifsFeignClient;
    private MoRoutingOperationMapper moRoutingOperationMapper;
    private LocationMapper locationMapper;
    private MoStructureComponentMapper moStructureComponentMapper;
    private ProductMainIfsReportMapper productMainIfsReportMapper;
    private ProductMainIfsLogService productMainIfsLogService;
    private TestApplyRuleUtils testApplyRuleUtils;
    private ApplyPartMapper applyPartMapper;
    private ApplyMapper applyMapper;
    private OperationTaskSupplyMapper operationTaskSupplyMapper;
    private ExaminerMapper examinerMapper;
    private StateMachineFactory<ManufacturingOrderStates, ManufacturingOrderEvents> manufacturingOrderStateMachineFactory;
    private StateMachinePersister<ManufacturingOrderStates, ManufacturingOrderEvents, ManufacturingOrder> persister;
 
    /**
     * 报工单撤回的权限
     */
    private static final String REVOKE_ROLE = "product_main_revoke";
 
    /**
     * 提交
     *
     * @param stateMachine
     * @param msg
     * @return
     */
    @OnTransition(source = ProductMainStateStringValues.PROCESSING, target = ProductMainStateStringValues.SUBMITTED)
    public boolean submit(StateMachine stateMachine, Message<ProductMainEvents> msg) {
        ProductMain productMain = (ProductMain) msg.getHeaders().get("productMain");
        log.info("进入提交状态机:"+productMain.getProductNo());
        productMain.setState(ProductMainStateStringValues.SUBMITTED);
        productMainMapper.updateById(productMain);
        updateCompletedQuantity(productMain, false);
        OperationTask operationTask = operationTaskMapper.selectById(productMain.getOperationTaskId());
        OperationTaskSupply operationTaskSupply = operationTaskSupplyMapper.selectOne(Wrappers.<OperationTaskSupply>lambdaQuery()
                .eq(OperationTaskSupply::getOperationTaskId, productMain.getOperationTaskId()));
        ManufacturingOrder manufacturingOrder = manufacturingOrderMapper.selectOne(Wrappers.<ManufacturingOrder>lambdaQuery()
                .eq(ManufacturingOrder::getId, operationTaskSupply.getMoId()));
        if(operationTask.getPartId().equals(manufacturingOrder.getPartId())){
            manufacturingOrder.setQtyFinished(operationTask.getCompletedQuantity());
            manufacturingOrderMapper.updateById(manufacturingOrder);
        }
        // 模具使用记录,调用模具接口
        try {
            mouldUseRecordService.insertMouldLife(productMain);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error(e.getMessage(), e);
        }
        // 产出提交时:自动报检
        try {
            autoInspection(productMain, false);
//        } catch (Exception e) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, e.getMessage());
//            return false;
//        }
        // 调用ifs
//        try {
        ifsHandle(productMain, 1);
        } catch (RuntimeException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, e.getMessage() == null ? "未知错误": e.getMessage());
            e.printStackTrace();
            return false;
        }
        //  超报则完成该工单
        try {
            checkOverProduction(productMain);
        }catch (RuntimeException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, e.getMessage() == null ? "未知错误": e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }
 
    /**
     * 跳线车间提交
     * @param stateMachine
     * @param msg
     * @return
     */
    @OnTransition(source = ProductMainStateStringValues.DRAFT, target = ProductMainStateStringValues.SUBMITTED)
    public boolean stepSubmit(StateMachine stateMachine, Message<ProductMainEvents> msg) {
        ProductMain productMain = (ProductMain) msg.getHeaders().get("productMain");
        productMain.setState(ProductMainStateStringValues.SUBMITTED);
        productMainMapper.updateById(productMain);
        updateCompletedQuantity(productMain, false);
        OperationTask operationTask = operationTaskMapper.selectById(productMain.getOperationTaskId());
        OperationTaskSupply operationTaskSupply = operationTaskSupplyMapper.selectOne(Wrappers.<OperationTaskSupply>lambdaQuery()
                .eq(OperationTaskSupply::getOperationTaskId, productMain.getOperationTaskId()));
        ManufacturingOrder manufacturingOrder = manufacturingOrderMapper.selectOne(Wrappers.<ManufacturingOrder>lambdaQuery()
                .eq(ManufacturingOrder::getId, operationTaskSupply.getMoId()));
        if(operationTask.getPartId().equals(manufacturingOrder.getPartId())){
            manufacturingOrder.setQtyFinished(operationTask.getCompletedQuantity());
            manufacturingOrderMapper.updateById(manufacturingOrder);
        }
        // 模具使用记录,调用模具接口
        try {
            mouldUseRecordService.insertMouldLife(productMain);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        // 产出提交时:自动报检
        try {
            autoInspection(productMain, false);
//        } catch (Exception e) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, e.getMessage());
//            return false;
//        }
            // 调用ifs
//        try {
        ifsHandle(productMain, 1);
        } catch (RuntimeException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, e.getMessage() == null ? "未知错误": e.getMessage());
            e.printStackTrace();
            return false;
        }
        //  超报则完成该工单
        try {
            checkOverProduction(productMain);
        }catch (RuntimeException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, e.getMessage() == null ? "未知错误": e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }
 
    /**
     * 撤回提交
     *
     * @param stateMachine
     * @param msg
     * @return
     */
    @OnTransition(source = ProductMainStateStringValues.SUBMITTED, target = ProductMainStateStringValues.DRAFT)
    public boolean revoke(StateMachine stateMachine, Message<ProductMainEvents> msg) {
        if (!permissionService.hasPermission(REVOKE_ROLE)) {
            stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, "您没有撤回的权限");
            return false;
        }
        ProductMain productMain = (ProductMain) msg.getHeaders().get("productMain");
        if (!StringUtils.equals(ProductMainStateStringValues.SUBMITTED, productMain.getState())) {
            stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, "只能撤销已提交工单");
            return false;
        }
 
        ProductOutput productOutput = productOutputMapper.selectOne(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getProductMainId, productMain.getId()));
        try {
        //判断是否检测
        Integer resultNum = resultMapper.selectCount(Wrappers.<Result>lambdaQuery()
                .eq(Result::getSystemNo, productOutput.getSystemNo())
                //.eq(Result::getApplyType, Apply.OUTPUT_APPLY)//解除工作台提交时与尾检的琐定【2022-09-20】
                .eq(Result::getApplyType, testApplyRuleUtils.getApplyTypeBySystemNo(productOutput.getSystemNo()))
                .isNotNull(Result::getIsQualified));
        if (resultNum > 0) {
            stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, "已检测不可撤回");
            return false;
        }
 
            //工作台报工数据删除时需要先校验,是否已经进行了检测汇报
        List<ApplyPart> applyPartList = applyPartMapper.selectApplyApertByInspState(productOutput.getOutBatchNo(), Apply.OUTPUT_APPLY);//这里的检测类型传参无效,无需解锁
        if (!CollectionUtils.isEmpty(applyPartList)) {
            List<ApplyPart> applyPartListChecked = applyPartList.stream().filter(e -> null != e.getReportId()).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(applyPartListChecked)) {
                //没有进行检测汇报,先删除检测申请数据,再删除报工数据
                List<Long> applyIds = applyPartList.stream().map(ApplyPart::getApplyId).collect(Collectors.toList());
                List<Long> applyPartIds = applyPartList.stream().map(ApplyPart::getId).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(applyIds)) {
                    applyMapper.deleteBatchIds(applyIds);
                }
                if (!CollectionUtils.isEmpty(applyPartIds)) {
                    applyPartMapper.deleteBatchIds(applyPartIds);
                }
                //删除检测结果
                resultMapper.deleteBySystemNo(productOutput.getSystemNo());
            } else {
                stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, "已经检测汇报,请先删除检测汇报");
                return false;
            }
        }
 
        productMain.setState(ProductMainStateStringValues.DRAFT);
        productMainMapper.updateById(productMain);
        //更新完成数量
        updateCompletedQuantity(productMain, true);
            // 模具使用记录,调用模具接口
            try {
                mouldUseRecordService.clearMouldLife(productMain);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
 
        // 产出提交时:自动报检
            autoInspection(productMain, true);
//        } catch (Exception e) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, e.getMessage());
//            return false;
//        }
        // 调用ifs
//        try {
            ifsHandle(productMain, 2);
        } catch (RuntimeException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, e.getMessage() == null ? "未知错误": e.getMessage());
            return false;
        }
        return true;
    }
 
    /**
     * 草稿到交班
     *
     * @param stateMachine
     * @param msg
     * @return
     */
    @OnTransition(source = ProductMainStateStringValues.DRAFT, target = ProductMainStateStringValues.CHANGESHIFT)
    public boolean draftToChangeShift(StateMachine stateMachine, Message<ProductMainEvents> msg) {
        ProductMain productMain = (ProductMain) msg.getHeaders().get("productMain");
        List<ProductOutput> productOutputs = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getProductMainId, productMain.getId()));
        for (ProductOutput productOutput : productOutputs) {
            ProductOutput update = new ProductOutput();
            update.setId(productOutput.getId());
            //修改状态
            update.setState(ProductMainStateStringValues.CHANGESHIFT);
            productOutputMapper.updateById(productOutput);
        }
        return true;
    }
 
    /**
     * 交班到草稿
     *
     * @param stateMachine
     * @param msg
     * @return
     */
    @OnTransition(source = ProductMainStateStringValues.CHANGESHIFT, target = ProductMainStateStringValues.DRAFT)
    public boolean ChangeShiftTodraft(StateMachine stateMachine, Message<ProductMainEvents> msg) {
        ProductMain productMain = (ProductMain) msg.getHeaders().get("productMain");
        List<ProductOutput> productOutputs = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getProductMainId, productMain.getId()));
        Integer shiftedNumber = productOutputMapper.getShiftedNumberByOutputIds(productOutputs.stream().map(ProductOutput::getId).collect(Collectors.toList()));
        if (shiftedNumber > 0) {
            stateMachine.getExtendedState().getVariables().put(StateMachineHandler.ERROR_KEY, "交班后产出已提交无法撤销");
            return false;
        }
 
        for (ProductOutput productOutput : productOutputs) {
            // 清空交班id数据
            productOutputMapper.clearShiftOutputId(productOutput.getId());
 
            ProductOutput update = new ProductOutput();
            update.setId(productOutput.getId());
            //修改状态
            productOutput.setState(ProductMainStateStringValues.DRAFT);
            productOutputMapper.updateById(productOutput);
        }
 
        return true;
    }
 
    /**
     * 更新已完成数量
     *
     * @param productMain
     * @param revoke
     */
    private void updateCompletedQuantity(ProductMain productMain, boolean revoke) {
        synchronized (String.valueOf(productMain.getOperationTaskId()).intern()) {
            List<ProductOutput> outputList = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery()
                    .eq(ProductOutput::getProductMainId, productMain.getId()));
            if (CollectionUtil.isNotEmpty(outputList)) {
                List<ProductOutput> changeShiftOutList =
                        productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery()
                                .eq(ProductOutput::getOutBatchNo, outputList.get(0).getOutBatchNo()).eq(ProductOutput::getState, ProductOutStateStringValues.CHANGESHIFT));
                BigDecimal total = outputList.stream().map(ProductOutput::getProductQty).reduce(BigDecimal::add).get();
                if (CollectionUtil.isNotEmpty(changeShiftOutList)) {
                    total =
                            total.add(changeShiftOutList.stream().map(ProductOutput::getProductQty).reduce(BigDecimal.ZERO, BigDecimal::add));
                }
                if (!BigDecimal.ZERO.equals(total)) {
                    operationTaskMapper.updateCompletedQuantity(productMain.getOperationTaskId(), revoke ? total.negate() : total);
                }
            }
        }
    }
 
    /**
     * 自动报检
     *
     * @param productMain
     */
    private void autoInspection(ProductMain productMain, boolean revoke) {
        //1.根据产出查工单-制造订单-工艺工序的配置(检验/自动报检)
        MoRoutingOperation routingOperation = moRoutingOperationMapper.findByProductMainId(productMain.getId());
        if (routingOperation != null) {
            //查询状态为草稿的数据
            List<ProductOutput> productOutputList = productOutputMapper.selectList(Wrappers.<ProductOutput>query().lambda()
//                    .eq(ProductOutput::getState, ProductOutStateStringValues.DRAFT)
                    .eq(ProductOutput::getProductMainId, productMain.getId()).orderByAsc(ProductOutput::getId));
            if (routingOperation.getInspection() == null || routingOperation.getInspection() == false) {
                addStock(productMain, WorkstationLocation.QUALIFIED_LOCATION, productOutputList, revoke, routingOperation.getIsLast());
                //2.不检验:进入检测合格库位,其检测结果为合格,允许使用
                if (CollectionUtil.isNotEmpty(productOutputList)) {
                    productOutputList.stream().forEach(productOutput -> {
                        // 撤销不删除检测结果,保留原有结果也不新增
                        if (revoke) {
                            // 删除检测结果
//                            deleteResult(productOutput.getSystemNo());
                        } else {
                            // 添加检测结果
                            //解除工作台提交时与尾检的琐定【2022-09-20】
                            //resultUtils.addOrUpdateResult(productOutput.getSystemNo(), productOutput.getOutBatchNo(), ResultStateStringValues.NOTEST, null, null, true, null, productOutput.getPartId(), null, Apply.OUTPUT_APPLY);
                            resultUtils.addOrUpdateResult(productOutput.getSystemNo(), productOutput.getOutBatchNo(), ResultStateStringValues.NOTEST, null, null, true, null, productOutput.getPartId(), null, testApplyRuleUtils.getApplyTypeBySystemNo(productOutput.getSystemNo()));
                        }
                    });
                }
            } else {
                // 如果检测类型判断为成品检,则移入成品待检库位,否则移入待检库位
                String applyType = testApplyRuleUtils.getApplyTypeBySystemNo(productOutputList.get(0).getSystemNo());
                if (applyType.equals(Apply.PRODUCT_APPLY)) {
                    addStock(productMain, WorkstationLocation.PENDING_PRODUCT_LOCATION, productOutputList, revoke, routingOperation.getIsLast());
                } else {
                    addStock(productMain, WorkstationLocation.INSPECTION_LOCATION, productOutputList, revoke, routingOperation.getIsLast());
                }
                if (routingOperation.getAutoInspection() == null || !routingOperation.getAutoInspection()) {
                    //3.检验,手动报检:不做处理,手动报检时生成检测记录(防止首检这种的,还没产出就要检验)
                } else {
                    //4.检验,自动报检:
                    if (CollectionUtil.isNotEmpty(productOutputList)) {
                        // 查零件对应的检验规则
                        int inspectQuantity = 1;
                        Long partId = productOutputList.get(0).getPartId();
                        Part part = partMapper.selectById(partId);
                        if (part != null && part.getTestRuleId() != null) {
                            //查询报检数量
                            TestRule testRule = testRuleMapper.selectById(part.getTestRuleId());
                            if (testRule != null) {
                                inspectQuantity = testRule.getInspectQuantity().intValue();
                            }
                        }
                        productOutputList.stream().forEach(productOutput -> {
                            // 撤销不删除检测结果,保留原有结果也不新增
                            if (revoke) {
//                                deleteResult(productOutput.getSystemNo());
                            } else {
                                //解除工作台提交时与尾检的琐定【2022-09-20】
                                //resultUtils.addOrUpdateResult(productOutput.getSystemNo(), productOutput.getOutBatchNo(), null, null, null, null, productMain.getWorkstationId(), partId, null, Apply.OUTPUT_APPLY);
                                resultUtils.addOrUpdateResult(productOutput.getSystemNo(), productOutput.getOutBatchNo(), null, null, null, null, productMain.getWorkstationId(), partId, null, testApplyRuleUtils.getApplyTypeBySystemNo(productOutput.getSystemNo()));
                            }
                        });
                        if (!revoke) {
                            //查询当前机台未报检的零件,按报检数量分组自动生成质检申请
                            List<Result> resultList = resultMapper.selectList(Wrappers.<Result>query().lambda()
                                    .eq(Result::getPartId, partId)
                                    .eq(Result::getWorkstationId, productMain.getWorkstationId())
                                    //.eq(Result::getApplyType, Apply.OUTPUT_APPLY)//解除工作台提交时与尾检的琐定【2022-09-20】
                                    .eq(Result::getApplyType, applyType)//同一个报工单,申请类型必定一样
                                    .eq(Result::getIsErp, false)
                                    .isNull(Result::getCheckStatus)
                                    .orderByAsc(Result::getId));
                            if (CollectionUtil.isNotEmpty(resultList)) {
                                Workstation workstation = workstationMapper.selectById(productMain.getWorkstationId());
                                int count = 0;
                                List<Result> group = new ArrayList<Result>();
                                for (Result result : resultList) {
                                    group.add(result);
                                    count += 1;
                                    if (count == inspectQuantity) {
                                        // 创建质检申请
                                        ApplyDTO applyDTO = new ApplyDTO();
                                        //applyDTO.setApplyType(Apply.OUTPUT_APPLY);//解除工作台提交时与尾检的琐定【2022-09-20】
                                        applyDTO.setApplyType(testApplyRuleUtils.getApplyTypeBySystemNo(productOutputList.get(0).getSystemNo()));//同一个报工单,申请类型必定一样
                                        applyDTO.setRemark("自动报检:" + workstation.getName());
                                        List<ApplyPartDTO> applyPartList = new ArrayList<ApplyPartDTO>();
                                        group.stream().forEach(e -> {
                                            ApplyPartDTO applyPartDTO = new ApplyPartDTO();
                                            applyPartDTO.setSystemNo(e.getSystemNo());
                                            applyPartList.add(applyPartDTO);
                                        });
                                        applyDTO.setApplyPartList(applyPartList);
                                        if(applyService.saveDto(applyDTO)){
                                            group.stream().forEach(e -> {
                                                e.setApplyId(applyDTO.getId());
                                                resultMapper.updateById(e);
                                            });
                                        }
                                        group.clear();
                                        count = 0;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
 
    /**
     * 产出自动进库(不检验进合格,其他进待检)
     *
     * @param productMain
     * @param locationType
     * @param productOutputList
     * @param revoke
     */
    private void addStock(ProductMain productMain, Long locationType, List<ProductOutput> productOutputList, boolean revoke, Boolean isLast) {
        String state = ProductOutStateStringValues.SUBMITTED;
        if (revoke) {
            state = ProductOutStateStringValues.DRAFT;
        }
        WorkstationLocation workstationLocation = workstationLocationMapper.selectOne(Wrappers.<WorkstationLocation>query().lambda()
                .eq(WorkstationLocation::getWorkstationId, productMain.getWorkstationId()).eq(WorkstationLocation::getLocationType, locationType));
        if (workstationLocation == null) {
            throw new RuntimeException("机台未配置库位,请配置库位后再操作");
        }
        OperationTaskDTO operationInfo = operationTaskMapper.getOperationInfoById(productMain.getOperationTaskId());
        for (ProductOutput productOutput : productOutputList) {
            //判断当前报告是否已经报工
//            if (state.equals(productOutput.getState())) {
//                return;
//            }
            BigDecimal stockQuantityIncrement = productOutput.getProductQty();
            BigDecimal sstockQuantityIncrement = productOutput.getSproductQty();
            // 判断是否存在交班产出,叠加交班产出
            if (productOutput.getShiftOutputId() != null) {
                List<ProductOutput> shifts = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery()
                        .eq(ProductOutput::getOutBatchNo, productOutput.getOutBatchNo())
                        .eq(ProductOutput::getState, ProductOutStateStringValues.CHANGESHIFT));
                stockQuantityIncrement = stockQuantityIncrement.add(shifts.stream().map(ProductOutput::getProductQty).reduce(BigDecimal.ZERO, BigDecimal::add));
                sstockQuantityIncrement = sstockQuantityIncrement.add(shifts.stream().map(ProductOutput::getSproductQty).reduce(BigDecimal.ZERO, BigDecimal::add));
            }
            if (revoke) {
                stockQuantityIncrement = stockQuantityIncrement.negate();
                sstockQuantityIncrement = sstockQuantityIncrement.negate();
            }
            // 合格库位增加/删除产出
            if (workstationLocation != null && workstationLocation.getLocationId() != null) {
 
                StockAddDTO stockAdd = new StockAddDTO();
                stockAdd.setPartsId(productOutput.getPartId());
                stockAdd.setNewLocationId(workstationLocation.getLocationId());
                stockAdd.setNewPartBatchNo(productOutput.getOutBatchNo());
                stockAdd.setNewSystemNo(productOutput.getSystemNo());
                stockAdd.setReelNumber(productOutput.getReelNumber());
                stockAdd.setCustomerOrderNo(operationInfo.getCustomerOrderNo());
                stockAdd.setMpsNo(operationInfo.getMpsNo());
                stockAdd.setOuterColor(operationInfo.getOuterColor());
                stockAdd.setInsulationColor(operationInfo.getInsulationColor());
                Stock stock = stockUtils.query(stockAdd);
 
                //将实时库存中的ifs批次号更新成与产出记录中的ifs批次号一致
                stock.setIfsBatchNo(productOutput.getIfsBatchNo());
                stockMapper.updateById(stock);
 
                stockUtils.updateById(stock.getId(), stockQuantityIncrement, BigDecimal.ZERO, sstockQuantityIncrement, BigDecimal.ZERO, null, TransactionType.PRODUCT_SUBMIT.getValue());
                // 设置是否工序库存
                setOperationStockStatus(stock, isLast);
                //查询当前工单同一个制造订单下的下一道工序的工单的工艺工序
                List<OperationTask> operationTaskList = operationTaskMapper.getLastOperationTask(productMain.getOperationTaskId());
                if (CollectionUtil.isNotEmpty(operationTaskList)) {
                    for (OperationTask operationTask : operationTaskList) {
                        //如果触发自动预留,实时库存需要预留的数量
                        BigDecimal number = BigDecimal.ZERO;
                        Stock newStock = stockMapper.selectById(stock.getId());
                        RoutingOperation routingOperation = routingOperationMapper.selectById(operationTask.getRoutingOperationId());
                        if (routingOperation != null) {
                            //如果当前工单绑定的工艺路线配置了自动预留并且是提交的时候,计算出预留的数量
                            if (routingOperation.getReserved() && !revoke) {
//                                OperationTaskMaterial operationTaskMaterial = operationTaskMaterialMapper.selectOne(Wrappers
//                                        .<OperationTaskMaterial>lambdaQuery().eq(OperationTaskMaterial::getOperationTaskId,operationTask.getId())
//                                        .eq(OperationTaskMaterial::getPartId,productOutput.getPartId()));
                                QueryWrapper<OperationTaskMaterialDTO> wrapper = new QueryWrapper<>();
                                OperationTaskMaterialDTO operationTaskMaterial =
                                        operationTaskMaterialMapper.getMaterial(wrapper.lambda().eq(OperationTaskMaterialDTO::getOperationTaskId, operationTask.getId())
                                                .eq(OperationTaskMaterialDTO::getPartId, productOutput.getPartId())).get(0);
 
                                if (operationTaskMaterial != null) {               //需求数量                                              //已预留
                                    BigDecimal needNumber = operationTaskMaterial.getQuantityRequired().subtract(operationTaskMaterial.getReservedQuantity());
                                    if (needNumber.compareTo(BigDecimal.ZERO) > 0) {
                                        // <
                                        if (needNumber.compareTo(newStock.getAvailableStockQuantity()) < 0) {//可用库存数量
                                            number = needNumber;
                                        } else {
                                            number = newStock.getAvailableStockQuantity();
                                        }
                                    }
                                }
                            }
                        }
                        //如果当前工单绑定的工艺路线配置了自动预留并且是提交的时候,新增工单预留
                        if (routingOperation.getReserved() && !revoke) {
                            joinStockOrderService.addJoinStock(operationTask.getId(), stock, number);
                        }
                    }
                }
            }
            productOutput.setState(state);
            productOutputMapper.updateById(productOutput);
        }
    }
 
    private void setOperationStockStatus(Stock stock, Boolean isLast) {
        if (stock.getOperationStockStatus() == null) {
            Stock update = new Stock();
            update.setId(stock.getId());
            if (isLast != null) {
                update.setOperationStockStatus(!isLast);
            } else {
                update.setOperationStockStatus(true);
            }
            stockMapper.updateById(update);
        }
    }
 
    /**
     * 撤销删除检验记录
     *
     * @param systemNo
     */
    private void deleteResult(String systemNo) {
        Result result = resultMapper.selectOne(Wrappers.<Result>query().lambda().eq(Result::getSystemNo, systemNo).eq(Result::getIsErp, false));
        if (result != null && result.getId() != null) {
            resultMapper.deleteById(result.getId());
            if (result.getApplyId() != null) {
                // 更新这个自动报检申请下面的所有产出结果记录
                resultMapper.revokeApplyByApplyId(result.getApplyId());
                applyService.deleteById(result.getApplyId());
            }
        }
    }
 
    /**
     * 提交或撤销 ifs
     *
     * @param productMain
     * @param type        1提交,2撤销
     */
    private void ifsHandle(ProductMain productMain, Integer type) {
        // 找出制造订单信息
        ManufacturingOrderDTO order = manufacturingOrderMapper.getOperationSupplyById(productMain.getOperationTaskId()).get(0);
 
        // 过滤产出,交班产出不进行提交
        List<ProductOutputDTO> allList = productOutputMapper.getByMainId(productMain.getId());
        List<ProductOutputDTO> outList = allList.stream().filter(p -> !p.getState().equals(ProductOutStateStringValues.CHANGESHIFT)).collect(Collectors.toList());
        if (outList.isEmpty()) {
            return;
        }
 
        // 找出工序节点信息
        MoRoutingOperation moRoutingOperation = moRoutingOperationMapper.selectOne(Wrappers.<MoRoutingOperation>lambdaQuery().eq(MoRoutingOperation::getMoId, order.getId())
                .eq(MoRoutingOperation::getOperationId, outList.get(0).getOperationId())
                .last("limit 1"));
 
        // 找出工序任务信息
        OperationTask operationTask = operationTaskMapper.selectById(productMain.getOperationTaskId());
 
        // 找出投入信息
        List<ProductInput> productInputs = productInputMapper.selectList(Wrappers.<ProductInput>lambdaQuery().eq(ProductInput::getProductMainId, productMain.getId()));
 
        // 校验参数
        if (order.getIfsOrderNo() == null || order.getIfsReleaseNo() == null || order.getIfsSequenceNo() == null) {
            log.error("订单相关IFS订单号或下达号或序列号为空,无法同步IFS");
            return;
//            throw new RuntimeException("订单相关IFS订单号或下达号或序列号为空,无法同步IFS");
        }
//        for (ProductInput productInput : productInputs) {
//            if (productInput.getIfsLineItemNo() == null) {
//                log.error("SN号为" + productInput.getPartBatchNo() + "的投入,IFS行项号为空,无法同步IFS");
//                return;
////                throw new RuntimeException("SN号为" + productInput.getPartBatchNo() + "的投入,IFS行项号为空,无法同步IFS");
//            }
//        }
 
        // MoRoutingOperation operation = moRoutingOperationMapper.findByOperationTaskId(operationTask.getId());
 
        // 查询产出所需物料结构
        // ManufacturingOrderDTO manufacturingOrderDTO = manufacturingOrderMapper.getOperationSupplyById(operationTask.getId()).get(0);
        // List<MoStructureComponent> componentList =
        //         moStructureComponentMapper.selectList(Wrappers.<MoStructureComponent>lambdaQuery()
        //         .eq(MoStructureComponent::getPlanManufacturingOrderId, manufacturingOrderDTO.getId())
        //         .eq(MoStructureComponent::getPartId, operationTask.getPartId())
        //         .and(wrapper -> wrapper.ne(MoStructureComponent::getOperationId, operation.getOperationId())
        //                 .or(w -> w.isNull(MoStructureComponent::getOperationId))));
        // List<Long> idList = componentList.stream().map(MoStructureComponent::getId).collect(Collectors.toList());
        // List<MoStructureComponent> needComponentList =
        //         moStructureComponentMapper.selectList(Wrappers.<MoStructureComponent>lambdaQuery().in(MoStructureComponent::getParent, idList));
 
        // 存在交班投入,扣除交班相关投入
        // if (allList.size() != outList.size()) {
        //     List<ProductOutputDTO> shiftList = allList.stream().filter(p -> p.getState().equals(ProductOutStateStringValues.CHANGESHIFT)).collect(Collectors.toList());
        //     for (ProductOutputDTO shift : shiftList) {
        //         for (MoStructureComponent moStructureComponent : needComponentList) {
        //             boolean flag = true;
        //             BigDecimal needQty = moStructureComponent.getQpa().multiply(shift.getProductQty().add(shift.getScrapQty()));
        //             for (int i = productInputs.size() - 1; i >= 0; i--) {
        //                 if (moStructureComponent.getPartId().equals(productInputs.get(i).getPartId()) && moStructureComponent.getIfsLineItemNo().equals(productInputs.get(i).getIfsLineItemNo())) {
        //                     // 需求数量小于该投入,直接扣除交班投入
        //                     if (needQty.compareTo(productInputs.get(i).getInputQuantity()) < 0) {
        //                         productInputs.get(i).setInputQuantity(productInputs.get(i).getInputQuantity().subtract(needQty));
        //                         flag = false;
        //                         break;
        //                         // 需求数量等于该投入,移除投入
        //                     } else if (needQty.compareTo(productInputs.get(i).getInputQuantity()) == 0) {
        //                         productInputs.remove(i);
        //                         flag = false;
        //                         break;
        //                     } else {
        //                         productInputs.remove(i);
        //                     }
        //                     needQty = needQty.subtract(productInputs.get(i).getInputQuantity());
        //                 }
        //             }
        //             // 数量不满足
        //             if (flag) {
        //                 Part part = partMapper.selectById(moStructureComponent.getPartId());
        //                 log.error(part.getPartName() + "投入数量不足");
        //                 return;
        //             }
        //         }
        //     }
        // }
 
        // 计算存在交班清空投入和产出进行计算
        for (ProductOutputDTO outputDTO : outList) {
            // 存在交班产出
            if (outputDTO.getShiftOutputId() != null) {
                // 根据相同SN号找出所有交班数据
                List<ProductOutput> shiftOutputList = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getOutBatchNo, outputDTO.getOutBatchNo()).eq(ProductOutput::getState, ProductOutStateStringValues.CHANGESHIFT));
                // 对产量和报废数量进行累加
                for (ProductOutput shift : shiftOutputList) {
                    outputDTO.setProductQty(outputDTO.getProductQty().add(shift.getProductQty()));
                    outputDTO.setScrapQty(outputDTO.getScrapQty().add(shift.getScrapQty()));
 
                    // 找出交班投入
                    List<ProductInput> shiftInputList = productInputMapper.selectList(Wrappers.<ProductInput>lambdaQuery().eq(ProductInput::getProductMainId, shift.getProductMainId()));
 
                    // 对投入进行累加
                    if (CollectionUtil.isNotEmpty(shiftInputList)) {
                        for (ProductInput shiftInput : shiftInputList) {
                            boolean flag = true;
                            for (ProductInput productInput : productInputs) {
                                if (shiftInput.getStockId().equals(productInput.getStockId())) {
                                    productInput.setInputQuantity(productInput.getInputQuantity().add(shiftInput.getInputQuantity()));
                                    flag = false;
                                    break;
                                }
                            }
                            if (flag) {
                                productInputs.add(shiftInput);
                            }
                        }
                    }
 
 
                    // 如果只存在交班产出无需计算,直接累加投入
                    // List<ProductOutput> shiftOutputs = productOutputMapper.selectList(Wrappers.<ProductOutput>lambdaQuery().eq(ProductOutput::getProductMainId, shift.getProductMainId()));
                    // if (shiftOutputs.size() > 1) {
                    //     for (MoStructureComponent moStructureComponent : needComponentList) {
                    //         boolean flag = true;
                    //         BigDecimal needQty = moStructureComponent.getQpa().multiply(shift.getProductQty().add(shift.getScrapQty()));
                    //         for (ProductInput productInput : shiftInputList) {
                    //             if (moStructureComponent.getPartId().equals(productInput.getPartId()) && moStructureComponent.getIfsLineItemNo().equals(productInput.getIfsLineItemNo())) {
                    //                 // 需求数量小于该投入
                    //                 if (needQty.compareTo(productInput.getInputQuantity()) <= 0) {
                    //                     productInput.setInputQuantity(needQty);
                    //                     productInputs.add(productInput);
                    //                     flag = false;
                    //                     break;
                    //                 } else {
                    //                     productInputs.add(productInput);
                    //                 }
                    //                 needQty = needQty.subtract(productInput.getInputQuantity());
                    //             }
                    //         }
                    //         // 数量不满足
                    //         if (flag) {
                    //             Part part = partMapper.selectById(moStructureComponent.getPartId());
                    //             log.error(part.getPartName() + "交班投入数量不足");
                    //             return;
                    //         }
                    //     }
                    // } else {
                    //     productInputs.addAll(shiftInputList);
                    // }
                }
            }
        }
 
        // 获取存在报废数量的报工单
        // List<ProductOutputDTO> scrapOutputList = outList.stream().filter(p -> p.getScrapQty() != null && p.getScrapQty().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
 
        //if (type == 1) {
        //    // 调用IFS车间订单发料接口
        //    ifsImportMaterial(productMain, order, productInputs, type);
        //
        //    // 判断当前车间订单的【IFS车间订单接收时报告工序】字段为否,则执行工序报工
        //    if (manufacturingOrderDTO.getIsReportOperation() != null && !manufacturingOrderDTO.getIsReportOperation()) {
        //        // 调用IFS车间订单工序报废接口
        //        if (!scrapOutputList.isEmpty()) {
        //            ifsImportScrap(productMain, order, scrapOutputList, moRoutingOperation.getOperationOrder());
        //        }
        //
        //        // 调用IFS车间订单工序报工接口
        //        List<MoRoutingOperation> operationList = new ArrayList<>();
        //        operationList.add(moRoutingOperation);
        //        ifsImportReport(productMain, order, outList, operationList);
        //    }
        //} else {
        //    // 判断当前车间订单的【IFS车间订单接收时报告工序】字段为否,则执行工序报工
        //    if (manufacturingOrderDTO.getIsReportOperation() != null && !manufacturingOrderDTO.getIsReportOperation()) {
        //        // 调用IFS车间订单工序取消报工接口
        //        List<ProductMainIfsReport> productMainIfsReports = productMainIfsReportMapper.selectList(Wrappers.<ProductMainIfsReport>lambdaQuery().eq(ProductMainIfsReport::getProductMainId, productMain.getId()));
        //        if (!productMainIfsReports.isEmpty()) {
        //            importUnreport(productMainIfsReports, productMain.getId());
        //        }
        //
        //        // 调用IFS车间订单工序取消报废接口
        //        if (!scrapOutputList.isEmpty()) {
        //            importUnscrap(order, scrapOutputList, moRoutingOperation.getOperationOrder(), productMain.getId());
        //        }
        //    }
        //
        //    // 调用IFS车间订单取消发料接口
        //    ifsImportMaterial(productMain, order, productInputs, type);
        //}
        ifsImportMaterial(productMain, order, productInputs, type);
        // 若产出的物料不需要检测,则继续执行后续步骤;否则流程结束。
        if (moRoutingOperation.getInspection()) {
            return;
        }
 
        // 若产出的物料不是虚拟件且对应的工序是的工艺路线最后一道工序,则继续执行后续步骤;否则流程结束(如需今后要进行IFS工序汇报,功能添加至此)。
        if (outList.get(0).getPlanningMethod().equals("K") || outList.get(0).getPlanningMethod().equals("P") || moRoutingOperation.getIsLast() == null || !moRoutingOperation.getIsLast()) {
            return;
        }
 
        //if (type == 1) {
        //    // 判断当前车间订单的【IFS车间订单接收时报告工序】字段为是,则执行工序报工
        //    if (manufacturingOrderDTO.getIsReportOperation() != null && manufacturingOrderDTO.getIsReportOperation()) {
        //        // 调用IFS车间订单工序报废接口
        //        if (!scrapOutputList.isEmpty()) {
        //            ifsImportScrap(productMain, order, scrapOutputList, moRoutingOperation.getOperationOrder());
        //        }
        //        // 对该工单所有工序进行报工
        //        List<MoRoutingOperation> operationList = moRoutingOperationMapper.selectList(Wrappers.<MoRoutingOperation>lambdaQuery().eq(MoRoutingOperation::getMoId, order.getId()));
        //        // 调用IFS车间订单工序报工接口
        //        ifsImportReport(productMain, order, outList, operationList);
        //    }
        //} else {
        //    // 判断当前车间订单的【IFS车间订单接收时报告工序】字段为否,则执行工序报工
        //    if (manufacturingOrderDTO.getIsReportOperation() != null && manufacturingOrderDTO.getIsReportOperation()) {
        //        // 调用IFS车间订单工序取消报工接口
        //        List<ProductMainIfsReport> productMainIfsReports = productMainIfsReportMapper.selectList(Wrappers.<ProductMainIfsReport>lambdaQuery().eq(ProductMainIfsReport::getProductMainId, productMain.getId()));
        //        if (!productMainIfsReports.isEmpty()) {
        //            importUnreport(productMainIfsReports, productMain.getId());
        //        }
        //
        //        // 调用IFS车间订单工序取消报废接口
        //        if (!scrapOutputList.isEmpty()) {
        //            importUnscrap(order, scrapOutputList, moRoutingOperation.getOperationOrder(), productMain.getId());
        //        }
        //    }
        //}
 
        // 调用IFS车间订单(批量)接收或取消接口
        try {
            ifsImportOperation(productMain, order, outList, operationTask, type);
        } catch (Exception e) {
            if (type == 1) {
                ifsImportMaterial(productMain, order, productInputs, 2);
            }else{
                ifsImportMaterial(productMain, order, productInputs, 1);
            }
            throw e;
        }
    }
 
    /**
     * 发料与取消发料
     *
     * @param productMain
     * @param order
     * @param type        1发料,2取消发料
     */
    private void ifsImportMaterial(ProductMain productMain, ManufacturingOrderDTO order, List<ProductInput> productInputs, Integer type) {
        log.info("import material :" + productMain.getProductNo());
        if (!productInputs.isEmpty()) {
            IfsImportMaterialDTO ifsImportMaterialDTO = new IfsImportMaterialDTO();
            ifsImportMaterialDTO.setRECORD_ID(UUID.randomUUID().toString().replace("-", ""));
            JSONObject mesParams = new JSONObject();
            mesParams.put("productMainId", productMain.getId());
            ifsImportMaterialDTO.setMesParams(mesParams.toJSONString());
            List<IfsImportMaterialDTO.DataBean> beanList = new ArrayList<>();
            ifsImportMaterialDTO.setBATCH_INFO(beanList);
            if (type == 2) {
                ifsImportMaterialDTO.setSYSMODEL("报工单取消发料");
            }
 
            for (ProductInput productInput : productInputs) {
                // 若当前报工单投入零件号为车间订单所关联零件号且该工单所属的车间订单类型为制造(M),则不调用该接口。若是工序库存也不调用接口
//                if ((productInput.getPartId().equals(order.getPartId()) && order.getWorkshopTypeCode().equals("M")) || productInput.getOperationStockStatus()) {
//                    continue;
//                }
                if (StringUtils.isBlank(productInput.getIfsLineItemNo()) || productInput.getOperationStockStatus() == null || productInput.getOperationStockStatus()) {
                    continue;
                }
                IfsImportMaterialDTO.DataBean bean = new IfsImportMaterialDTO.DataBean();
                bean.setORDER_NO(order.getIfsOrderNo());
                bean.setRELEASE_NO(order.getIfsReleaseNo());
                bean.setSEQUENCE_NO(order.getIfsSequenceNo());
                bean.setLINE_ITEM_NO(Integer.parseInt(productInput.getIfsLineItemNo()));
                Part part = partMapper.selectById(productInput.getPartId());
                bean.setPART_NO(part.getPartNo());
                Stock stock = stockMapper.selectById(productInput.getStockId());
                Location location = locationMapper.selectById(stock.getLocationId());
                bean.setLOCATION_NO(location.getIfsLocation());
                if (part.getLotTrackingIfs() != null && part.getLotTrackingIfs()) {
                    bean.setLOT_BATCH_NO(productInput.getIfsBatchNo());
                    bean.setWAIV_DEV_REJ_NO(productInput.getPartBatchNo());
                } else {
                    bean.setLOT_BATCH_NO("*");
                    bean.setWAIV_DEV_REJ_NO("*");
                }
                bean.setENG_CHG_LEVEL(part.getEngChgLevel() == null ? "1" : part.getEngChgLevel());
                if (type == 1) {
                    bean.setQTY_TO_ISSUE(productInput.getInputQuantity());
                } else {
                    bean.setQTY_TO_UNISSUE(productInput.getInputQuantity());
                }
 
                beanList.add(bean);
            }
            if (!beanList.isEmpty()) {
                Gson gson = new Gson();
                JSONObject jsonObject = JSONObject.parseObject(gson.toJson(ifsImportMaterialDTO));//解决序列化时自动将大写转小写问题
                R response = null;
                if (type == 1) {
                    response = ifsFeignClient.importSoMaterialIssueStd(jsonObject, true);
                } else {
                    response = ifsFeignClient.importSoMaterialUnissueStd(jsonObject, true);
                }
                if (response.getCode() == 0) {
                    JSONObject data = (JSONObject) JSON.toJSON(response.getData());
                    if (!data.getBooleanValue("FLAG")) {
                        return;
                    }
                    if (!data.getString("OPERATION_TYPE").equals("1")) {
                        if (type == 1) {
//                            productMainIfsLogService.fastSave("车间订单发料", "importSoMaterialIssueStd", jsonObject.toJSONString(), data.getString("ErrorMsg"));
                            throw new RuntimeException("车间订单发料失败:" + data.getString("ErrorMsg"));
                        } else {
//                            productMainIfsLogService.fastSave("车间订单发料取消", "importSoMaterialUnissueStd", jsonObject.toJSONString(), data.getString("ErrorMsg"));
                            throw new RuntimeException("车间订单发料取消失败:" + data.getString("ErrorMsg"));
                        }
                    }
                } else {
                    if (type == 1) {
//                        productMainIfsLogService.fastSave("车间订单发料", "importSoMaterialIssueStd", jsonObject.toJSONString(), response.getMsg());
                        throw new RuntimeException("车间订单发料失败:" + response.getMsg());
                    } else {
//                        productMainIfsLogService.fastSave("车间订单发料取消", "importSoMaterialUnissueStd", jsonObject.toJSONString(), response.getMsg());
                        throw new RuntimeException("车间订单发料取消失败:" + response.getMsg());
                    }
                }
            }
        }
    }
 
    private void ifsImportReport(ProductMain productMain, ManufacturingOrderDTO order, List<ProductOutputDTO> outList,
                                 List<MoRoutingOperation> operationList) {
        BigDecimal qty = BigDecimal.ZERO;
        for (ProductOutputDTO productOutputDTO : outList) {
            qty = qty.add(productOutputDTO.getProductQty());
        }
 
        IfsImportReportDTO ifsImportReportDTO = new IfsImportReportDTO();
        ifsImportReportDTO.setRECORD_ID(UUID.randomUUID().toString().replace("-", ""));
        JSONObject mesParams = new JSONObject();
        mesParams.put("productMainId", productMain.getId());
        ifsImportReportDTO.setMesParams(mesParams.toJSONString());
        List<IfsImportReportDTO.DataBean> beanList = new ArrayList<>();
        ifsImportReportDTO.setBATCH_INFO(beanList);
        ifsImportReportDTO.setProductMainId(productMain.getId());
        for (MoRoutingOperation operation : operationList) {
            IfsImportReportDTO.DataBean bean = new IfsImportReportDTO.DataBean();
            bean.setORDER_NO(order.getIfsOrderNo());
            bean.setRELEASE_NO(order.getIfsReleaseNo());
            bean.setSEQUENCE_NO(order.getIfsSequenceNo());
            bean.setOPERATION_NO(operation.getOperationOrder() * 10);
            bean.setREPORTED_QTY(qty);
            bean.setMES_REPORT_ID(operation.getId().intValue());
            beanList.add(bean);
        }
        Gson gson = new Gson();
        JSONObject jsonObject = JSONObject.parseObject(gson.toJson(ifsImportReportDTO));//解决序列化时自动将大写转小写问题
        R response = ifsFeignClient.importSoOperReportStd(jsonObject, true);
        if (response.getCode() == 0) {
            JSONObject data = (JSONObject) JSON.toJSON(response.getData());
            if (!data.getBooleanValue("FLAG")) {
                return;
            }
            if (!data.getString("OPERATION_TYPE").equals("1")) {
//                    productMainIfsLogService.fastSave("车间订单工序报工", "importSoOperReportStd", jsonObject.toJSONString(),
//                    data.getString("ErrorMsg"));
                throw new RuntimeException("车间订单工序报工失败:" + data.getString("ErrorMsg"));
            }
            // 保存ifs工序报告id和人工id,用于取消
            JSONArray reportInfosList = data.getJSONArray("REPORT_INFOS");
            for (int i = 0; i < reportInfosList.size(); i++) {
                JSONArray reportInfo = reportInfosList.getJSONObject(i).getJSONArray("REPORT_INFO");
                if (CollectionUtil.isNotEmpty(reportInfo)) {
                    Long ifsOpfeedId = null;
                    Long ifsLaborId = null;
                    for (int j = 0; j < reportInfo.size(); j++) {
                        if (reportInfo.getJSONObject(j).getString("TRANSACTION_CODE").equals("OPFEED")) {
                            ifsOpfeedId = reportInfo.getJSONObject(j).getLongValue("TRANSACTION_ID");
                        } else {
                            ifsLaborId = reportInfo.getJSONObject(j).getLongValue("TRANSACTION_ID");
                        }
                    }
                    ProductMainIfsReport productMainIfsReport = new ProductMainIfsReport();
                    productMainIfsReport.setProductMainId(productMain.getId());
                    productMainIfsReport.setIfsOpfeedId(ifsOpfeedId);
                    productMainIfsReport.setIfsLaborId(ifsLaborId);
                    productMainIfsReportMapper.insert(productMainIfsReport);
                }
            }
        } else {
//                productMainIfsLogService.fastSave("车间订单工序报工", "importSoOperReportStd", jsonObject.toJSONString(),
//                response.getMsg());
            throw new RuntimeException("车间订单工序报工失败:" + response.getMsg());
        }
    }
 
    private void ifsImportScrap(ProductMain productMain, ManufacturingOrderDTO order, List<ProductOutputDTO> outList, Integer operationOrder) {
        IfsImportScrapDTO ifsImportScrapDTO = new IfsImportScrapDTO();
        ifsImportScrapDTO.setRECORD_ID(UUID.randomUUID().toString().replace("-", ""));
        JSONObject mesParams = new JSONObject();
        mesParams.put("productMainId", productMain.getId());
        ifsImportScrapDTO.setMesParams(mesParams.toJSONString());
        List<IfsImportScrapDTO.DataBean> beanList = new ArrayList<>();
        ifsImportScrapDTO.setBATCH_INFO(beanList);
        BigDecimal qty = BigDecimal.ZERO;
        for (ProductOutputDTO productOutputDTO : outList) {
            qty = qty.add(productOutputDTO.getScrapQty());
        }
 
        IfsImportScrapDTO.DataBean bean = new IfsImportScrapDTO.DataBean();
        bean.setORDER_NO(order.getIfsOrderNo());
        bean.setRELEASE_NO(order.getIfsReleaseNo());
        bean.setSEQUENCE_NO(order.getIfsSequenceNo());
        bean.setOPERATION_NO(operationOrder * 10);
        bean.setREPORTED_SCRAP_QTY(qty);
        bean.setSCRAP_REASON("*");
        bean.setSCRAP_NOTE_TEXT("");
        beanList.add(bean);
        Gson gson = new Gson();
        JSONObject jsonObject = JSONObject.parseObject(gson.toJson(ifsImportScrapDTO));//解决序列化时自动将大写转小写问题
        R response = ifsFeignClient.importSoOperScrapStd(jsonObject, true);
        if (response.getCode() == 0) {
            JSONObject data = (JSONObject) JSON.toJSON(response.getData());
            if (!data.getBooleanValue("FLAG")) {
                return;
            }
            if (!data.getString("OPERATION_TYPE").equals("1")) {
//                productMainIfsLogService.fastSave("车间订单工序报废", "importSoOperScrapStd", jsonObject.toJSONString(), data.getString("ErrorMsg"));
                throw new RuntimeException("车间订单工序报废失败:" + data.getString("ErrorMsg"));
            }
        } else {
//            productMainIfsLogService.fastSave("车间订单工序报废", "importSoOperScrapStd", jsonObject.toJSONString(), response.getMsg());
            throw new RuntimeException("车间订单工序报废失败:" + response.getMsg());
        }
    }
 
    private void ifsImportOperation(ProductMain productMain, ManufacturingOrderDTO order, List<ProductOutputDTO> outList, OperationTask operationTask, Integer type) {
        IfsImportOperationDTO importOperationDTO = new IfsImportOperationDTO();
        importOperationDTO.setRECORD_ID(UUID.randomUUID().toString().replace("-", ""));
        JSONObject mesParams = new JSONObject();
        mesParams.put("productMainId", productMain.getId());
        importOperationDTO.setMesParams(mesParams.toJSONString());
        if (type == 2) {
            importOperationDTO.setSYSMODEL("报工单订单取消接收");
        }
        List<IfsImportOperationDTO.DataBean> beanList = new ArrayList<>();
        importOperationDTO.setBATCH_INFO(beanList);
        List<ProductOutput> updateList = new ArrayList<>();
        for (ProductOutputDTO productOutputDTO : outList) {
            // 若产出的物料【已同步至IFS】字段值为否,则继续执行后续步骤;否则判断下一条产出记录。取消相反
            if (type == 1 && productOutputDTO.getIfsSync()) {
                continue;
            } else if (type == 2 && !productOutputDTO.getIfsSync()) {
                continue;
            }
            List<ProductOutputDTO> dutyRecordList = productOutputMapper.getDutyRecordByOutputId(productOutputDTO.getId());
            IfsImportOperationDTO.DataBean bean = new IfsImportOperationDTO.DataBean();
            bean.setORDER_NO(order.getIfsOrderNo());
            bean.setRELEASE_NO(order.getIfsReleaseNo());
            bean.setSEQUENCE_NO(order.getIfsSequenceNo());
            bean.setPART_NO(productOutputDTO.getPartNo());
            WorkstationLocation workstationLocation = workstationLocationMapper.selectOne(Wrappers.<WorkstationLocation>query().lambda()
                    .eq(WorkstationLocation::getWorkstationId, productMain.getWorkstationId()).eq(WorkstationLocation::getLocationType, WorkstationLocation.QUALIFIED_LOCATION));
            Location location = locationMapper.selectById(workstationLocation.getLocationId());
            bean.setLOCATION_NO(location.getIfsLocation());
            Part part = partMapper.selectById(productOutputDTO.getPartId());
            if (part.getLotTrackingIfs() != null && part.getLotTrackingIfs()) {
                bean.setLOT_BATCH_NO(productOutputDTO.getIfsBatchNo());
                bean.setWAIV_DEV_REJ_NO(productOutputDTO.getOutBatchNo());
            } else {
                bean.setLOT_BATCH_NO("*");
                bean.setWAIV_DEV_REJ_NO("*");
            }
            bean.setSERIAL_NO("*");
            bean.setENG_CHG_LEVEL(part.getEngChgLevel() == null ? "1" : part.getEngChgLevel());
            bean.setQUANTITY(productOutputDTO.getProductQty());
            bean.setAUTO_REPORT("是");
            bean.setOUT_SYS_LOT_BAT_NO(productOutputDTO.getOutBatchNo());
            if(CollectionUtil.isNotEmpty(dutyRecordList)){
                bean.setSHIFT_DATE(dutyRecordList.get(0).getNowDutyDate());
                if("早".equals(dutyRecordList.get(0).getShiftName().substring(0,1))){
                    bean.setSHIFT_TYPE("白");
                }else if("夜".equals(dutyRecordList.get(0).getShiftName().substring(0,1))) {
                    bean.setSHIFT_TYPE("夜");
                }
            }
            beanList.add(bean);
            // 产出同步状态更新为已同步或未同步
            ProductOutput update = new ProductOutput();
            update.setId(productOutputDTO.getId());
            if (type == 1) {
                update.setIfsSync(true);
            } else {
                update.setIfsSync(false);
            }
            updateList.add(update);
        }
 
        Gson gson = new Gson();
        JSONObject jsonObject = JSONObject.parseObject(gson.toJson(importOperationDTO));//解决序列化时自动将大写转小写问题
        R response = null;
        if (type == 1) {
            response = ifsFeignClient.importSoReceiveStd(jsonObject, true);
        } else {
            response = ifsFeignClient.importSoUnReceiveStd(jsonObject, true);
        }
        if (response.getCode() == 0) {
            JSONObject data = (JSONObject) JSON.toJSON(response.getData());
            if (!data.getBooleanValue("FLAG")) {
                return;
            }
            // 成功更新同步状态
            if (data.getString("OPERATION_TYPE").equals("1")) {
                updateList.forEach(e -> productOutputMapper.updateById(e));
            } else {
                if (type == 1) {
//                    productMainIfsLogService.fastSave("车间订单接收", "importSoReceiveStd", jsonObject.toJSONString(), data.getString("ErrorMsg"));
                    throw new RuntimeException("车间订单接收失败:" + data.getString("ErrorMsg"));
                } else {
//                    productMainIfsLogService.fastSave("车间订单接收取消", "importSoUnReceiveStd", jsonObject.toJSONString(), data.getString("ErrorMsg"));
                    throw new RuntimeException("车间订单接收取消失败:" + data.getString("ErrorMsg"));
                }
            }
        } else {
            if (type == 1) {
//                productMainIfsLogService.fastSave("车间订单接收", "importSoReceiveStd", jsonObject.toJSONString(), response.getMsg());
                throw new RuntimeException("车间订单接收失败:" + response.getMsg());
            } else {
//                productMainIfsLogService.fastSave("车间订单接收取消", "importSoUnReceiveStd", jsonObject.toJSONString(), response.getMsg());
                throw new RuntimeException("车间订单接收取消失败:" + response.getMsg());
            }
        }
    }
 
    private void importUnreport(List<ProductMainIfsReport> productMainIfsReports, Long productMainId) {
        JSONObject params = new JSONObject();
        params.put("RECORD_ID", UUID.randomUUID().toString().replace("-", ""));
        params.put("SYSCODE", "L-MES");
        params.put("SYSMODEL", "报工单取消工序报工");
        params.put("mesParams", new JSONObject().put("productMainId", productMainId));
        JSONArray jsonArray = new JSONArray();
        for (ProductMainIfsReport productMainIfsReport : productMainIfsReports) {
            JSONObject opfeed = new JSONObject();
            opfeed.put("TRANSACTION_ID", productMainIfsReport.getIfsOpfeedId());
            JSONObject labor = new JSONObject();
            labor.put("TRANSACTION_ID", productMainIfsReport.getIfsLaborId());
            jsonArray.add(opfeed);
            jsonArray.add(labor);
        }
        params.put("BATCH_INFO", jsonArray);
 
        R response = ifsFeignClient.importSoOperUnreportStd(params, true);
        if (response.getCode() == 0) {
            JSONObject data = (JSONObject) JSON.toJSON(response.getData());
            if (!data.getBooleanValue("FLAG")) {
                return;
            }
            if (!data.getString("OPERATION_TYPE").equals("1")) {
//                productMainIfsLogService.fastSave("车间订单工序报工取消", "importSoOperUnreportStd", params.toJSONString(), data.getString("ErrorMsg"));
                throw new RuntimeException("车间订单工序报工取消失败:" + data.getString("ErrorMsg"));
            } else {
                // 取消成功后删除关联表记录
                productMainIfsReportMapper.deleteBatchIds(productMainIfsReports.stream().map(ProductMainIfsReport::getId).collect(Collectors.toList()));
            }
        } else {
//            productMainIfsLogService.fastSave("车间订单工序报工取消", "importSoOperUnreportStd", params.toJSONString(), response.getMsg());
            throw new RuntimeException("车间订单工序报工取消失败:" + response.getMsg());
        }
    }
 
    private void importUnscrap(ManufacturingOrderDTO order, List<ProductOutputDTO> outList, Integer operationOrder, Long productMainId) {
        IfsImportUnscrapDTO ifsImportUnscrapDTO = new IfsImportUnscrapDTO();
        ifsImportUnscrapDTO.setRECORD_ID(UUID.randomUUID().toString().replace("-", ""));
        JSONObject mesParams = new JSONObject();
        mesParams.put("productMainId", productMainId);
        ifsImportUnscrapDTO.setMesParams(mesParams.toJSONString());
        List<IfsImportUnscrapDTO.DataBean> beanList = new ArrayList<>();
        ifsImportUnscrapDTO.setBATCH_INFO(beanList);
        BigDecimal qty = BigDecimal.ZERO;
        for (ProductOutputDTO productOutputDTO : outList) {
            qty = qty.add(productOutputDTO.getScrapQty());
        }
 
        IfsImportUnscrapDTO.DataBean bean = new IfsImportUnscrapDTO.DataBean();
        bean.setORDER_NO(order.getIfsOrderNo());
        bean.setRELEASE_NO(order.getIfsReleaseNo());
        bean.setSEQUENCE_NO(order.getIfsSequenceNo());
        bean.setOPERATION_NO(operationOrder * 10);
        bean.setUNSCRAP_QTY(qty);
        beanList.add(bean);
        Gson gson = new Gson();
        JSONObject jsonObject = JSONObject.parseObject(gson.toJson(ifsImportUnscrapDTO));//解决序列化时自动将大写转小写问题
        R response = ifsFeignClient.importSoOperUnscrapStd(jsonObject, true);
        if (response.getCode() == 0) {
            JSONObject data = (JSONObject) JSON.toJSON(response.getData());
            if (!data.getBooleanValue("FLAG")) {
                return;
            }
            if (!data.getString("OPERATION_TYPE").equals("1")) {
//                productMainIfsLogService.fastSave("车间订单工序报废取消", "importSoOperUnscrapStd", jsonObject.toJSONString(), data.getString("ErrorMsg"));
                throw new RuntimeException("车间订单工序报废取消失败:" + data.getString("ErrorMsg"));
            }
        } else {
//            productMainIfsLogService.fastSave("车间订单工序报废取消", "importSoOperUnscrapStd", jsonObject.toJSONString(), response.getMsg());
            throw new RuntimeException("车间订单工序报废取消失败:" + response.getMsg());
        }
    }
 
 
    void checkOverProduction(ProductMain productMain){
        List<ProductOutputDTO> productOutputDTOList = productOutputMapper.selectCheckOverProduction(productMain.getOperationTaskId());
        //获取该工单下所有状态
        List<String> stateList = productOutputDTOList.stream().map(ProductOutputDTO::getState).collect(Collectors.toList());
        //产出表不存在草稿状态并且工单完成数量超过计划数量5%,该工单完成
        if(!stateList.contains(ProductOutStateStringValues.DRAFT) && productOutputDTOList.get(0).getCompletedQuantity().compareTo(productOutputDTOList.get(0).getPlannedQuantity().multiply(new BigDecimal("0.05").add(BigDecimal.ONE))) >= 0){
            OperationTask operationTask = new OperationTask();
            operationTask.setId(productMain.getOperationTaskId());
            operationTask.setState(OperationTaskStateStringValues.COMPLETED);
            operationTaskMapper.updateById(operationTask);
        }
 
        /*OperationTask operationTask = operationTaskMapper.selectById(productMain.getOperationTaskId());
        List<ProductMain> productMainList = productMainMapper.selectList(Wrappers.<ProductMain>lambdaQuery()
                .eq(ProductMain::getOperationTaskId, productMain.getOperationTaskId()));
        //获取所有报工单id
        List<Long> productMainIdList = productMainList.stream().map(ProductMain::getId).collect(Collectors.toList());
        //计算该工单下所有交班数量
        Integer changeshiftCount = productOutputMapper.countChangeshiftByList(productMainIdList);
        //获取该工单下所有状态
        List<String> stateList = productMainList.stream().map(ProductMain::getState).collect(Collectors.toList());
        //统计该工单下草稿状态数量
        Integer draftSize = stateList.stream().filter(a -> a.equals(ProductMainStateStringValues.DRAFT)).collect(Collectors.toList()).size();
        //工单不存在未交班的草稿状态的报工单并且工单完成数量超过计划数量5%,该工单完成
        if (changeshiftCount.equals(draftSize) && operationTask.getCompletedQuantity().compareTo(operationTask.getPlannedQuantity().multiply(new BigDecimal("0.05").add(BigDecimal.ONE))) >= 0){
            operationTask.setState(OperationTaskStateStringValues.COMPLETED);
            operationTaskMapper.updateById(operationTask);
            List<OperationTaskSupply> operationTaskSupplyList = operationTaskSupplyMapper.selectList(Wrappers.<OperationTaskSupply>lambdaQuery()
                    .eq(OperationTaskSupply::getOperationTaskId, operationTask.getId()));
            ManufacturingOrder manufacturingOrder = manufacturingOrderMapper.selectById(operationTaskSupplyList.get(0).getMoId());
            if(!ManufacturingOrderStateStringValues.COMPLETED.equals(manufacturingOrder.getState())) {
                //根据工单id查找对应车间订单下所有工单状态
                List<String> operationTaskList = operationTaskMapper.getAllTaskStateByTaskId(operationTask.getId());
                boolean match = operationTaskList.stream().allMatch(a -> a.equals(OperationTaskStateStringValues.COMPLETED));
                //如果所有工单都完成,则车间订单完成。调用车间订单状态机(完成状态)
                if (match) {
                    Message<ManufacturingOrderEvents> message = MessageBuilder.withPayload(ManufacturingOrderEvents.valueOf("COMPLETE")).setHeader("manufacturingOrder", manufacturingOrder).build();
                    StateMachineHandler handler = new StateMachineHandler(manufacturingOrderStateMachineFactory, persister, ManufacturingOrderStateMachineConfig.MACHINE_ID, manufacturingOrder);
                    StateResult res = handler.sendEvent(message, manufacturingOrder.getId());
                    if (!res.isSuccess()) {
                        throw new RuntimeException(res.getMsg());
                    }
                }
            }
            //根据工单id判断当前是否是最后一道工序工单
            Boolean validateIsLastOperation = operationTaskMapper.validateIsLastOperation(productMain.getOperationTaskId());
            if(validateIsLastOperation!=null && validateIsLastOperation){
                //车间订单的完成数量同车间订单下面最后一个工单的完成数量
                BigDecimal qtyFinished = operationTask.getCompletedQuantity();
                manufacturingOrder.setQtyFinished(qtyFinished);
                manufacturingOrderMapper.updateById(manufacturingOrder);
            }
        }*/
 
    }
}