李林
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
package com.chinaztt.mes.quality.service.impl;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.chinaztt.ifs.api.feign.IfsFeignClient;
import com.chinaztt.mes.basic.entity.WorkstationLocation;
import com.chinaztt.mes.basic.mapper.WorkstationLocationMapper;
import com.chinaztt.mes.basic.util.AesUtils;
import com.chinaztt.mes.common.wrapper.QueryWrapperUtil;
import com.chinaztt.mes.quality.dto.*;
import com.chinaztt.mes.quality.entity.*;
import com.chinaztt.mes.quality.mapper.*;
import com.chinaztt.mes.quality.service.ApplyPartService;
import com.chinaztt.mes.quality.service.ApplyService;
import com.chinaztt.mes.quality.service.ReportSampleService;
import com.chinaztt.mes.quality.service.ReportService;
import com.chinaztt.mes.quality.state.result.constant.ResultStateStringValues;
import com.chinaztt.mes.quality.state.unqualifiedprocess.constant.UnqualifiedprocessStateStringValues;
import com.chinaztt.mes.quality.utils.ReportUtils;
import com.chinaztt.mes.quality.utils.TestApplyRuleUtils;
import com.chinaztt.mes.warehouse.entity.Stock;
import com.chinaztt.mes.warehouse.mapper.StockMapper;
import com.chinaztt.mes.warehouse.service.StockService;
import com.chinaztt.mes.warehouse.util.StockUtils;
import com.chinaztt.mes.warehouse.util.TransactionType;
import com.chinaztt.ztt.admin.api.feign.RemoteParamService;
import com.chinaztt.ztt.common.core.constant.SecurityConstants;
import com.chinaztt.ztt.common.core.util.R;
import com.chinaztt.ztt.common.security.util.SecurityUtils;
import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
 
/**
 * 检测申请材料表
 *
 * @author cxf
 * @date 2021-04-01 13:34:51
 */
@Service
@AllArgsConstructor
@Component
@Transactional(rollbackFor = Exception.class)
public class ApplyPartServiceImpl extends ServiceImpl<ApplyPartMapper, ApplyPart> implements ApplyPartService {
    private static final long ONE = 1L;
    private static final long TWO = 2L;
    public static final String MOVELIBRARY = "mv";//移库码
    public static final String UNMOVELIBRARY = "unmv";//取消移库码
    private static final String SYSTEM = "L-MES";
    private static final String SYSTEM_NAME = "采购检验后移库";
    private static final String NEW_SYSTEM_NAME = "登记检验结果";
    @Resource
    private ResultMapper resultMapper;
    @Resource
    private RemoteParamService remoteParamService;
    @Autowired
    private StockBean stockBean;
    @Autowired
    private StockUtils stockUtils;
    @Resource
    private WorkstationLocationMapper workstationLocationMapper;
    private ReportService reportService;
    @Autowired
    private ApplyService applyService;
    @Resource
    private ReportMapper reportMapper;
    @Resource
    private ApplyPartMapper applyPartMapper;
    @Resource
    private IfsFeignClient ifsFeignClient;
    @Resource
    private ReportUtils reportUtils;
    @Resource
    private ReportSampleService reportSampleService;
    @Resource
    private ReportSampleMapper reportSampleMapper;
    @Resource
    private TestApplyRuleUtils testApplyRuleUtils;
    @Resource
    private StockMapper stockMapper;
    @Resource
    private ApplyPartFileMapper applyPartFileMapper;
 
    @Resource
    private UnqualifiedProcessMapper unqualifiedProcessMapper;
 
    @Autowired
    public ApplyPartServiceImpl(@Lazy ReportService reportService) {
        this.reportService = reportService;
    }
 
 
 
    @Override
    public IPage getApplyPartPage(Page page, QueryWrapper<ApplyPartDTO> gen) {
        return baseMapper.getApplyPartPage(page, gen);
    }
 
    @Override
    public IPage getApplyPartPageForReport(Page page, QueryWrapper<ApplyPartDTO> gen) {
        return baseMapper.getApplyPartPageForReport(page, gen);
    }
 
    @Override
    public IPage getApplyPartPageForUnqualified(Page page, QueryWrapper<ApplyPartDTO> gen, Long unqualifiedProcessId) {
        IPage<ApplyPartDTO> applyPartPageForUnqualifiedList = baseMapper.getApplyPartPageForUnqualified(page, gen, unqualifiedProcessId);
        List<ApplyPartDTO> records = applyPartPageForUnqualifiedList.getRecords();
        for (ApplyPartDTO applyPartDTO:records) {
            if(applyPartDTO.getReplacePartId()!=null){
                applyPartDTO.setPartId(applyPartDTO.getReplacePartId());
                applyPartDTO.setPartNo(applyPartDTO.getReplacePartNo());
                applyPartDTO.setPartName(applyPartDTO.getReplacePartName());
                applyPartDTO.setPartDesc(applyPartDTO.getReplacePartName());
            }
        }
        return applyPartPageForUnqualifiedList;
    }
 
    @Override
    public boolean removeByIdForReport(Long id) {
        // 删除零件时,对检测报告状态进行判断,如果是未检测,删除后全部检测完毕,则将状态改为已检测
        ApplyPart applyPart = baseMapper.selectById(id);//传的是检测汇报明细id
 
        if(isApplyReportIsSubmit(applyPart.getReportId())){
            throw new RuntimeException("检测汇报已提交,冻结删除操作!");
        }
 
        Report report = reportMapper.selectById(applyPart.getReportId());
 
        applyPart.setIsQualified(null);//复位检测结果
        applyPart.setQtyArrived((new BigDecimal(applyPart.getQtyArrived()).add(new BigDecimal(applyPart.getUnqualifiedArrived()))).toString());
        applyPart.setUnqualifiedArrived("0");
        baseMapper.updateById(applyPart);
        boolean result = SqlHelper.retBool(baseMapper.deleteByIdForReport(id));
        changeCheckState(applyPart);
        //更新检测结果为待检测
        changeStatus(applyPart.getSystemNo(), ResultStateStringValues.UNTESTED, applyPart.getIsQualified(), report.getReportType());
        return result;
    }
 
    /**
     * 根据检测汇报id判断检测汇报是否已提交
     * @param reportId 检测汇报id
     * @return true:已提交;false:未提交
     */
    private boolean isApplyReportIsSubmit(Long reportId){
        Report report = reportMapper.selectById(reportId);
        if(report == null){
            throw new RuntimeException("检测汇报状态获取失败!");
        }else{
            if(report.getIsSubmit() == null || !report.getIsSubmit()){
                return false;//检测汇报未提交
            }else{
                return true;//检测汇报已提交
            }
        }
    }
 
    @Override
    public boolean isApplyReportIsSubmitByApplyPartId(Long id){
        ApplyPart applyPart = baseMapper.selectById(id);
        Report report = reportMapper.selectById(applyPart.getReportId());
        if(report == null){
            return false;//没有检测汇报
        }else{
            if(report.getIsSubmit() == null || !report.getIsSubmit()){
                return false;//检测汇报未提交
            }else{
                return true;//检测汇报已提交
            }
        }
    }
 
    @Override
    public ApplyPartDTO getApplyPartDtoById(Long id) {
        ApplyPartDTO applyPartDTO = baseMapper.getApplyPartDtoById(id);
        applyPartDTO.setTestStandardList(baseMapper.findTestStandardNoBySystemNo(applyPartDTO.getSystemNo()));
        List<ApplyPartFile> applyPartFiles = this.applyPartFileMapper.selectList(Wrappers.<ApplyPartFile>lambdaQuery().eq(ApplyPartFile::getApplyPartId, id));
        applyPartDTO.setApplyPartFileList(applyPartFiles);
        List<ReportSample> reportSamples = reportSampleMapper.selectList(Wrappers.<ReportSample>lambdaQuery().eq(ReportSample::getReportId, applyPartDTO.getReportId()));
        applyPartDTO.setReportSampleList(reportSamples);
        if (applyPartDTO.getProduceTime() == null) {
            applyPartDTO.setIsNotOutCheck(true);
        }
        return applyPartDTO;
    }
 
    @Override
    public List<TestStandard> findTestStandardNoBySystemNo(String systemNo) {
        return baseMapper.findTestStandardNoBySystemNo(systemNo);
    }
 
    @Override
    public boolean synchronizationErpStock(List<ApplyPart> applyPartList) {
        List<JSONObject> stockList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(applyPartList)) {
            Set<Long> idList = applyPartList.stream().filter(o -> o.getIsErp() && o.getIsQualified() == null && Double.parseDouble(o.getQtyArrived()) > 0).map(o -> o.getId()).collect(Collectors.toSet());
            //合格数量大于0
            if (CollectionUtil.isNotEmpty(idList)) {
                stockList = baseMapper.selectApplyPart(idList, remoteParamService.getByKey("QUALIFIED_LIBRARY", SecurityConstants.FROM_IN).getData());
                //erp移库
                synchronizationErp(stockList);
            }
            //不合格数量大于0
            Set<Long> list = applyPartList.stream().filter(o -> o.getIsErp() && o.getIsQualified() == null && Double.parseDouble(o.getUnqualifiedArrived()) > 0).map(o -> o.getId()).collect(Collectors.toSet());
            if (CollectionUtil.isNotEmpty(list)) {
                stockList = baseMapper.selectUnApplyPart(list, remoteParamService.getByKey("UNQUALIFIED_LIBRARY", SecurityConstants.FROM_IN).getData());
                synchronizationErp(stockList);
            }
        }
        return true;
    }
 
    @Override
    public boolean saveApply(List<ApplyPart> applyPartList) {
        applyPartList.stream().forEach(applyPart -> {
            // 添加申请零件
            applyPart.setIsErp(true);
            applyPart.setSystemNo(applyPart.getOrderNo() + "-" + applyPart.getLineNo() + "-" + applyPart.getReleaseNo() + "-" + applyPart.getReceiptNo());
            baseMapper.insert(applyPart);
        });
        return true;
    }
 
    /**
     * 校验是否首检、是否合格
     *
     * @param systemNo 改造(22-09-13)-交班产出在工作台那边,不会创建首检,但是会创建尾检,导致尾检与首检的系统编号不一致,统一改成通过批次号去判断
     * @param batchNo 产出批次号
     * @return
     */
    private boolean isFirstApplyGood(String batchNo) {
        // 获取产出首检结果
        Result result = resultMapper.selectOne(Wrappers.<Result>lambdaQuery().eq(Result::getApplyType,
                Apply.FIRST_APPLY).eq(Result::getPartBatchNo, batchNo));
        if (null == result) {
            return Boolean.FALSE;
        }
        if (BooleanUtil.isTrue(result.getIsQualified())) {
            return Boolean.TRUE;
        }
        // 产出首检为不合格,查询不合格处理,如果是让步放行,返回true,否则返回false
        List<UnqualifiedProcess> unqualifiedProcessList = unqualifiedProcessMapper.selectByQualityResultId(result.getId());
        if (CollectionUtil.isEmpty(unqualifiedProcessList)) {
            return Boolean.FALSE;
        }
        return (org.apache.commons.lang3.StringUtils.equals(UnqualifiedprocessStateStringValues.PROCESS_MODE_ALLOW,
                unqualifiedProcessList.get(0).getProcessMode()) && org.apache.commons.lang3.StringUtils.equals(unqualifiedProcessList.get(0).getState(),
                UnqualifiedprocessStateStringValues.EXECUTED));
    }
 
    @Override
    public R batchUpdateApplyPart(List<ApplyPart> applyPartList, Long type) {
        StringBuffer tipMsg = new StringBuffer();
        List<ApplyPart> arrayList = new ArrayList();
        if (CollectionUtil.isNotEmpty(applyPartList)) {
            Report report = reportMapper.selectById(applyPartList.get(0).getReportId());
            if(null != report){
                if(null != report.getIsSubmit() && report.getIsSubmit()){
                    throw new RuntimeException("检测汇报已提交 -> 冻结该操作");
                }
            }
            Set<Long> idList = applyPartList.stream().map(o -> o.getId()).collect(Collectors.toSet());//获取检测汇报零件行id
            if (CollectionUtil.isNotEmpty(idList)) {
                List<ApplyPart> newApplyPartList = baseMapper.selectList(Wrappers.<ApplyPart>lambdaQuery().in(ApplyPart::getId, idList));//通过行id查quality_apply_part
                if (CollectionUtil.isNotEmpty(newApplyPartList)) {
 
                    //遍历newApplyPartList,判断检测结果都为null是否成立,不成立则中断修改检测结果业务(不支持反复修改检测结果)
                    // for(int i = 0;i < newApplyPartList.size();i++){
                    //     if(newApplyPartList.get(i).getIsQualified() != null){
                    //         return R.failed("提交列表中存在已检测数据");
                    //     }
                    // }
 
                    arrayList = newApplyPartList.stream().filter(o -> o.getIsErp() && o.getIsQualified() == null).collect(Collectors.toList());//过滤:是erp库存,且检测结果值为null
                }
                //同步erp
                if (type == ONE) {
                    //更新检测汇报明细时不进行ifs移库(统一在检测汇报提交时进行)
                    //moveStock(newApplyPartList);
                }
            }
            // 成品检list
            List<ApplyPartDTO> finishApplyPartList = new ArrayList<>();
 
            applyPartList.stream().forEach(applyPart -> {
 
                if (type == ONE) {
                    ApplyPart oldApplyPart = baseMapper.selectById(applyPart.getId());
                    //若是判定为合格,则合格数量为合格数量+不合格数量,不合格数量为0
                    if (applyPart.getIsQualified()) {
                        //这里根据检测结果强制更新了合格数据,如果判定结果为合格,则不合格数量必定为0
                        applyPart.setQtyArrived((new BigDecimal(oldApplyPart.getQtyArrived()).add(new BigDecimal(oldApplyPart.getUnqualifiedArrived()))).toString());
                        applyPart.setUnqualifiedArrived("0");
                    }
                    applyPart.setCheckLength(new BigDecimal(applyPart.getQtyArrived()).add(new BigDecimal(applyPart.getUnqualifiedArrived())));
                    baseMapper.updateById(applyPart);
 
                    String applyType = baseMapper.selectApplyTypeByApplyPartId(applyPart.getId());
 
                    //如果所有材料都进行了检测,将检测汇报状态改为已检测
                    changeCheckState(oldApplyPart);//这个方法更新的只是检测字段check_state的状态值
 
                    //1.如果是标记结果合格不合格,把检测结果状态打成已检测
                    changeStatus(applyPart.getSystemNo(), ResultStateStringValues.TESTED, applyPart.getIsQualified(), applyType);
 
                    //1.1如果是产出报检,需要进行移库操作
                    //if (StringUtils.isNotBlank(applyType) && Apply.OUTPUT_APPLY.equals(applyType)) { //01output:产出尾检
                    if (false) { //更新检测汇报明细时不进行移库(统一在检测汇报提交时进行)
                        // 判断一下,第一次质检才自动移库,后面修改检测结果,不进行移库
                        if (oldApplyPart.getIsQualified() == null) {
                            //校验是否首检、是否合格
                            if (!isFirstApplyGood(applyPart.getLotBatchNo())) {
                                tipMsg.append("系统编号:" + applyPart.getSystemNo() + " SN号:" + applyPart.getLotBatchNo()
                                        + " 首检未做或首检不合格,请确认!\r\n");
                                return;
                            }
 
                            // 存在工序且为最后一道工序,并且合格时,仅生成成品检验,不移库
                            if (null != oldApplyPart.getOperationId() && applyPart.getIsQualified() && baseMapper
                                    .isLastOperationBySystemNo(applyPart.getSystemNo())) {
                                ApplyPartDTO partDTO = new ApplyPartDTO();
                                partDTO.setOutBatchNo(oldApplyPart.getLotBatchNo());
                                partDTO.setPartId(oldApplyPart.getPartId());
                                partDTO.setSystemNo(oldApplyPart.getSystemNo());
                                partDTO.setPartName(oldApplyPart.getPartDesc());
                                partDTO.setPartNo(oldApplyPart.getPartNo());
                                finishApplyPartList.add(partDTO);
                                // 移库
                            } else {
                                autoMoveStock(applyPart,"抛异常", false);
                            }
                        }
                        // 成品检移库
                    //} else if (StringUtils.isNotBlank(applyType) && Apply.PRODUCT_APPLY.equals(applyType)) {
                      } else if (false) {//更新检测汇报明细时不进行移库(统一在检测汇报提交时进行)
                        // 判断一下,第一次质检才自动移库,后面修改检测结果,不进行移库
                        if (oldApplyPart.getIsQualified() == null) {
                            autoMoveStock(applyPart,"抛异常", false);
                        }
                    }
                    //1.2如果是库存报检,不需要进行移库操作
                } else if (type == TWO) {
                    ApplyPart oldApplyPart = baseMapper.selectById(applyPart.getId());
                    baseMapper.updateById(applyPart);
                    String applyType = baseMapper.selectApplyTypeByApplyPartId(applyPart.getId());
                    //2.如果是绑定汇报,把检测结果状态打成检测中
                    changeStatus(applyPart.getSystemNo(), ResultStateStringValues.TESTING, null, applyType);
                    //新增报检后,需要将检测汇报状态改为未检测
                    changeCheckState(applyPart);
                    //如果不存在汇报样品则自动创建一条汇报样品
                    List<ReportSample> reportSampleList = reportSampleMapper.selectList(Wrappers.<ReportSample>lambdaQuery().eq(ReportSample::getReportId,applyPart.getReportId()));
                    if(CollectionUtils.isEmpty(reportSampleList)){
                        ReportSample reportSample = new ReportSample();
                        reportSample.setReportId(applyPart.getReportId());
                        reportSample.setSystemNo(applyPart.getSystemNo());
                        reportSample.setTestStandardNo(applyPart.getTestStandardNo());
                        reportSample.setTestStandardId(applyPart.getMoTestStandardId());
                        reportSample.setIsMoTestStandard(true);
                        reportSampleList.add(reportSample);
                        reportSampleService.saveBatchList(reportSampleList);
                    }
 
                } else {
                    ApplyPart oldApplyPart = baseMapper.selectById(applyPart.getId());
                    baseMapper.updateById(applyPart);
                    String applyType = baseMapper.selectApplyTypeByApplyPartId(applyPart.getId());
                }
            });
 
            // 生成成品检 (成品检测自动创建统一在检测汇报提交时创建)
//            if (!finishApplyPartList.isEmpty()) {
//                ApplyDTO applyDTO = new ApplyDTO();
//                applyDTO.setApplyPartList(finishApplyPartList);
//                applyDTO.setApplyType(Apply.PRODUCT_APPLY);
//                applyService.saveDto(applyDTO);
//            }
        }
        return R.ok(arrayList, tipMsg.toString());
    }
 
    @Override
    public R batchUpdateApplyPartV2(List<ApplyPart> applyPartList, Long type) {
        StringBuffer tipMsg = new StringBuffer();
        List<ApplyPart> arrayList = new ArrayList();
        if (CollectionUtil.isNotEmpty(applyPartList)) {
            Report report = reportMapper.selectById(applyPartList.get(0).getReportId());
            if(null != report){
                if(null != report.getIsSubmit() && report.getIsSubmit()){
                    throw new RuntimeException("检测汇报已提交 -> 冻结该操作");
                }
            }
            Set<Long> idList = applyPartList.stream().map(o -> o.getId()).collect(Collectors.toSet());//获取检测汇报零件行id
            if (CollectionUtil.isNotEmpty(idList)) {
                List<ApplyPart> newApplyPartList = baseMapper.selectList(Wrappers.<ApplyPart>lambdaQuery().in(ApplyPart::getId, idList));//通过行id查quality_apply_part
                if (CollectionUtil.isNotEmpty(newApplyPartList)) {
 
                    //遍历newApplyPartList,判断检测结果都为null是否成立,不成立则中断修改检测结果业务(不支持反复修改检测结果)
                    // for(int i = 0;i < newApplyPartList.size();i++){
                    //     if(newApplyPartList.get(i).getIsQualified() != null){
                    //         return R.failed("提交列表中存在已检测数据");
                    //     }
                    // }
 
                    arrayList = newApplyPartList.stream().filter(o -> o.getIsErp() && o.getIsQualified() == null).collect(Collectors.toList());//过滤:是erp库存,且检测结果值为null
                }
                //同步erp
                if (type == ONE) {
                    //更新检测汇报明细时不进行ifs移库(统一在检测汇报提交时进行)
                    //moveStock(newApplyPartList);
                }
            }
            // 成品检list
            List<ApplyPartDTO> finishApplyPartList = new ArrayList<>();
 
            applyPartList.stream().forEach(applyPart -> {
 
                if (type == ONE) {
                    ApplyPart oldApplyPart = baseMapper.selectById(applyPart.getId());
                    //若是判定为合格,则合格数量为合格数量+不合格数量,不合格数量为0
                    if (oldApplyPart.getCheckLength() == null) {
                        throw new RuntimeException("检测长度不能为空,请先保存检测数据");
                    }
 
                    if ((applyPart.getTargetQualifiedLocationId() != null && applyPart.getTargetQualifiedLocationId().equals(oldApplyPart.getSourceLocationId())) ||
                            (applyPart.getTargetUnqualifiedLocationId() != null && applyPart.getTargetUnqualifiedLocationId().equals(oldApplyPart.getSourceLocationId()))) {
                        throw new RuntimeException("目标库位不能与源库位相同");
                    }
 
                    if (applyPart.getIsQualified()) {
                        //这里根据检测结果强制更新了合格数据,如果判定结果为合格,则不合格数量必定为0
                        applyPart.setQtyArrived(oldApplyPart.getCheckLength().stripTrailingZeros().toPlainString());
                        applyPart.setUnqualifiedArrived("0");
                    } else {
                        //这里根据检测结果强制更新了不合格数据,如果判定结果为不合格,则合格数量必定为0
                        applyPart.setQtyArrived("0");
                        applyPart.setUnqualifiedArrived(oldApplyPart.getCheckLength().stripTrailingZeros().toPlainString());
                    }
 
                    baseMapper.updateById(applyPart);
 
                    String applyType = baseMapper.selectApplyTypeByApplyPartId(applyPart.getId());
 
                    //如果所有材料都进行了检测,将检测汇报状态改为已检测
                    changeCheckState(oldApplyPart);//这个方法更新的只是检测字段check_state的状态值
 
                    //1.如果是标记结果合格不合格,把检测结果状态打成已检测
                    changeStatus(applyPart.getSystemNo(), ResultStateStringValues.TESTED, applyPart.getIsQualified(), applyType);
 
                    //1.1如果是产出报检,需要进行移库操作
                    //if (StringUtils.isNotBlank(applyType) && Apply.OUTPUT_APPLY.equals(applyType)) { //01output:产出尾检
                    if (false) { //更新检测汇报明细时不进行移库(统一在检测汇报提交时进行)
                        // 判断一下,第一次质检才自动移库,后面修改检测结果,不进行移库
                        if (oldApplyPart.getIsQualified() == null) {
                            //校验是否首检、是否合格
                            if (!isFirstApplyGood(applyPart.getLotBatchNo())) {
                                tipMsg.append("系统编号:" + applyPart.getSystemNo() + " SN号:" + applyPart.getLotBatchNo()
                                        + " 首检未做或首检不合格,请确认!\r\n");
                                return;
                            }
 
                            // 存在工序且为最后一道工序,并且合格时,仅生成成品检验,不移库
                            if (null != oldApplyPart.getOperationId() && applyPart.getIsQualified() && baseMapper
                                    .isLastOperationBySystemNo(applyPart.getSystemNo())) {
                                ApplyPartDTO partDTO = new ApplyPartDTO();
                                partDTO.setOutBatchNo(oldApplyPart.getLotBatchNo());
                                partDTO.setPartId(oldApplyPart.getPartId());
                                partDTO.setSystemNo(oldApplyPart.getSystemNo());
                                partDTO.setPartName(oldApplyPart.getPartDesc());
                                partDTO.setPartNo(oldApplyPart.getPartNo());
                                finishApplyPartList.add(partDTO);
                                // 移库
                            } else {
                                autoMoveStock(applyPart,"抛异常", false);
                            }
                        }
                        // 成品检移库
                        //} else if (StringUtils.isNotBlank(applyType) && Apply.PRODUCT_APPLY.equals(applyType)) {
                    } else if (false) {//更新检测汇报明细时不进行移库(统一在检测汇报提交时进行)
                        // 判断一下,第一次质检才自动移库,后面修改检测结果,不进行移库
                        if (oldApplyPart.getIsQualified() == null) {
                            autoMoveStock(applyPart,"抛异常", false);
                        }
                    }
                    //1.2如果是库存报检,不需要进行移库操作
                } else if (type == TWO) {
                    ApplyPart oldApplyPart = baseMapper.selectById(applyPart.getId());
                    baseMapper.updateById(applyPart);
                    String applyType = baseMapper.selectApplyTypeByApplyPartId(applyPart.getId());
                    //2.如果是绑定汇报,把检测结果状态打成检测中
                    changeStatus(applyPart.getSystemNo(), ResultStateStringValues.TESTING, null, applyType);
                    //新增报检后,需要将检测汇报状态改为未检测
                    changeCheckState(applyPart);
                    //如果不存在汇报样品则自动创建一条汇报样品
                    List<ReportSample> reportSampleList = reportSampleMapper.selectList(Wrappers.<ReportSample>lambdaQuery().eq(ReportSample::getReportId,applyPart.getReportId()));
                    if(CollectionUtils.isEmpty(reportSampleList)){
                        ReportSample reportSample = new ReportSample();
                        reportSample.setReportId(applyPart.getReportId());
                        reportSample.setSystemNo(applyPart.getSystemNo());
                        reportSample.setTestStandardNo(applyPart.getTestStandardNo());
                        reportSample.setTestStandardId(applyPart.getMoTestStandardId());
                        reportSample.setIsMoTestStandard(true);
                        reportSampleList.add(reportSample);
                        reportSampleService.saveBatchList(reportSampleList);
                    }
 
                } else {
                    ApplyPart oldApplyPart = baseMapper.selectById(applyPart.getId());
                    if (oldApplyPart.getTotalLength() == null) {
                        JSONObject showInfo = applyPartMapper.selectShowInfoBySystemNo(oldApplyPart.getSystemNo());
                        oldApplyPart.setTotalLength(showInfo.getBigDecimal("product_qty"));
                        applyPart.setTotalLength(showInfo.getBigDecimal("product_qty"));
                    }
                    if (applyPart.getCheckLength() == null) {
                        throw new RuntimeException("系统编号:" + applyPart.getSystemNo() + " SN号:" + applyPart.getLotBatchNo()
                                + " 入库长度不能为空,请确认!");
                    }
                    if (applyPart.getCheckLength().compareTo(oldApplyPart.getTotalLength()) > 0 || applyPart.getCheckLength().compareTo(BigDecimal.ZERO) < 0) {
                        throw new RuntimeException("系统编号:" + applyPart.getSystemNo() + " SN号:" + applyPart.getLotBatchNo()
                                + " 入库长度不能大于总长度或小于等于0,请确认!");
                    }
 
                    if ((applyPart.getTargetQualifiedLocationId() != null && applyPart.getTargetQualifiedLocationId().equals(oldApplyPart.getSourceLocationId())) ||
                            (applyPart.getTargetUnqualifiedLocationId() != null && applyPart.getTargetUnqualifiedLocationId().equals(oldApplyPart.getSourceLocationId()))) {
                        throw new RuntimeException("目标库位不能与源库位相同");
                    }
 
                    applyPart.setScrapArrived(oldApplyPart.getTotalLength().subtract(applyPart.getCheckLength()));
 
                    if (applyPart.getReplacePartId() == null) {
                        baseMapper.removeReplacePart(applyPart.getId());
                    } else {
                        if (StringUtils.isBlank(applyPart.getReplacePartNo()) || StringUtils.isBlank(applyPart.getReplacePartName())) {
                            throw new RuntimeException("系统编号:" + applyPart.getSystemNo() + " SN号:" + applyPart.getLotBatchNo()
                                    + " 替换零件信息不能为空,请确认!");
                        }
                    }
 
                    if (oldApplyPart.getIsQualified() != null) {
                        if (oldApplyPart.getIsQualified()) {
                            applyPart.setQtyArrived(applyPart.getCheckLength().stripTrailingZeros().toPlainString());
                            applyPart.setUnqualifiedArrived("0");
                        } else {
                            applyPart.setQtyArrived("0");
                            applyPart.setUnqualifiedArrived(applyPart.getCheckLength().stripTrailingZeros().toPlainString());
                        }
                    }
                    baseMapper.updateById(applyPart);
                }
            });
        }
        return R.ok(arrayList, tipMsg.toString());
    }
 
    /**
     * 根据产出系统唯一编号移库
     *
     * @param systemNo           系统编号
     * @param lotBatchNo         零件批号
     * @param qtyArrived         合格数量
     * @param unqualifiedArrived 不合格数量
     */
    private void autoMoveStock(ApplyPart applyPart,String dir,Boolean isNeedFinishApply) {
        //根据系统唯一编号查出零件id
        Long partId = baseMapper.selectPartIdBySystemNo(applyPart.getSystemNo());
        if (partId == null) {
            //return;//这里不应该return
            throw new RuntimeException("移库对象零件查无零件基础数据!");
        }
        //根据产出系统唯一编号查出对应工作站的库位
        Long inspectionLocationId = workstationLocationMapper.selectBySystemNo(applyPart.getSystemNo(), WorkstationLocation.INSPECTION_LOCATION);//产出待检库位
        Long disqualifiedLocationId = workstationLocationMapper.selectBySystemNo(applyPart.getSystemNo(), WorkstationLocation.DISQUALIFIED_LOCATION);//产出不合格品库位
//        Long qualifiedLocationId = workstationLocationMapper.selectBySystemNo(systemNo, WorkstationLocation.QUALIFIED_LOCATION);
        // 如果配置了成品待检库位,则移入成品待检库
        Long qualifiedLocationId = workstationLocationMapper.selectFinishToQualifiedLocationIdBySystemNo(applyPart.getSystemNo());
        // 存在源库位,则取源库位
        if (applyPart.getSourceLocationId() != null) {
            inspectionLocationId = applyPart.getSourceLocationId();
            disqualifiedLocationId = applyPart.getTargetUnqualifiedLocationId() == null ? -1 : applyPart.getTargetUnqualifiedLocationId();
            qualifiedLocationId = applyPart.getTargetQualifiedLocationId() == null ? -1 : applyPart.getTargetQualifiedLocationId();
        } else {
            if (!isNeedFinishApply) {
                // 合格库位取工单中库位
                qualifiedLocationId = workstationLocationMapper.selectQualifiedLocationIdBySystemNo(applyPart.getSystemNo());//合格品库位
            } else {
                if (qualifiedLocationId == null) {
                    throw new RuntimeException("成品待检库位未配置!");
                }
            }
        }
 
        if (inspectionLocationId != null && disqualifiedLocationId != null && qualifiedLocationId != null) {
            if(dir.equals(MOVELIBRARY)){
                // 待检移合格
                if (new BigDecimal(applyPart.getQtyArrived()).compareTo(BigDecimal.ZERO) == 1) {
                    // 如果有替代件,则替代件移库
                    if (applyPart.getReplacePartId() != null) {
                        stockUtils.replaceMove(partId, applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getQtyArrived()), inspectionLocationId, qualifiedLocationId, applyPart.getReplacePartId());
                    } else {
                        stockUtils.localMove(partId, applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getQtyArrived()), inspectionLocationId, qualifiedLocationId);
                    }
                }
                // 待检移不合格
                if (new BigDecimal(applyPart.getUnqualifiedArrived()).compareTo(BigDecimal.ZERO) == 1) {
                    if (applyPart.getReplacePartId() != null) {
                        stockUtils.replaceMove(partId, applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getUnqualifiedArrived()), inspectionLocationId, disqualifiedLocationId, applyPart.getReplacePartId());
                    } else {
                        stockUtils.localMove(partId, applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getUnqualifiedArrived()), inspectionLocationId, disqualifiedLocationId);
                    }
                }
                // 报废库存发放
                if (applyPart.getScrapArrived() != null && applyPart.getScrapArrived().compareTo(BigDecimal.ZERO) > 0) {
                    Stock stock = stockMapper.selectOne(Wrappers.<Stock>lambdaQuery().eq(Stock::getPartId, partId)
                            .eq(Stock::getLocationId,inspectionLocationId)
                            .eq(Stock::getPartBatchNo,applyPart.getLotBatchNo())
                            .eq(Stock::getSystemNo,applyPart.getSystemNo()));
                    stockUtils.updateById(stock.getId(), applyPart.getScrapArrived().negate(), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, null, TransactionType.SCRAP.getValue());
                }
            }else if(dir.equals(UNMOVELIBRARY)){
                // 合格移待检
                if (new BigDecimal(applyPart.getQtyArrived()).compareTo(BigDecimal.ZERO) == 1) {
                    if (applyPart.getReplacePartId() != null) {
                        stockUtils.replaceMove(applyPart.getReplacePartId(), applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getQtyArrived()), qualifiedLocationId, inspectionLocationId, partId);
                    } else {
                        stockUtils.localMove(partId, applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getQtyArrived()), qualifiedLocationId, inspectionLocationId);
                    }
                }
                // 不合格移待检
                if (new BigDecimal(applyPart.getUnqualifiedArrived()).compareTo(BigDecimal.ZERO) == 1) {
                    if (applyPart.getReplacePartId() != null) {
                        stockUtils.replaceMove(applyPart.getReplacePartId(), applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getUnqualifiedArrived()), disqualifiedLocationId, inspectionLocationId, partId);
                    } else {
                        stockUtils.localMove(partId, applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getUnqualifiedArrived()), disqualifiedLocationId, inspectionLocationId);
                    }
                }
                // 报废库存撤回
                if (applyPart.getScrapArrived() != null && applyPart.getScrapArrived().compareTo(BigDecimal.ZERO) > 0) {
                    Stock stock = stockMapper.selectOne(Wrappers.<Stock>lambdaQuery().eq(Stock::getPartId, partId)
                            .eq(Stock::getLocationId,inspectionLocationId)
                            .eq(Stock::getPartBatchNo,applyPart.getLotBatchNo())
                            .eq(Stock::getSystemNo,applyPart.getSystemNo()));
                    stockUtils.updateById(stock.getId(), applyPart.getScrapArrived() , BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, null, TransactionType.CANCEL_SCRAP.getValue());
                }
            }else{
                throw new RuntimeException("移库方向码异常!异常码--" + dir);
            }
        }else{
            throw new RuntimeException("移库库位信息获取不全->产出待检库位id=" + inspectionLocationId + "->产出不合格品库位id=" + disqualifiedLocationId + "->产出合格库位id=" + qualifiedLocationId);
        }
    }
 
    private void autoMoveStockV2(ApplyPart applyPart,String dir,Boolean isNeedFinishApply) {
        //根据系统唯一编号查出零件id
        Long partId = applyPart.getPartId();
        if (partId == null) {
            //return;//这里不应该return
            throw new RuntimeException("移库对象零件查无零件基础数据!");
        }
        //根据产出系统唯一编号查出对应工作站的库位
        Long inspectionLocationId = workstationLocationMapper.selectBySystemNo(applyPart.getSystemNo(), WorkstationLocation.INSPECTION_LOCATION);//产出待检库位
        Long disqualifiedLocationId = workstationLocationMapper.selectBySystemNo(applyPart.getSystemNo(), WorkstationLocation.DISQUALIFIED_LOCATION);//产出不合格品库位
//        Long qualifiedLocationId = workstationLocationMapper.selectBySystemNo(systemNo, WorkstationLocation.QUALIFIED_LOCATION);
        // 如果配置了成品待检库位,则移入成品待检库
        Long qualifiedLocationId = workstationLocationMapper.selectFinishToQualifiedLocationIdBySystemNo(applyPart.getSystemNo());
        // 存在源库位,则取源库位
        if (applyPart.getSourceLocationId() != null) {
            inspectionLocationId = applyPart.getSourceLocationId();
            disqualifiedLocationId = applyPart.getTargetUnqualifiedLocationId() == null ? -1 : applyPart.getTargetUnqualifiedLocationId();
            qualifiedLocationId = applyPart.getTargetQualifiedLocationId() == null ? -1 : applyPart.getTargetQualifiedLocationId();
        } else {
            if (!isNeedFinishApply) {
                // 合格库位取工单中库位
                qualifiedLocationId = workstationLocationMapper.selectQualifiedLocationIdBySystemNo(applyPart.getSystemNo());//合格品库位
            } else {
                if (qualifiedLocationId == null) {
                    throw new RuntimeException("成品待检库位未配置!");
                }
            }
        }
 
        if (inspectionLocationId != null && disqualifiedLocationId != null && qualifiedLocationId != null) {
            if(dir.equals(MOVELIBRARY)){
                // 待检移合格
                if (new BigDecimal(applyPart.getQtyArrived()).compareTo(BigDecimal.ZERO) == 1) {
                    // 如果有替代件,则替代件移库
                    if (applyPart.getReplacePartId() != null) {
                        stockUtils.replaceMove(partId, applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getQtyArrived()), inspectionLocationId, qualifiedLocationId, applyPart.getReplacePartId());
                    } else {
                        stockUtils.localMove(partId, applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getQtyArrived()), inspectionLocationId, qualifiedLocationId);
                    }
                }
                // 待检移不合格
                if (new BigDecimal(applyPart.getUnqualifiedArrived()).compareTo(BigDecimal.ZERO) == 1) {
                    if (applyPart.getReplacePartId() != null) {
                        stockUtils.replaceMove(partId, applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getUnqualifiedArrived()), inspectionLocationId, disqualifiedLocationId, applyPart.getReplacePartId());
                    } else {
                        stockUtils.localMove(partId, applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getUnqualifiedArrived()), inspectionLocationId, disqualifiedLocationId);
                    }
                }
                // 报废库存发放
                if (applyPart.getScrapArrived() != null && applyPart.getScrapArrived().compareTo(BigDecimal.ZERO) > 0) {
                    Stock stock = stockMapper.selectOne(Wrappers.<Stock>lambdaQuery().eq(Stock::getPartId, partId)
                            .eq(Stock::getLocationId,inspectionLocationId)
                            .eq(Stock::getPartBatchNo,applyPart.getLotBatchNo())
                            .eq(Stock::getSystemNo,applyPart.getSystemNo()));
                    stockUtils.updateById(stock.getId(), applyPart.getScrapArrived().negate(), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, null, TransactionType.SCRAP.getValue());
                }
            }else if(dir.equals(UNMOVELIBRARY)){
                // 合格移待检
                if (new BigDecimal(applyPart.getQtyArrived()).compareTo(BigDecimal.ZERO) == 1) {
                    if (applyPart.getReplacePartId() != null) {
                        stockUtils.replaceMove(applyPart.getReplacePartId(), applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getQtyArrived()), qualifiedLocationId, inspectionLocationId, partId);
                    } else {
                        stockUtils.localMove(partId, applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getQtyArrived()), qualifiedLocationId, inspectionLocationId);
                    }
                }
                // 不合格移待检
                if (new BigDecimal(applyPart.getUnqualifiedArrived()).compareTo(BigDecimal.ZERO) == 1) {
                    if (applyPart.getReplacePartId() != null) {
                        stockUtils.replaceMove(applyPart.getReplacePartId(), applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getUnqualifiedArrived()), disqualifiedLocationId, inspectionLocationId, partId);
                    } else {
                        stockUtils.localMove(partId, applyPart.getSystemNo(), applyPart.getLotBatchNo(), new BigDecimal(applyPart.getUnqualifiedArrived()), disqualifiedLocationId, inspectionLocationId);
                    }
                }
                // 报废库存撤回
                if (applyPart.getScrapArrived() != null && applyPart.getScrapArrived().compareTo(BigDecimal.ZERO) > 0) {
                    Stock stock = stockMapper.selectOne(Wrappers.<Stock>lambdaQuery().eq(Stock::getPartId, partId)
                            .eq(Stock::getLocationId,inspectionLocationId)
                            .eq(Stock::getPartBatchNo,applyPart.getLotBatchNo())
                            .eq(Stock::getSystemNo,applyPart.getSystemNo()));
                    stockUtils.updateById(stock.getId(), applyPart.getScrapArrived() , BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, null, TransactionType.CANCEL_SCRAP.getValue());
                }
            }else{
                throw new RuntimeException("移库方向码异常!异常码--" + dir);
            }
        }else{
            throw new RuntimeException("移库库位信息获取不全->产出待检库位id=" + inspectionLocationId + "->产出不合格品库位id=" + disqualifiedLocationId + "->产出合格库位id=" + qualifiedLocationId);
        }
    }
 
    public void moveStock(List<ApplyPart> applyPartList) {
        List<JSONObject> newStockList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(applyPartList)) {
            //这里再过滤一遍,把是ifs的且没有检测的筛选出来
            Set<Long> newIdList = applyPartList.stream().filter(o -> o.getIsErp() && o.getIsQualified() == null).map(o -> o.getId()).collect(Collectors.toSet());
            if (CollectionUtil.isNotEmpty(newIdList)) {
                newStockList = baseMapper.selectRegistrationApplyPart(newIdList, remoteParamService.getByKey("QUALIFIED_LIBRARY", SecurityConstants.FROM_IN).getData());
                //登记检验结果
                registrationResult(newStockList);//这个是原材料检测,暂时不做
            }
        }
    }
 
    /**
     * erp登记检验结果
     */
    public void registrationResult(List<JSONObject> stockList) {
        String one = "1";
        String data = "data";
        String type = "operationType";
        JSONObject inAttr = new JSONObject();
        String s = UUID.randomUUID().toString();
        inAttr.put("recordId", s);
        inAttr.put("syscode", SYSTEM);
        inAttr.put("sysmodel", NEW_SYSTEM_NAME);
        inAttr.put("batchInfo", stockList);
        JSONObject stockMap = new JSONObject();
        stockMap.put("contract", stockBean.getRegion());
        try {
            System.out.println(stockBean.getSecretKey());
            System.out.println(stockBean.getCleartextSecretKey());
            if (StringUtils.isNotBlank(stockBean.getSecretKey())) {
                stockMap.put("contractKey", stockBean.getSecretKey());
            } else if (StringUtils.isNotBlank(stockBean.getCleartextSecretKey())) {
                stockMap.put("contractKey", AesUtils.encrypt(stockBean.getCleartextSecretKey()));
            }
        } catch (Exception e) {
            throw new RuntimeException("明文密钥加密失败");
        }
        stockMap.put("userId", SecurityUtils.getUser().getUsername());
        stockMap.put("inAttr", inAttr);
        String result = HttpRequest.post(stockBean.getRegistrationResultIp()).body(JSONObject.toJSONString(stockMap)).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!one.equals(jsonObject.getJSONObject(data).getString(type))) {
            throw new RuntimeException(jsonObject.getString("msg"));
        }
    }
 
    /**
     * 同步erp库存
     */
    public void synchronizationErp(List<JSONObject> stockList) {
        String one = "1";
        String data = "data";
        String type = "operationType";
        JSONObject inAttr = new JSONObject();
        String s = UUID.randomUUID().toString();
        inAttr.put("recordId", s);
        inAttr.put("syscode", SYSTEM);
        inAttr.put("sysmodel", SYSTEM_NAME);
        inAttr.put("batchInfo", stockList);
        JSONObject stockMap = new JSONObject();
        stockMap.put("contract", stockBean.getRegion());
        try {
            System.out.println(stockBean.getSecretKey());
            System.out.println(stockBean.getCleartextSecretKey());
            if (StringUtils.isNotBlank(stockBean.getSecretKey())) {
                stockMap.put("contractKey", stockBean.getSecretKey());
            } else if (StringUtils.isNotBlank(stockBean.getCleartextSecretKey())) {
                stockMap.put("contractKey", AesUtils.encrypt(stockBean.getCleartextSecretKey()));
            }
        } catch (Exception e) {
            throw new RuntimeException("明文密钥加密失败");
        }
        stockMap.put("userId", SecurityUtils.getUser().getUsername());
        stockMap.put("inAttr", inAttr);
        System.out.println(stockMap);
        String result = HttpRequest.post(stockBean.getMoveStockIp()).body(JSONObject.toJSONString(stockMap)).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!one.equals(jsonObject.getJSONObject(data).getString(type))) {
            throw new RuntimeException(jsonObject.getString("msg"));
        }
    }
 
    @Override
    public void changeStatus(String systemNo, String checkStatus, Boolean isQualified, String applyType) {
        Result result = resultMapper.selectOne(Wrappers.<Result>query().lambda().eq(Result::getSystemNo, systemNo)
                .eq(Result::getApplyType, applyType).eq(Result::getIsErp, false));
        if (result != null) {
            //if (isQualified != null) {
                result.setIsQualified(isQualified);
                result.setIsUsed(isQualified);
            //}
            result.setCheckStatus(checkStatus);
            resultMapper.updateById(result);
        }
    }
 
    /**
     * 如果所有材料都进行了检测,将检测汇报状态改为已检测,否则为未检测
     *
     * @param applyPart
     */
    @Override
    public void changeCheckState(ApplyPart applyPart) {
        Report report = reportService.getById(applyPart.getReportId());
        List<ApplyPart> applyParts = baseMapper.selectList(Wrappers.<ApplyPart>lambdaQuery().eq(ApplyPart::getReportId
                , applyPart.getReportId()));
        Report update = new Report();
        update.setId(report.getId());
        update.setReportNo(report.getReportNo());
        update.setCheckTime(LocalDateTime.now());
        if (!applyParts.isEmpty() && applyParts.stream().allMatch(p -> p.getIsQualified() != null)) {
            if (report.getCheckState() == null || report.getCheckState().equals(Report.CHECK_STATE_UNCHECK)) {
                update.setCheckState(Report.CHECK_STATE_CHECKED);
                reportService.updateById(update);
            }
        } else {
            if (report.getCheckState() != null && report.getCheckState().equals(Report.CHECK_STATE_CHECKED)) {
                update.setCheckState(Report.CHECK_STATE_UNCHECK);
                reportService.updateById(update);
            }
        }
    }
 
    /**
     * 移库
     * @param reportId 检测汇报id
     * @param dir 操作方向,mv移库;unmv:取消移库
     */
    @Override
    public boolean moveLibrary(Long reportId,String dir){
        // 是否需要成品检处理
        boolean isNeedFinishApply = false;
        Report report = reportMapper.selectById(reportId);
        List<ApplyPart> applyPartList = applyPartMapper.selectListByReportId(reportId);//通过检测汇报id获取检测汇报材料明细
        List<ApplyPart> applyPartList_ifs = new ArrayList<>();//ifs库存件报检
        List<ApplyPart> applyPartList_mes = new ArrayList<>();//mes产出报检
        if(CollectionUtil.isNotEmpty(applyPartList)){
            //将集合进行数据源的分离:mes的产出报检、ifs的库存件报检
            applyPartList_ifs = applyPartList.stream().filter(o -> o.getIsErp() && o.getIsQualified() != null).collect(Collectors.toList());//ifs库存件报检数据(这里的is_erp字段代表的应该是ifs的原材料报检,原材料报检暂时不上)
            applyPartList_mes = applyPartList.stream().filter(o -> !o.getIsErp() && o.getIsQualified() != null).collect(Collectors.toList());//mes产出报检数据
        }
 
        if(CollectionUtil.isNotEmpty(applyPartList_ifs)){
            //对接ifs移库
            if(false){//暂时不开放ifs原材料在mes中报检
                moveLibrary_ifs(applyPartList_ifs,report.getReportNo(),report.getReportType(),dir);
            }
        }
 
        if(CollectionUtil.isNotEmpty(applyPartList_mes)){
            //mes移库
            isNeedFinishApply = moveLibrary_mes(applyPartList_mes, report.getReportType(), dir);
        }
        return isNeedFinishApply;
    }
 
    @Override
    public boolean moveLibraryV2(Long reportId, String dir) {
        // 是否需要成品检处理
        boolean isNeedFinishApply = false;
        Report report = reportMapper.selectById(reportId);
        List<ApplyPart> applyPartList = applyPartMapper.selectListByReportId(reportId);//通过检测汇报id获取检测汇报材料明细
        List<ApplyPart> applyPartList_ifs = new ArrayList<>();//ifs库存件报检
        List<ApplyPart> applyPartList_mes = new ArrayList<>();//mes产出报检
        if(CollectionUtil.isNotEmpty(applyPartList)){
            //将集合进行数据源的分离:mes的产出报检、ifs的库存件报检
            applyPartList_ifs = applyPartList.stream().filter(o -> o.getIsErp() && o.getIsQualified() != null).collect(Collectors.toList());//ifs库存件报检数据(这里的is_erp字段代表的应该是ifs的原材料报检,原材料报检暂时不上)
            applyPartList_mes = applyPartList.stream().filter(o -> !o.getIsErp() && o.getIsQualified() != null).collect(Collectors.toList());//mes产出报检数据
        }
 
        if(CollectionUtil.isNotEmpty(applyPartList_ifs)){
            //对接ifs移库
            if(false){//暂时不开放ifs原材料在mes中报检
                moveLibrary_ifs(applyPartList_ifs,report.getReportNo(),report.getReportType(),dir);
            }
        }
 
        if(CollectionUtil.isNotEmpty(applyPartList_mes)){
            //mes移库
            isNeedFinishApply = moveLibrary_mes_v2(applyPartList_mes, report.getReportType(), dir);
        }
        return isNeedFinishApply;
    }
 
    /**
     * ifs移库
     * @param applyPartList
     * @param reportNo 检测汇报编号
     */
    public void moveLibrary_ifs(List<ApplyPart> applyPartList,String reportNo,String reportType,String dir){
        if(StringUtils.isBlank(reportType)){
            throw new RuntimeException("检测汇报类型为空!操作已中断!");
        }
        //拼接inAttr
        //对接库存件移库
        IfsMoveLibraryDTO ifsMoveLibraryDTO = new IfsMoveLibraryDTO();
        ifsMoveLibraryDTO.setRECORD_ID(reportNo);
        List<IfsMoveLibraryDTO.DataBean> dataBeanList = new ArrayList<>();//批量标识
 
        for(int i = 0;i < applyPartList.size();i++){
            if(baseMapper.isLastOperationBySystemNo(applyPartList.get(i).getSystemNo()) && !reportType.equals(Apply.PRODUCT_APPLY)){
                continue;//是最后一道工序,且不是成品检,则跳过
            }
            List<Boolean> operationStockStatus = applyPartMapper.selectStockOperationStatus(applyPartList.get(0).getSystemNo());
            // 如果是工序库存,不进行IFS移库
            if (CollectionUtil.isNotEmpty(operationStockStatus) && BooleanUtil.isTrue(operationStockStatus.get(0))) {
                continue;
            }
            SubmitReportDTO submitReportDTO = reportMapper.getManufacturingOrderInfo(applyPartList.get(i).getId());
 
 
            double qty_qualified = Double.parseDouble(applyPartList.get(i).getQtyArrived());//合格数量
            double qty_unqualified = Double.parseDouble(applyPartList.get(i).getUnqualifiedArrived());//不合格数量
 
            BigDecimal big_qualified = BigDecimal.valueOf(qty_qualified);//合格数量转换数据类型
            BigDecimal big_unqualified = BigDecimal.valueOf(qty_unqualified);//不合格数量转换数据类型
 
            if(big_qualified.compareTo(BigDecimal.ZERO) == 1){
                //合格数量大于0
                IfsMoveLibraryDTO.DataBean batchInfo = new IfsMoveLibraryDTO.DataBean();
                batchInfo.setPART_NO(applyPartList.get(i).getPartNo());//零件号
                batchInfo.setLOT_BATCH_NO(applyPartList.get(i).getLotBatchNo());//批次号
                batchInfo.setMOVE_QTY(Double.parseDouble(applyPartList.get(i).getQtyArrived()));//合格数量
                //------------------------------------------------------------------------------------------------------序列号、版本号、wdr号、ifs原库位号,从ifs库存件获取数据时存储在quality_apply_part表中
                batchInfo.setSERIAL_NO(applyPartList.get(i).getSerialNo());//序列号
                batchInfo.setENG_CHG_LEVEL(applyPartList.get(i).getEngChgLevel());//版本号
                batchInfo.setWAIV_DEV_REJ_NO(applyPartList.get(i).getWaivDevRejNo());//wdr号
                if(dir.equals(MOVELIBRARY)){
                    //移库
                    batchInfo.setLOCATION_NO(applyPartList.get(i).getLocationNo());//ifs原库位号
                    batchInfo.setTO_LOCATION_NO(reportMapper.getIfsLocationArrivedByWorkstationId(submitReportDTO.getWorkstationId(),WorkstationLocation.QUALIFIED_LOCATION));//获取IFS产出合格库位
                }else if(dir.equals(UNMOVELIBRARY)){
                    //取消移库
                    batchInfo.setTO_LOCATION_NO(applyPartList.get(i).getLocationNo());//ifs原库位号
                    batchInfo.setLOCATION_NO(reportMapper.getIfsLocationArrivedByWorkstationId(submitReportDTO.getWorkstationId(),WorkstationLocation.QUALIFIED_LOCATION));//获取IFS产出合格库位
                }else{
                    throw new RuntimeException("移库方向码异常!");
                }
                batchInfo.setTO_CONTRACT(stockBean.getRegion());//目标域
                // 因为现在多个 mes库位可能对应一个 ifs库位 所以 执行移库操作之前需要判断一下库位是否相同
                // xcg 20230413
                if (!StrUtil.equals(batchInfo.getLOCATION_NO(), batchInfo.getTO_LOCATION_NO())) {
                    dataBeanList.add(batchInfo);
                }
            }
 
            if(big_unqualified.compareTo(BigDecimal.ZERO) == 1){
                //不合格数量大于0
                IfsMoveLibraryDTO.DataBean batchInfo = new IfsMoveLibraryDTO.DataBean();
                batchInfo.setPART_NO(applyPartList.get(i).getPartNo());//零件号
                batchInfo.setLOT_BATCH_NO(applyPartList.get(i).getLotBatchNo());//批次号
                batchInfo.setMOVE_QTY(Double.parseDouble(applyPartList.get(i).getUnqualifiedArrived()));//不合格数量
                //------------------------------------------------------------------------------------------------------序列号、版本号、wdr号、ifs原库位号,从ifs库存件获取数据时存储在quality_apply_part表中
                batchInfo.setSERIAL_NO(applyPartList.get(i).getSerialNo());//序列号
                batchInfo.setENG_CHG_LEVEL(applyPartList.get(i).getEngChgLevel());//版本号
                batchInfo.setWAIV_DEV_REJ_NO(applyPartList.get(i).getWaivDevRejNo());//wdr号
                if(dir.equals(MOVELIBRARY)){
                    batchInfo.setLOCATION_NO(applyPartList.get(i).getLocationNo());//ifs原库位号
                    batchInfo.setTO_LOCATION_NO(reportMapper.getIfsLocationArrivedByWorkstationId(submitReportDTO.getWorkstationId(),WorkstationLocation.DISQUALIFIED_LOCATION));//获取IFS产出不合格库位
                }else if(dir.equals(UNMOVELIBRARY)){
                    batchInfo.setTO_LOCATION_NO(applyPartList.get(i).getLocationNo());//ifs原库位号
                    batchInfo.setLOCATION_NO(reportMapper.getIfsLocationArrivedByWorkstationId(submitReportDTO.getWorkstationId(),WorkstationLocation.DISQUALIFIED_LOCATION));//获取IFS产出不合格库位
                }else{
                    throw new RuntimeException("移库方向码异常!异常码--" + dir);
                }
                batchInfo.setTO_CONTRACT(stockBean.getRegion());//目标域
                // 因为现在多个 mes库位可能对应一个 ifs库位 所以 执行移库操作之前需要判断一下库位是否相同
                // xcg 20230413
                if (!StrUtil.equals(batchInfo.getLOCATION_NO(), batchInfo.getTO_LOCATION_NO())) {
                    dataBeanList.add(batchInfo);
                }
            }
        }
        if (CollectionUtil.isEmpty(dataBeanList)) {
            return;
        }
        ifsMoveLibraryDTO.setBATCH_INFO(dataBeanList);
        Gson gson = new Gson();
        String jsonstr = gson.toJson(ifsMoveLibraryDTO);
        JSONObject jsonObject = JSONObject.parseObject(jsonstr);//解决序列化时自动将大写转小写问题
 
        R res = ifsFeignClient.importMovePartStd(jsonObject,true);
        if(res.getCode() != 0){
            throw new RuntimeException("ifs库存件移库失败;erromsg:" + res.getMsg());
        }
    }
 
    /**
     * mes移库
     * @param applyPartList
     */
    public boolean moveLibrary_mes(List<ApplyPart> applyPartList,String reportType,String dir){
        //检测汇报类型为空则中断程序
        if(StringUtils.isBlank(reportType)){
            throw new RuntimeException("检测汇报类型为空!操作已中断!");
        }
 
        List<ApplyPartDTO> finishApplyPartList = new ArrayList<>();//成品检list
 
        // 是否需要成品检处理
        boolean isNeedFinishApply = false;
 
        //不满足已首检&&首检状态为合格,则中断程序
        for(ApplyPart applyPart_cursor:applyPartList){
            //存在首检,且首检结果为合格(整改优化:汇报类型为尾检时才去判断是否存在首检)
            if(reportType.equals(Apply.OUTPUT_APPLY)){
                if(!isFirstApplyGood(applyPart_cursor.getLotBatchNo())){
                    throw new RuntimeException("系统编号--" + applyPart_cursor.getSystemNo() + "|SN号--" + applyPart_cursor.getLotBatchNo() + "--首检未做或首检不合格!操作已中断!");
                }
            }
 
            //批次首检不参与移库&&自动创建成品检
//            if(!reportType.equals(Apply.BATCHFIRST_APPLY)){
                //若工序为最后一道工序&&检测结果为合格&&汇报类型不是成品检,则自动生成成品检(该规则作废)
                //若工序为最后一道工序&&检测结果为合格&&汇报类型是非批次首检,则自动生成成品检(该规则作废)
                //(若工序为尾检或者工序检)&&检测结果为合格
                //if((reportType.equals(Apply.OUTPUT_APPLY) || reportType.equals(Apply.PROCESS_APPLY)) && applyPart_cursor.getOperationId() != null && applyPart_cursor.getIsQualified() && baseMapper.isLastOperationBySystemNo(applyPart_cursor.getSystemNo())){
                if((reportType.equals(Apply.OUTPUT_APPLY) || reportType.equals(Apply.PROCESS_APPLY)) && applyPart_cursor.getOperationId() != null && applyPart_cursor.getIsQualified()){
                    if(dir.equals(MOVELIBRARY)){
                        //判断检测申请规则是否配置了成品检
                        String ruleApply = remoteParamService.getByKey(Apply.RULE_APPLY, SecurityConstants.FROM_IN).getData();
                        ApplyPartDTO applyPartDTO = new ApplyPartDTO();
                        applyPartDTO.setOutBatchNo(applyPart_cursor.getLotBatchNo());
                        applyPartDTO.setPartId(applyPart_cursor.getPartId());
                        applyPartDTO.setSystemNo(applyPart_cursor.getSystemNo());
                        applyPartDTO.setPartName(applyPart_cursor.getPartDesc());
                        applyPartDTO.setPartNo(applyPart_cursor.getPartNo());
                        if(ruleApply.equals("true") && baseMapper.isExistTestApplyConfigBySystemNo(applyPart_cursor.getSystemNo())){
                            //存在成品检检测申请配置
                            if(baseMapper.isConfigFinishedProdTest(applyPart_cursor.getSystemNo())){
                                //校验一下配置规则 (2023-02-24 配置规则不再使用,从车间订单配置中获取)
                                // String operationNo = baseMapper.selectOperationNoBySystemNo(applyPart_cursor.getSystemNo());//根据产出系统编号获取工序编号
                                testApplyRuleUtils.applyRulesCheckBySystemNo(applyPart_cursor.getSystemNo());
                                finishApplyPartList.add(applyPartDTO);
                                isNeedFinishApply = true;
                            }
                        }
                        // 2023-02-23 只有配置成品检才会自动创建成品检
                        // else{
                        //     //不存在检测申请配置,走原来的路径,判断是否是最后一道工序
                        //     if(baseMapper.isLastOperationBySystemNo(applyPart_cursor.getSystemNo())){
                        //         finishApplyPartList.add(applyPartDTO);
                        //     }
                        // }
 
                    }else if(dir.equals(UNMOVELIBRARY)){
                        //如果不是成品检测,才需要去校验是否存在成品检
                        if(!reportType.equals(Apply.PRODUCT_APPLY)){
                            String reportNo = baseMapper.getFinishedProductReportNo(applyPart_cursor.getSystemNo());
                            if(!StringUtils.isBlank(reportNo)){
                                throw new RuntimeException("请先删除成品检检测汇报!汇报编号--" + reportNo);
                            }
                            isNeedFinishApply = baseMapper.isExistFinishedApplyPart(applyPart_cursor.getSystemNo());
                        }
                    }
                }
                    //是成品检测,则mes移库;或者非成品检且产出非最后一道工序,则移库(该规则作废)
                    //if(reportType.equals(Apply.PRODUCT_APPLY) || !baseMapper.isLastOperationBySystemNo(applyPart_cursor.getSystemNo())){
                    if(!reportType.equals(Apply.PRODUCT_APPLY)){
                        //非成品检的移库
                        autoMoveStock(applyPart_cursor, dir, isNeedFinishApply);
                    }else{
                        //成品检的移库(单独处理)
                        String ruleApply = remoteParamService.getByKey(Apply.RULE_APPLY, SecurityConstants.FROM_IN).getData();
                        if(false && ruleApply.equals("true")){//成品检必定要经过过程检测
                            //如果没有尾检及工序检,则成品检也走上面的路径(待检移合格或不合格)
                            if(baseMapper.isConfigMoveLibraryTest(applyPart_cursor.getSystemNo())){
                                reportUtils.autoMoveStockFinishedProductV2(applyPart_cursor,dir);
                            }else{
                                autoMoveStock(applyPart_cursor, dir,false);
                            }
                        }else{
                            reportUtils.autoMoveStockFinishedProductV2(applyPart_cursor,dir);
                        }
                    }
//            }
        }
 
        //创建成品检
        if (!finishApplyPartList.isEmpty()) {
            ApplyDTO applyDTO = new ApplyDTO();
            applyDTO.setApplyPartList(finishApplyPartList);
            applyDTO.setApplyType(Apply.PRODUCT_APPLY);
            applyDTO.setFinishedProductAutoInsp(true);//很关键,标记为系统规则自动触发
            applyService.saveDto(applyDTO);
        }
 
        return isNeedFinishApply;
    }
 
    private boolean moveLibrary_mes_v2(List<ApplyPart> applyPartList,String reportType,String dir) {
        //检测汇报类型为空则中断程序
        if(StringUtils.isBlank(reportType)){
            throw new RuntimeException("检测汇报类型为空!操作已中断!");
        }
 
        List<ApplyPartDTO> finishApplyPartList = new ArrayList<>();//成品检list
 
        // 是否需要成品检处理
        boolean isNeedFinishApply = false;
 
        //不满足已首检&&首检状态为合格,则中断程序
        for(ApplyPart applyPart_cursor:applyPartList){
            //存在首检,且首检结果为合格(整改优化:汇报类型为尾检时才去判断是否存在首检)
            if(reportType.equals(Apply.OUTPUT_APPLY)){
                if(!isFirstApplyGood(applyPart_cursor.getLotBatchNo())){
                    throw new RuntimeException("系统编号--" + applyPart_cursor.getSystemNo() + "|SN号--" + applyPart_cursor.getLotBatchNo() + "--首检未做或首检不合格!操作已中断!");
                }
            }
 
            //批次首检不参与移库&&自动创建成品检
//            if(!reportType.equals(Apply.BATCHFIRST_APPLY)){
            //若工序为最后一道工序&&检测结果为合格&&汇报类型不是成品检,则自动生成成品检(该规则作废)
            //若工序为最后一道工序&&检测结果为合格&&汇报类型是非批次首检,则自动生成成品检(该规则作废)
            //(若工序为尾检或者工序检)&&检测结果为合格
            //if((reportType.equals(Apply.OUTPUT_APPLY) || reportType.equals(Apply.PROCESS_APPLY)) && applyPart_cursor.getOperationId() != null && applyPart_cursor.getIsQualified() && baseMapper.isLastOperationBySystemNo(applyPart_cursor.getSystemNo())){
            if((reportType.equals(Apply.OUTPUT_APPLY) || reportType.equals(Apply.PROCESS_APPLY)) && applyPart_cursor.getOperationId() != null && applyPart_cursor.getIsQualified()){
                if(dir.equals(MOVELIBRARY)){
                    //判断检测申请规则是否配置了成品检
                    String ruleApply = remoteParamService.getByKey(Apply.RULE_APPLY, SecurityConstants.FROM_IN).getData();
                    ApplyPartDTO applyPartDTO = new ApplyPartDTO();
                    applyPartDTO.setOutBatchNo(applyPart_cursor.getLotBatchNo());
                    applyPartDTO.setPartId(applyPart_cursor.getReplacePartId() == null ? applyPart_cursor.getPartId() : applyPart_cursor.getReplacePartId());
                    applyPartDTO.setSystemNo(applyPart_cursor.getSystemNo());
                    applyPartDTO.setPartName(applyPart_cursor.getReplacePartId() == null ? applyPart_cursor.getPartDesc() : applyPart_cursor.getReplacePartName());
                    applyPartDTO.setPartNo(applyPart_cursor.getReplacePartId() == null ? applyPart_cursor.getPartNo() : applyPart_cursor.getReplacePartNo());
                    applyPartDTO.setCheckLength(applyPart_cursor.getCheckLength());
                    if(ruleApply.equals("true") && baseMapper.isExistTestApplyConfigBySystemNo(applyPart_cursor.getSystemNo())){
                        //存在成品检检测申请配置
                        if(baseMapper.isConfigFinishedProdTest(applyPart_cursor.getSystemNo())){
                            //校验一下配置规则 (2023-02-24 配置规则不再使用,从车间订单配置中获取)
                            // String operationNo = baseMapper.selectOperationNoBySystemNo(applyPart_cursor.getSystemNo());//根据产出系统编号获取工序编号
                            testApplyRuleUtils.applyRulesCheckBySystemNo(applyPart_cursor.getSystemNo());
                            if (applyPart_cursor.getCheckLength().compareTo(BigDecimal.ZERO) > 0) {
                                finishApplyPartList.add(applyPartDTO);
                                isNeedFinishApply = true;
                            }
                        }
                    }
                    // 2023-02-23 只有配置成品检才会自动创建成品检
                    // else{
                    //     //不存在检测申请配置,走原来的路径,判断是否是最后一道工序
                    //     if(baseMapper.isLastOperationBySystemNo(applyPart_cursor.getSystemNo())){
                    //         finishApplyPartList.add(applyPartDTO);
                    //     }
                    // }
 
                } else if(dir.equals(UNMOVELIBRARY)) {
                    //如果不是成品检测,才需要去校验是否存在成品检
                    if(!reportType.equals(Apply.PRODUCT_APPLY)){
                        String reportNo = baseMapper.getFinishedProductReportNo(applyPart_cursor.getSystemNo());
                        if(!StringUtils.isBlank(reportNo)){
                            throw new RuntimeException("请先删除成品检检测汇报!汇报编号--" + reportNo);
                        }
                        isNeedFinishApply = baseMapper.isExistFinishedApplyPart(applyPart_cursor.getSystemNo());
                    }
                }
            }
            //是成品检测,则mes移库;或者非成品检且产出非最后一道工序,则移库(该规则作废)
            //if(reportType.equals(Apply.PRODUCT_APPLY) || !baseMapper.isLastOperationBySystemNo(applyPart_cursor.getSystemNo())){
            if(!reportType.equals(Apply.PRODUCT_APPLY)){
                //非成品检的移库
                autoMoveStockV2(applyPart_cursor, dir, isNeedFinishApply);
            }else{
                //成品检的移库(单独处理)
                String ruleApply = remoteParamService.getByKey(Apply.RULE_APPLY, SecurityConstants.FROM_IN).getData();
                if(false && ruleApply.equals("true")){//成品检必定要经过过程检测
                    //如果没有尾检及工序检,则成品检也走上面的路径(待检移合格或不合格)
                    if(baseMapper.isConfigMoveLibraryTest(applyPart_cursor.getSystemNo())){
                        reportUtils.autoMoveStockFinishedProductV2(applyPart_cursor,dir);
                    }else{
                        autoMoveStock(applyPart_cursor, dir,false);
                    }
                }else{
                    reportUtils.autoMoveStockFinishedProductV2(applyPart_cursor,dir);
                }
            }
//            }
        }
 
        //创建成品检
        if (!finishApplyPartList.isEmpty()) {
            ApplyDTO applyDTO = new ApplyDTO();
            applyDTO.setApplyPartList(finishApplyPartList);
            applyDTO.setApplyType(Apply.PRODUCT_APPLY);
            applyDTO.setFinishedProductAutoInsp(true);//很关键,标记为系统规则自动触发
            applyService.saveDto(applyDTO);
        }
 
        return isNeedFinishApply;
    }
 
 
    /**
     * 质检合格率统计报表
     * @param qualityCheckRateInputDTO
     */
    public IPage getQualityCheckRate(Page page, QualityCheckRateInputDTO qualityCheckRateInputDTO){
        return baseMapper.getQualityCheckRate(page,qualityCheckRateInputDTO);
    }
 
 
    /**
     * 质检合格率统计柱状图
     * @param qualityCheckRateInputDTO
     */
    public List<QualityCheckRatePictureDTO> getQualityCheckRatePicture(QualityCheckRateInputDTO qualityCheckRateInputDTO){
        return baseMapper.getQualityCheckRatePicture(qualityCheckRateInputDTO);
    }
 
    @Override
    public IPage<ApplyPartDTO> getTestApplyPage(Page page, QueryWrapper<ApplyPartDTO> gen, Integer queryType) {
        return this.baseMapper.getTestApplyPage(page, gen, queryType);
    }
}