李林
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
/*
 *    Copyright (c) 2018-2025, ztt All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: ztt
 */
package com.chinaztt.mes.technology.service.impl;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.Part;
import com.chinaztt.mes.basic.mapper.PartMapper;
import com.chinaztt.mes.common.numgen.NumberGenerator;
import com.chinaztt.mes.common.oa.OAProperty;
import com.chinaztt.mes.quality.dto.TestStandardDTO;
import com.chinaztt.mes.quality.entity.TestStandard;
import com.chinaztt.mes.quality.entity.TestStandardBinding;
import com.chinaztt.mes.quality.entity.TestStandardParam;
import com.chinaztt.mes.quality.mapper.TestStandardBindingMapper;
import com.chinaztt.mes.quality.mapper.TestStandardMapper;
import com.chinaztt.mes.quality.mapper.TestStandardParamMapper;
import com.chinaztt.mes.quality.service.impl.TestStandardServiceImpl;
import com.chinaztt.mes.quality.state.standard.constant.TestStandardStateStringValues;
import com.chinaztt.mes.technology.dto.*;
import com.chinaztt.mes.technology.entity.*;
import com.chinaztt.mes.technology.excel.DocumentTestStandardData;
import com.chinaztt.mes.technology.excel.MaterialCostData;
import com.chinaztt.mes.technology.mapper.*;
import com.chinaztt.mes.technology.service.DocumentJgtService;
import com.chinaztt.mes.technology.service.DocumentService;
import com.chinaztt.mes.technology.service.StructureService;
import com.chinaztt.mes.technology.state.bom.constant.BomStateStringValues;
import com.chinaztt.mes.technology.state.document.constant.DocumentStateStringValues;
import com.chinaztt.mes.technology.state.document.constant.DocumentStates;
import com.chinaztt.mes.technology.state.routing.constant.RoutingStateStringValues;
import com.chinaztt.mes.technology.util.DocumentWordExportUtils;
import com.chinaztt.mes.technology.util.TechnologyUtils;
import com.chinaztt.ztt.common.core.util.R;
import com.chinaztt.ztt.common.oss.service.OssTemplate;
import com.chinaztt.ztt.common.security.service.ZttUser;
import com.chinaztt.ztt.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 工艺文件
 *
 * @author zhangxy
 * @date 2021-05-07 09:45:58
 */
@Slf4j
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class DocumentServiceImpl extends ServiceImpl<DocumentMapper, Document> implements DocumentService {
 
    private static final String OSS_BUCKET = "technology";
    private final OssTemplate minioTemplate;
    private BomMapper bomMapper;
    private BomServiceImpl bomService;
    private BomComponentMapper bomComponentMapper;
    private DocumentMaterialCostMapper documentMaterialCostMapper;
    private IfsFeignClient ifsFeignClient;
    private OAProperty oaProperty;
    private OperationMapper operationMapper;
    private PartMapper partMapper;
    private RoutingOperationTemplateMapper routingOperationTemplateMapper;
    private RoutingOperationMapper routingOperationMapper;
    private RoutingOperationParamMapper routingOperationParamMapper;
    private RoutingServiceImpl routingService;
    private RoutingMapper routingMapper;
    private StructureService structureService;
    private StructureMapper structureMapper;
    private TestStandardMapper testStandardMapper;
    private TestStandardParamMapper testStandardParamMapper;
    private TestStandardBindingMapper testStandardBindingMapper;
    private JoinDocumentBomRoutingMapper joinDocumentBomRoutingMapper;
    private JoinDocumentTestStandardMapper joinDocumentTestStandardMapper;
    private TestStandardServiceImpl testStandardService;
    private NumberGenerator<Document> numberGenerator;
    private DocumentStandardParamMapper documentStandardParamMapper;
    private DocumentTestStandardMapper documentTestStandardMapper;
    private TechnologyUtils technologyUtils;
    private DocumentJgtMapper documentJgtMapper;
    private DocumentJgtService documentJgtService;
    private DocumentSamplingRuleMapper documentSamplingRuleMapper;
 
    /**
     * @Author: Hans
     * @Description: 根据工艺文件ID查询相关库存件、BOM、工艺路线、检测标准
     * @Date: 2022-06-09
     */
    @Override
    public DocumentDTO getDtoById(Long documentId) {
        Document document = baseMapper.selectById(documentId);
        DocumentDTO dto = new DocumentDTO();
        BeanUtils.copyProperties(document, dto);
        dto.setBomRoutings(baseMapper.getBomRoutingDtoByDocId(documentId));
        dto.setBomRoutingParts(baseMapper.getBomRoutingDtoPartByDocId(documentId));
        dto.setTestStandards(joinDocumentTestStandardMapper.selectDtoListByDocumentId(documentId));
        dto.setJgtList(documentJgtMapper.selectList(Wrappers.<DocumentJgt>lambdaQuery()
                .eq(DocumentJgt::getDocumentId,documentId)));
        List<DocumentMaterialCostDTO> costs = baseMapper.getMaterialCostByDocId(documentId);
        if (CollectionUtil.isNotEmpty(costs)) {
            dto.setMaterialCosts(costs.stream().collect(Collectors.groupingBy(DocumentMaterialCostDTO::getBomId)));
        }
        return dto;
    }
 
    @Override
    public DocumentDTO getDocumentById(Long id) {
        Document document = baseMapper.selectById(id);
        DocumentDTO dto = new DocumentDTO();
        BeanUtils.copyProperties(document, dto);
        //bom结构的数据
        dto.setBomRoutings(baseMapper.getBomRoutingDtoByDocId(id));
        //检测规则与工艺文件的关联表
        List<JoinDocumentTestStandardDTO> joinDocumentTestStandardList = joinDocumentTestStandardMapper.selectDtoListByDocumentId(id);
        if (CollectionUtil.isNotEmpty(joinDocumentTestStandardList)) {
            for (JoinDocumentTestStandardDTO join : joinDocumentTestStandardList) {
                join.setStandardParams(testStandardParamMapper.selectList(Wrappers.<TestStandardParam>lambdaQuery().eq(TestStandardParam::getTestStandardId, join.getTestStandardId())));
            }
            //检测规则与检测规则参数
            dto.setTestStandards(joinDocumentTestStandardList);
        }
        if (CollectionUtil.isNotEmpty(dto.getBomRoutings())) {
            for (JoinDocumentBomRoutingDTO joinDocumentBomRoutingDTO : dto.getBomRoutings()) {
                //工艺路线的数据(包含工序)
                joinDocumentBomRoutingDTO.setRoutingDTO(routingService.getRoutingById(joinDocumentBomRoutingDTO.getRoutingId()));
                if (CollectionUtil.isNotEmpty(joinDocumentBomRoutingDTO.getRoutingDTO().getOperations())) {
                    //循环工序把工序参数塞进工序
                    for (RoutingOperationDTO routingOperationDTO : joinDocumentBomRoutingDTO.getRoutingDTO().getOperations()) {
                        List<RoutingOperationTemplate> routingOperationTemplateList = routingOperationTemplateMapper.selectList(
                                Wrappers.<RoutingOperationTemplate>lambdaQuery()
                                        .eq(RoutingOperationTemplate::getRoutingOperationId, routingOperationDTO.getId()));
                        if (CollectionUtil.isNotEmpty(routingOperationTemplateList)) {
                            Set<Long> idList = routingOperationTemplateList.stream().map(o -> o.getId()).collect(Collectors.toSet());
                            List<RoutingOperationParam> routingOperationParamList = routingOperationParamMapper.selectList(Wrappers.<RoutingOperationParam>lambdaQuery()
                                    .in(RoutingOperationParam::getOperationTemplateId, idList).eq(RoutingOperationParam::getRoutingOperationId, routingOperationDTO.getId())
                                    .orderByAsc(RoutingOperationParam::getRoutingOperationId).orderByAsc(RoutingOperationParam::getId));
                            routingOperationDTO.setRoutingOperationParam(routingOperationParamList);
                        }
                    }
                }
            }
        }
        List<DocumentMaterialCostDTO> costs = baseMapper.getMaterialCostByDocId(id);
        if (CollectionUtil.isNotEmpty(costs)) {
            dto.setMaterialCosts(costs.stream().collect(Collectors.groupingBy(DocumentMaterialCostDTO::getBomId)));
        }
        return dto;
    }
 
    /**
     * 修改工艺文件状态
     *
     * @param ids
     * @param state
     * @return
     */
    @Override
    public boolean updateStateByIds(List<Long> ids, DocumentStates state) {
        List<Document> documentList = baseMapper.selectList(Wrappers.<Document>lambdaQuery().in(Document::getId, ids));
        //查询工艺路线和bom
        List<JoinDocumentBomRouting> djbList = joinDocumentBomRoutingMapper.selectList(Wrappers.
                <JoinDocumentBomRouting>lambdaQuery().in(JoinDocumentBomRouting::getDocumentId, ids));
        //查询检测标准
        List<JoinDocumentTestStandard> jdtsList = joinDocumentTestStandardMapper.selectList(Wrappers.
                <JoinDocumentTestStandard>lambdaQuery().in(JoinDocumentTestStandard::getDocumentId, ids));
        if (state.equals(DocumentStates.ACCEPTED)) {
            //检查合法性
            checkDocument(documentList);
            changeState(ids, djbList, jdtsList, DocumentStateStringValues.ACCEPTED, BomStateStringValues.ACCEPTED, RoutingStateStringValues.ACCEPTED, TestStandardStateStringValues.ACCEPTED);
        } else if (DocumentStates.DRAFT.equals(state)) {
            changeState(ids, djbList, jdtsList, DocumentStateStringValues.DRAFT, BomStateStringValues.DRAFT, RoutingStateStringValues.DRAFT, TestStandardStateStringValues.DRAFT);
        } else {
            changeDocState(ids, DocumentStateStringValues.REJECT);
        }
        List<Document> updateDocumentList = new ArrayList<>();
        for (Long id:ids) {
            Document document = new Document();
            document.setId(id);
            updateDocumentList.add(doUpdateRealUser(document));
        }
        updateBatchById(updateDocumentList);
        return true;
    }
 
    /**
     * 检验工艺文件合法性
     *
     * @param documents
     * @return
     */
    private void checkDocument(List<Document> documents) {
        for (Document document : documents) {
            List<JoinDocumentBomRouting> jbrList = joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery()
                    .eq(JoinDocumentBomRouting::getDocumentId, document.getId()));
            if (CollectionUtil.isEmpty(jbrList)) {
                throw new RuntimeException(document.getNumber() + "缺少工艺路线");
            }
            for (JoinDocumentBomRouting jbr : jbrList) {
                List<Long> ids = routingOperationMapper.checkOperationPartByRoutingId(jbr.getRoutingId());
                if (CollectionUtil.isNotEmpty(ids)) {
                    throw new RuntimeException(document.getNumber() + "工艺路线上工序未全部绑定零件");
                }
            }
        }
    }
 
    /**
     * 修改工艺文件和关联数据的状态
     *
     * @param ids
     * @param djbList
     * @param jdtsList
     * @param docState      工艺文件状态
     * @param bomState      bom状态
     * @param routingState  工艺路线状态
     * @param standardState 检测标准状态
     */
    private void changeState(List<Long> ids, List<JoinDocumentBomRouting> djbList, List<JoinDocumentTestStandard> jdtsList, String docState, String bomState, String routingState, String standardState) {
        //修改主表状态
        changeDocState(ids, docState);
        //更新BOM状态
        List<Long> bomIds = djbList.stream().map(JoinDocumentBomRouting::getBomId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(bomIds)) {
            UpdateWrapper<Bom> bomUpdateWrapper = new UpdateWrapper();
            bomUpdateWrapper.in("id", bomIds).set("state", bomState);
            bomMapper.update(null, bomUpdateWrapper);
        }
        //更新工艺状态
        List<Long> routingIds = djbList.stream().map(JoinDocumentBomRouting::getRoutingId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(routingIds)) {
            UpdateWrapper<Routing> routingUpdateWrapper = new UpdateWrapper();
            routingUpdateWrapper.in("id", routingIds).set("state", routingState);
            routingMapper.update(null, routingUpdateWrapper);
        }
        //更新检测标准
        List<Long> standardids = jdtsList.stream().map(JoinDocumentTestStandard::getTestStandardId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(standardids)) {
            UpdateWrapper<TestStandard> standardUpdateWrapper = new UpdateWrapper();
            standardUpdateWrapper.in("id", standardids).set("state", standardState);
            testStandardMapper.update(null, standardUpdateWrapper);
        }
    }
 
    /**
     * 修改工艺文件主表状态
     *
     * @param ids
     * @param state
     */
    private void changeDocState(List<Long> ids, String state) {
        if (CollectionUtil.isNotEmpty(ids)) {
            //设置工艺文件主表状态
            UpdateWrapper<Document> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in("id", ids).set("state", state);
            baseMapper.update(null, updateWrapper);
        }
    }
 
 
    @Override
    public IPage<List<TestStandard>> getTestStand(Page page, QueryWrapper<TestStandardDTO> ew, Long id) {
        return testStandardMapper.getTestStand(page, ew, id);
    }
 
    @Override
    public R<Map<Long, Collection<DocumentMaterialCostDTO>>> calcMaterialCost(Long documentId) {
        //先删除老的
        documentMaterialCostMapper.delete(Wrappers.<DocumentMaterialCost>lambdaQuery().eq(DocumentMaterialCost::getDocumentId, documentId));
        List<JoinDocumentBomRouting> joinList = joinDocumentBomRoutingMapper.selectList
                (Wrappers.<JoinDocumentBomRouting>lambdaQuery().eq(JoinDocumentBomRouting::getDocumentId, documentId));
        if (CollectionUtil.isEmpty(joinList)) {
            return R.failed("请先添加产品结构工序参数");
        }
        Map<Long, Collection<DocumentMaterialCostDTO>> result = new HashMap<>(8);
        //循环每个BOM
        for (JoinDocumentBomRouting j : joinList) {
            //如果没有bomId 和 工艺路线id 都是null 就跳过当前循环
            if (j.getBomId() == null || j.getRoutingId() == null) {
                continue;
            }
            List<BomComponent> bomComponentTotallList = bomComponentMapper.selectList(Wrappers.<BomComponent>lambdaQuery()
                    .eq(BomComponent::getBomId, j.getBomId()).isNotNull(BomComponent::getParent));
            List<Long> fatherIds = bomComponentTotallList.stream().map(e -> e.getParent()).collect(Collectors.toList());
            RoutingDTO routing = routingMapper.getRoutingDtoById(j.getRoutingId());
            Bom bom = bomMapper.selectById(j.getBomId());
            Part bomPart = partMapper.selectById(bom.getPartId());
            setIndex(routing);
            List<DocumentMaterialCostDTO> dlist = new ArrayList<>();
            for (RoutingOperationDTO routingOperationDTO : routing.getOperations()) {
                List<BomComponent> bomComponentList = bomComponentMapper.selectList(Wrappers.<BomComponent>lambdaQuery()
                        .eq(BomComponent::getBomId, j.getBomId())
                        .eq(BomComponent::getPartId, routingOperationDTO.getPartId())
                );
                bomComponentList.forEach(e -> {
                    List<BomComponentDTO> childList = bomMapper.getBomComponentsOrderByPartName(j.getBomId(), e.getId());
                    childList.forEach(ce -> {
                        if (!fatherIds.contains(ce.getId())) {
                            DocumentMaterialCostDTO dto = new DocumentMaterialCostDTO();
                            Part part = partMapper.selectById(ce.getPartId());
                            Operation operation = operationMapper.selectById(routingOperationDTO.getOperationId());
                            dto.setDocumentId(documentId);
                            dto.setBomId(ce.getBomId());
                            dto.setPartId(ce.getPartId());
                            dto.setOperationName(operation.getName());
                            dto.setBomNumber(bom.getNumber());
                            dto.setFinishedProduct(bomPart.getPartName());
                            dto.setOperationId(routingOperationDTO.getOperationId());
                            dto.setIndex(routingOperationDTO.getIndex());
                            dto.setPartName(part.getPartName());
                            dto.setUnit(part.getUnit());
                            dto.setQuantity(ce.getQpa());
                            documentMaterialCostMapper.insert(dto);
                            dlist.add(dto);
                        }
                    });
                });
            }
            result.put(bom.getId(), dlist);
        }
        return R.ok(result);
    }
 
 
    private void setIndex(RoutingDTO routing) {
        List<RoutingOperationDTO> operations = routing.getOperations();
        if (CollectionUtil.isEmpty(operations)) {
            return;
        }
        if (operations.size() == 1) {
            operations.get(0).setIndex(1);
            return;
        }
        Set<Long> roIds = operations.stream().map(r -> r.getId()).collect(Collectors.toSet());
        List<RefDTO> refs = routing.getRefs();
        Map<Long, Long> refMap = refs.stream().collect(Collectors.toMap(RefDTO::getFromId, RefDTO::getToId));
        //找到第一个节点
        final Long first = roIds.stream().filter(id -> refMap.keySet().contains(id) && !refMap.values().contains(id)).findFirst().get();
        operations.stream().filter(e -> e.getId().equals(first)).findFirst().get().setIndex(1);
 
        Long fromId = first;
        int index = 2;
 
        while (refMap.get(fromId) != null) {
            Long toId = refMap.get(fromId);
            if (toId == null) {
                break;
            }
            operations.stream().filter(o -> o.getId().equals(toId)).findAny().get().setIndex(index);
            fromId = toId;
            index++;
        }
        operations.sort(Comparator.comparing(RoutingOperationDTO::getIndex));
    }
 
 
    @Override
    public R saveBom(JoinDocumentBomRouting join) {
        if (join.getDocumentId() == null) {
            return R.failed("请先保存基本信息");
        }
        if (join.getRoutingId() == null) {
            return R.failed("请先选择工艺");
        }
        //如果传了BomId 就用传的BomId
        if (join.getBomId() == null) {
            Routing routing = routingMapper.selectById(join.getRoutingId());
            join.setBomId(routing.getBomId());
        }
        joinDocumentBomRoutingMapper.updateById(join);
        if (join.getBomId() != null) {
            delRoutings(join.getId());
            addDocTestStandard(join);
            Document document = getById(join.getDocumentId());
            addBomRoutingPartByBomId(join.getId(), join.getBomId(), join.getDocumentId(), document.getDocType());
        }
        Document document = new Document();
        document.setId(join.getDocumentId());
        baseMapper.updateById(doUpdateRealUser(document));
        return R.ok(getDtoById(join.getDocumentId()));
    }
 
 
    private void addBomRoutingPartByBomId(Long parentId, Long bomId, Long documentId, String docType) {
        Bom bom = bomMapper.selectById(bomId);
        if (bom == null) {
            throw new RuntimeException("bom丢失id为" + bomId);
        }
        List<Part> parts = bomMapper.getBomCompontBomPart(bomId);
        for (Part part : parts) {
            JoinDocumentBomRouting joinDocumentBomRouting = new JoinDocumentBomRouting();
            joinDocumentBomRouting.setPartId(part.getId());
            joinDocumentBomRouting.setDocumentId(documentId);
            joinDocumentBomRouting.setParentId(parentId);
            // 根据PartID查找工艺路线中数据,并进行设置
            List<Routing> routings = routingMapper.selectList(Wrappers.<Routing>lambdaQuery()
                    .eq(Routing::getPartId, part.getId())
                    .eq(Routing::getBomTypeDb, docType)
                    .orderByDesc(Routing::getId));
            if (CollectionUtil.isEmpty(routings)) {
                throw new RuntimeException("保存失败,零件:" + part.getPartNo() + "无工艺路线");
            }
            Routing routing = routings.get(0);
            joinDocumentBomRouting.setRoutingId(routing.getId());
            joinDocumentBomRouting.setBomId(routing.getBomId());
            joinDocumentBomRoutingMapper.insertAndGetId(joinDocumentBomRouting);
            // 添加检测标准
            addDocTestStandard(joinDocumentBomRouting);
            // 当前零件有Bom数据且零件为制造件“A”
            if (routing.getBomId() != null && part.getPlanningMethod().equals("A") && part.getMaterialType().equals("1")) {
                addBomRoutingPartByBomId(joinDocumentBomRouting.getId(), routing.getBomId(), documentId, docType);
            }
        }
    }
 
    @Override
    public R<Boolean> saveTestStandard(List<JoinDocumentTestStandardDTO> joins) {
        if (CollectionUtil.isNotEmpty(joins)) {
            joins.forEach(j -> {
                int count = joinDocumentTestStandardMapper.selectCount(Wrappers.<JoinDocumentTestStandard>lambdaQuery().eq(JoinDocumentTestStandard::getDocumentId, j.getDocumentId())
                        .eq(JoinDocumentTestStandard::getTestStandardId, j.getTestStandardId()));
                if (count == 0) {
                    joinDocumentTestStandardMapper.insert(j);
                }
            });
        }
        return R.ok();
    }
 
    @Override
    public R<Boolean> deleteTestStandard(JoinDocumentTestStandardDTO join) {
        joinDocumentTestStandardMapper.delete(Wrappers.<JoinDocumentTestStandard>lambdaQuery().eq(JoinDocumentTestStandard::getDocumentId, join.getDocumentId())
                .eq(JoinDocumentTestStandard::getTestStandardId, join.getTestStandardId()));
        return R.ok();
    }
 
    @Override
    public R deleteBom(JoinDocumentBomRouting join) {
        if (join.getId() == null) {
            return R.failed("请选择需要删除数据");
        }
        JoinDocumentBomRouting joinDocumentBomRouting = joinDocumentBomRoutingMapper.selectById(join.getId());
        //工艺主表更新时间,更新人
        Document document = new Document();
        document.setId(joinDocumentBomRouting.getDocumentId());
        baseMapper.updateById(doUpdateRealUser(document));
        //先新增一个在删除
        JoinDocumentBomRouting jadd = new JoinDocumentBomRouting();
        jadd.setParentId(joinDocumentBomRouting.getParentId());
        jadd.setPartId(joinDocumentBomRouting.getPartId());
        jadd.setDocumentId(joinDocumentBomRouting.getDocumentId());
        //再新增一个
        joinDocumentBomRoutingMapper.insert(jadd);
        //刪除子节点和检测标准
        if (joinDocumentBomRouting.getRoutingId() != null) {
            delRoutings(joinDocumentBomRouting.getId());
        }
        //删除当前节点和检测标准
        delJoinAndTest(joinDocumentBomRouting);
        joinDocumentBomRoutingMapper.deleteById(joinDocumentBomRouting.getId());
        return R.ok(getDtoById(joinDocumentBomRouting.getDocumentId()));
    }
 
    //删除子节点
    private void delRoutings(Long id) {
        List<JoinDocumentBomRouting> joinDocumentBomRoutingList = joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery()
                .eq(JoinDocumentBomRouting::getParentId, id));
        for (JoinDocumentBomRouting joinDocumentBomRouting : joinDocumentBomRoutingList) {
            delJoinAndTest(joinDocumentBomRouting);
            joinDocumentBomRoutingMapper.deleteById(joinDocumentBomRouting.getId());
            delRoutings(joinDocumentBomRouting.getId());
        }
    }
 
 
    @Override
    public R<Integer> routingChildCheck(Long id) {
        return R.ok(joinDocumentBomRoutingMapper.selectCount(Wrappers.<JoinDocumentBomRouting>lambdaQuery().eq(JoinDocumentBomRouting::getParentId, id)));
    }
 
    @SneakyThrows
    @Override
    public void exportMaterialCost(Long documentId, HttpServletResponse response) {
        List<JoinDocumentBomRouting> joinList = joinDocumentBomRoutingMapper.selectList
                (Wrappers.<JoinDocumentBomRouting>lambdaQuery().eq(JoinDocumentBomRouting::getDocumentId, documentId));
        if (CollectionUtil.isEmpty(joinList)) {
            return;
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
 
        String fileName = URLEncoder.encode("工艺文件原材料表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
 
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), MaterialCostData.class).build();
        for (int i = 0; i < joinList.size(); i++) {
            Bom bom = bomMapper.selectById(joinList.get(i).getBomId());
            WriteSheet sheet = EasyExcel.writerSheet(i, bom.getNumber()).head(MaterialCostData.class).build();
            List<MaterialCostData> data = baseMapper.exportList(documentId, bom.getId());
            excelWriter.write(data, sheet);
 
        }
        excelWriter.finish();
    }
 
    @Override
    public void updateStateByOa(String workflowId, DocumentStates state) {
        Document document = baseMapper.selectOne(Wrappers.<Document>lambdaQuery().eq(Document::getOaWorkflowId, workflowId));
        if (document == null) {
            log.error("工艺文件审批回调", "workflowId=" + workflowId + "对应的工艺文件没有找到");
            return;
        }
 
        List<JoinDocumentBomRouting> joinList1 = joinDocumentBomRoutingMapper.selectList(Wrappers.
                <JoinDocumentBomRouting>lambdaQuery().eq(JoinDocumentBomRouting::getDocumentId, document.getId()));
        List<JoinDocumentTestStandard> joinList2 = joinDocumentTestStandardMapper.selectList(Wrappers.
                <JoinDocumentTestStandard>lambdaQuery().eq(JoinDocumentTestStandard::getDocumentId, document.getId()));
 
        if (DocumentStates.ACCEPTED.equals(state)) {
            //批准
            document.setState(DocumentStateStringValues.ACCEPTED);
 
            if (CollectionUtil.isNotEmpty(joinList1)) {
                //循环更新工艺、BOM状态
                for (JoinDocumentBomRouting j : joinList1) {
                    UpdateWrapper<Bom> bomUpdateWrapper = new UpdateWrapper();
                    bomUpdateWrapper.set("state", BomStateStringValues.ACCEPTED);
                    bomUpdateWrapper.eq("id", j.getBomId());
                    bomMapper.update(null, bomUpdateWrapper);
 
                    UpdateWrapper<Routing> routingUpdateWrapper = new UpdateWrapper();
                    routingUpdateWrapper.set("state", RoutingStateStringValues.ACCEPTED);
                    routingUpdateWrapper.eq("id", j.getRoutingId());
                    routingMapper.update(null, routingUpdateWrapper);
                }
            }
 
            if (CollectionUtil.isNotEmpty(joinList2)) {
                //更新检测标准状态
                for (JoinDocumentTestStandard jj : joinList2) {
                    UpdateWrapper<TestStandard> standardUpdateWrapper = new UpdateWrapper();
                    standardUpdateWrapper.set("state", TestStandardStateStringValues.ACCEPTED);
                    standardUpdateWrapper.eq("id", jj.getTestStandardId());
                    testStandardMapper.update(null, standardUpdateWrapper);
                }
            }
 
        } else {
            //驳回
            document.setState(DocumentStateStringValues.REJECT);
        }
        baseMapper.updateById(document);
    }
 
    @SneakyThrows
    @Override
    public R uploadJgt(List<MultipartFile> file, Long documentId) {
        List<DocumentJgt> list = new ArrayList<>();
        for (MultipartFile multipartFile:file) {
            String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(multipartFile.getOriginalFilename());
            minioTemplate.putObject(OSS_BUCKET, fileName, multipartFile.getInputStream());
            DocumentJgt jgt = new DocumentJgt();
            jgt.setFileName(fileName);
            jgt.setDocumentId(documentId);
            list.add(jgt);
        }
        //工艺主表更新时间,更新人
        Document document = new Document();
        document.setId(documentId);
        baseMapper.updateById(doUpdateRealUser(document));
        documentJgtService.saveBatch(list);
        List<String> fileNameList = list.stream().map(a -> a.getFileName()).collect(Collectors.toList());
        return R.ok(org.apache.commons.lang3.StringUtils.join(fileNameList,","));
    }
 
    @SneakyThrows
    @Override
    public R uploadLct(MultipartFile file, Long documentId, String lctRemark) {
        Document document = baseMapper.selectById(documentId);
        if (StringUtils.isNotBlank(document.getLct())) {
            minioTemplate.removeObject(OSS_BUCKET, document.getLct());
        }
 
        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
        minioTemplate.putObject(OSS_BUCKET, fileName, file.getInputStream());
 
        document.setLctRemark(lctRemark);
        document.setLct(fileName);
        baseMapper.updateById(doUpdateRealUser(document));
 
        return R.ok("/document/" + OSS_BUCKET + "/" + fileName);
    }
 
    @SneakyThrows
    @Override
    public R removeJgt(Long jgtId) {
        DocumentJgt documentJgt = documentJgtMapper.selectById(jgtId);
        //工艺主表更新时间,更新人
        Document document = new Document();
        document.setId(documentJgt.getDocumentId());
        baseMapper.updateById(doUpdateRealUser(document));
        if (StringUtils.isNotBlank(documentJgt.getFileName())) {
            minioTemplate.removeObject(OSS_BUCKET, documentJgt.getFileName());
            documentJgtMapper.deleteById(jgtId);
        }
        return R.ok();
    }
 
    @SneakyThrows
    @Override
    public R removeLct(Long documentId) {
        Document document = baseMapper.selectById(documentId);
        if (StringUtils.isNotBlank(document.getLct())) {
            minioTemplate.removeObject(OSS_BUCKET, document.getLct());
            document.setLct(null);
            document.setId(documentId);
            baseMapper.updateById(doUpdateRealUser(document));
 
        }
        return R.ok();
    }
 
    @Override
    public void getFile(String fileName, HttpServletResponse response) {
        try (InputStream inputStream = minioTemplate.getObject(OSS_BUCKET, fileName)) {
            response.setContentType("application/octet-stream; charset=UTF-8");
            IoUtil.copy(inputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("文件读取异常: {}", e.getLocalizedMessage());
        }
    }
 
    @Override
    public R copyDocument(List<Document> documentList) {
        return R.failed("相同零件不可有多个工艺文件");
//        if (CollectionUtil.isNotEmpty(documentList)) {
//            for (Document document : documentList) {
//                Long id = document.getId();
//                //新增工艺文件主表
//                document.setId(null);
//                document.setOaWorkflowId(null);
//                document.setState(DocumentStateStringValues.DRAFT);
//                document.setNumber(numberGenerator.generateNumberWithPrefix(Document.DIGIT, Document.PREFIX, Document::getNumber));
//                baseMapper.insert(document);
//                //查询工艺文件的检测和参数
//                List<TestStandard> testStandardList = testStandardMapper.getTestStandard(id);
//                for (TestStandard testStandard : testStandardList) {
//                    //复制检测规则和参数
//                    TestStandard newTestStandard = testStandardService.copyTestStandard(testStandard);
//                    JoinDocumentTestStandard joinDocumentTestStandard = new JoinDocumentTestStandard();
//                    joinDocumentTestStandard.setDocumentId(document.getId());
//                    joinDocumentTestStandard.setTestStandardId(newTestStandard.getId());
//                    joinDocumentTestStandardMapper.insert(joinDocumentTestStandard);
//                }
//                //查询工艺文件关联bom和工艺路线
//                List<JoinDocumentBomRouting> joinDocumentBomRoutingList = joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery().eq(JoinDocumentBomRouting::getDocumentId, id));
//                if (CollectionUtil.isNotEmpty(joinDocumentBomRoutingList)) {
//                    for (JoinDocumentBomRouting joinDocumentBomRouting : joinDocumentBomRoutingList) {
//                        //根据工艺路线id查询工艺路线
//                        List<RoutingDTO> routingDTO = routingService.getByRoutingId(joinDocumentBomRouting.getRoutingId());
//                        //复制工艺路线
//                        R<List<Routing>> routingList = routingService.copyRoutingSave(routingDTO);
//                        List<Routing> routing = routingList.getData();
//                        //复制的bom
//                        Bom bom = bomService.copyBom(joinDocumentBomRouting.getBomId());
//                        //保存新的关联关系
//                        JoinDocumentBomRouting newJoinDocumentBomRouting = new JoinDocumentBomRouting();
//                        newJoinDocumentBomRouting.setDocumentId(document.getId());
//                        newJoinDocumentBomRouting.setBomId(bom.getId());
//                        newJoinDocumentBomRouting.setRoutingId(routing.get(0).getId());
//                        joinDocumentBomRoutingMapper.insert(newJoinDocumentBomRouting);
//                    }
//                }
//            }
//        }
//        return R.ok();
    }
 
    /**
     * @Author: Hans
     * @Description: 重写保存工艺文件
     * @Date: 2022-06-10
     */
    @Override
    public R fullSave(Document document) {
        List<Document> documentList = baseMapper.selectList(Wrappers.<Document>lambdaQuery()
                .eq(Document::getVersion,document.getVersion())
                .eq(Document::getPartId, document.getPartId())
                .eq(Document::getDocType, document.getDocType()));
        if (CollectionUtil.isNotEmpty(documentList)) {
            return R.failed("该零件号同一版本已存在工艺文件");
        }
        Document newDocument = new Document();
        BeanUtils.copyProperties(document, newDocument);
        checkDocumentNumber(newDocument);
        newDocument.setState(DocumentStateStringValues.DRAFT);
        baseMapper.insert(newDocument);
        buildBomRoutingBom(newDocument);
        return R.ok(newDocument);
    }
 
    /**
     * @Author: Hans
     * @Description: 重写更新工艺文件
     * @Date: 2022-06-10
     */
    @Override
    public R fullUpdate(Document document) {
        Document oriDocument = baseMapper.selectById(document.getId());
        if (!oriDocument.getPartId().equals( document.getPartId())
                || !org.apache.commons.lang3.StringUtils.equals(document.getDocType(), oriDocument.getDocType())) {
            List<Document> documentList = baseMapper.selectList(Wrappers.<Document>lambdaQuery()
                    .ne(Document::getId, document.getId())
                    .eq(Document::getPartId, document.getPartId())
                    .eq(Document::getVersion, document.getVersion())
                    .eq(Document::getDocType, document.getDocType()));
            if (CollectionUtil.isNotEmpty(documentList)) {
                throw new RuntimeException("该零件号同一版本已存在工艺文件");
            }
            // 先删除工艺文件、BOM、工艺路线关联表中数据
            List<JoinDocumentBomRouting> joinDocumentBomRoutingList =
                    joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery().eq(JoinDocumentBomRouting::getDocumentId, document.getId()));
            delJoinAndTest(joinDocumentBomRoutingList);
            buildBomRoutingBom(document);
        }
        baseMapper.updateById(doUpdateRealUser(document));
        return R.ok(document);
    }
 
 
    /**
     * @Author: Hans
     * @Description: 构建工艺文件、工艺路线、BOM数据关联表
     * @Date: 2022-06-10
     */
    private void buildBomRoutingBom(Document document) {
        JoinDocumentBomRouting joinDocumentBomRouting = new JoinDocumentBomRouting();
        joinDocumentBomRouting.setDocumentId(document.getId());
        joinDocumentBomRouting.setPartId(document.getPartId());
        joinDocumentBomRouting.setQrate(BigDecimal.ONE);
        // 根据PartID查找工艺路线中数据,并进行设置
        List<Routing> routings = routingMapper.selectList(Wrappers.<Routing>lambdaQuery()
                .eq(Routing::getPartId, document.getPartId())
                .eq(Routing::getBomTypeDb, document.getDocType())
                .orderByDesc(Routing::getId));
        if (CollectionUtil.isEmpty(routings)) {
            throw new RuntimeException("保存失败,零件:" + document.getPartNo() + "无工艺路线");
        }
        Routing routing = routings.get(0);
        joinDocumentBomRouting.setRoutingId(routing.getId());
        joinDocumentBomRouting.setBomId(routing.getBomId());
        joinDocumentBomRoutingMapper.insertAndGetId(joinDocumentBomRouting);
        // 添加检测标准
        addDocTestStandard(joinDocumentBomRouting);
        // 设置子节点数据
        addBomRoutingPartByBomId(joinDocumentBomRouting.getId(), routing.getBomId(),
                joinDocumentBomRouting.getDocumentId(),document.getDocType());
 
    }
 
 
    @Override
    public boolean updateById(Document document) {
        checkDocumentNumber(document);
        return SqlHelper.retBool(baseMapper.updateById(document));
    }
 
    private void checkDocumentNumber(Document document) {
        if (StringUtils.isBlank(document.getNumber())) {
            // 1. 自动生成编号
            document.setNumber(numberGenerator.generateNumberWithPrefix(Document.DIGIT, Document.PREFIX, Document::getNumber));
        } else {
            // 2.判断是否重复
            List<Document> repeatNos = baseMapper.selectList(Wrappers.<Document>query().lambda().eq(Document::getNumber, document.getNumber()).ne(Document::getId, document.getId()));
            if (CollectionUtil.isNotEmpty(repeatNos)) {
                throw new RuntimeException("编号重复");
            }
        }
    }
 
    /**
     * 构建检测参数
     *
     * @param documentId
     * @param doc
     */
    private void buildTestParam(Long documentId, XWPFDocument doc) {
        DocumentWordExportUtils.createText(doc, "1", "7 成品检测", true, "宋体");
        List<JoinDocumentTestStandard> joinList = joinDocumentTestStandardMapper.selectList(Wrappers.<JoinDocumentTestStandard>lambdaQuery().eq(JoinDocumentTestStandard::getDocumentId, documentId));
        for (int j = 1; j <= joinList.size(); j++) {
            List<TestStandardParam> testStandardParams = testStandardParamMapper.selectList(Wrappers.<TestStandardParam>lambdaQuery().eq(TestStandardParam::getTestStandardId, joinList.get(j - 1).getTestStandardId()));
            if (CollectionUtil.isNotEmpty(testStandardParams)) {
                for (int i = 1; i <= testStandardParams.size(); i++) {
                    DocumentWordExportUtils.createText(doc, null, "7." + j + "." + i + testStandardParams.get(i - 1).getParameterItem(), false, "宋体");
                    DocumentWordExportUtils.createText(doc, null, "    " + testStandardParams.get(i - 1).getReferenceValue(), false, "宋体");
                }
            }
        }
    }
 
    /**
     * 构建工序参数
     *
     * @param documentId
     * @param doc
     */
    private void buildOperationParam(Long documentId, XWPFDocument doc) {
        List<JoinDocumentBomRouting> jbrList = joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery().eq(JoinDocumentBomRouting::getDocumentId, documentId));
        if (CollectionUtil.isNotEmpty(jbrList)) {
            //工艺参数导出,多个BOM对应的工序步骤是一样的,但是每道的参数不一样
            JoinDocumentBomRouting jbr = jbrList.get(0);
            List<RoutingOperation> routingOperations = routingOperationMapper.selectList(Wrappers.<RoutingOperation>lambdaQuery().eq(RoutingOperation::getRoutingId, jbr.getRoutingId()));
            if (CollectionUtil.isNotEmpty(routingOperations)) {
                for (int i = 0; i < routingOperations.size(); i++) {
                    RoutingOperation routingOperation = routingOperations.get(i);
                    Operation operation = operationMapper.selectById(routingOperation.getOperationId());
                    int num = i + 1;
                    DocumentWordExportUtils.createText(doc, "2", "6." + num + operation.getName(), true, "宋体");
                    DocumentWordExportUtils.createText(doc, null, "   6." + num + ".1 生产设备: ", false, "宋体");
                    if (StringUtils.isNotBlank(routingOperation.getRemark())) {
                        String[] remarkArray = DocumentWordExportUtils.returnStation(routingOperation.getRemark(), "\r\n");
                        for (int d = 0; d < remarkArray.length; d++) {
                            DocumentWordExportUtils.createText(doc, null, "   6." + num + ".2." + remarkArray[d], false, "宋体");
                        }
                    }
                    Map<String, List<RoutingOperationParam>> stringListMap = new LinkedHashMap<>();
 
                    for (int a = 0; a < jbrList.size(); a++) {
                        List<RoutingOperationParam> params = routingOperationParamMapper.selectList(Wrappers.<RoutingOperationParam>lambdaQuery()
                                .eq(RoutingOperationParam::getRoutingId, jbrList.get(0).getRoutingId()).eq(RoutingOperationParam::getOperationId, operation.getId()));
                        Bom bom = bomMapper.selectById(jbrList.get(a).getBomId());
                        Part finalProduct = partMapper.selectById(bom.getPartId());
                        stringListMap.put(finalProduct.getPartName(), params);
                    }
                    DocumentWordExportUtils.createParaTable(doc, stringListMap);
                }
            }
        }
    }
 
    /**
     * 同步ifs
     *
     * @param id
     * @return
     */
    @Override
    public R ifsSync(Long id) {
        String msg = "";
        R routingIfsSyncResult = routingIfsSync(id);
        int code = 0;
        if (routingIfsSyncResult.getCode() == 0) {
            msg += "工艺路线同步成功!";
        } else {
            msg += "工艺路线同步失败!原因:" + routingIfsSyncResult.getMsg() + " !";
            code = 1;
        }
        R structureIfsSyncResult = structureIfsSync(id);
        if (structureIfsSyncResult.getCode() == 0) {
            msg += "产品结构同步成功!";
        } else {
            msg += "产品结构同步失败!原因:" + structureIfsSyncResult.getMsg() + " !";
            code = 1;
        }
        R routingIfsCalResult = routingIfsCal(id);
        if (routingIfsCalResult.getCode() == 0) {
            msg += "工艺路线替代制造提前期计算成功";
        } else {
            msg += "工艺路线替代制造提前期计算失败!原因:" + routingIfsCalResult.getMsg() + " !";
            code = 1;
        }
        Document document = new Document();
        document.setId(id);
        baseMapper.updateById(doUpdateRealUser(document));
        if (code == 0) {
            return R.ok().setMsg(msg);
        } else {
            return R.failed(msg);
        }
    }
 
    /**
     * 工艺路线的对接
     *
     * @param id
     * @return
     */
    private R routingIfsSync(Long id) {
        List<JoinDocumentBomRouting> joinList = joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery()
                .eq(JoinDocumentBomRouting::getDocumentId, id)
                .isNotNull(JoinDocumentBomRouting::getRoutingId));
        List<Long> routingIds = joinList.stream().map(joinDocumentBomRouting -> joinDocumentBomRouting.getRoutingId()).collect(Collectors.toList());
        return R.ok(routingService.routingIfsSync(routingIds));
    }
 
    /**
     * 对接产品结构
     *
     * @param id
     * @return
     */
    private R structureIfsSync(Long id) {
        List<StructureDTO> structureDTOS = structureMapper.getStructureDtoByDocId(id);
        return R.ok(structureService.structureIfsSyncByDto(structureDTOS));
    }
 
    /**
     * 工艺路线替代提前制造
     *
     * @param id
     * @return
     */
    private R routingIfsCal(Long id) {
        List<JoinDocumentBomRouting> joinList = joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery()
                .eq(JoinDocumentBomRouting::getDocumentId, id)
                .isNotNull(JoinDocumentBomRouting::getRoutingId));
        List<Long> routingIds = joinList.stream().map(joinDocumentBomRouting -> joinDocumentBomRouting.getRoutingId()).collect(Collectors.toList());
        return R.ok(routingService.routingIfsCal(routingIds));
    }
 
    /**
     * 根据零件添加检测标准
     *
     * @param joinDocumentBomRouting
     */
    private void addDocTestStandard(JoinDocumentBomRouting joinDocumentBomRouting) {
        //查询工艺路线工序
        List<RoutingOperation> routingOperationList = routingOperationMapper.selectList(Wrappers.<RoutingOperation>lambdaQuery()
                .eq(RoutingOperation::getRoutingId, joinDocumentBomRouting.getRoutingId()));
        //根据每个工艺路线工序的零件id 查询检测标准
        for (RoutingOperation routingOperation : routingOperationList) {
            if (null != routingOperation.getPartId()) {
                List<TestStandardBinding> testStandardBindingList = testStandardBindingMapper.selectList(Wrappers.<TestStandardBinding>lambdaQuery()
                        .eq(TestStandardBinding::getPartId, routingOperation.getPartId()));
                // 将所有的检测标准全部添加进来
                for (TestStandardBinding testStandardBinding : testStandardBindingList) {
                    addDocTestStandard(joinDocumentBomRouting.getId(), routingOperation.getId(), testStandardBinding.getStandardId());
                }
            }
        }
    }
 
    @Override
    public boolean addDocTestStandard(Long docBomId, Long routingOperationId, Long testStandardId) {
        DocumentTestStandard documentTestStandard = documentTestStandardMapper.getDocumentTestStandardByStandardId(testStandardId);
        if (documentTestStandard != null) {
            String testType = documentTestStandard.getInspectionType();
            Boolean isFinishedProduct = false;
            if (testType.equals("成品检验") || testType.equals("06finishedproduct")) {
                isFinishedProduct = true;//检测标准那边导入有问题,没有把name转成code
            }
            List<DocumentStandardParam> documentStandardParamList = documentStandardParamMapper.getDocumentStandardParamListByStandardId(testStandardId);
            if (null != documentTestStandard) {
                documentTestStandard.setDocBomId(docBomId);//工艺文件与bom关系表id
                documentTestStandard.setRoutingOperationId(routingOperationId);//工艺工序id
                documentTestStandardMapper.insert(documentTestStandard);
                for (DocumentStandardParam documentStandardParam : documentStandardParamList) {
                    documentStandardParam.setTestStandardId(documentTestStandard.getId());//主表id
                    if (BooleanUtil.isTrue(documentStandardParam.getIsReference())) {
                        //成品检的引用池范围:工艺文件中所有工艺路线下所有工序对应的工序参数;其他检引用池范围:该工序下的工艺参数
                        //若引用工艺参数,则根据参数编号判断工艺项是否存在
                        String paramValue;
                        if (isFinishedProduct) {
                            paramValue = technologyUtils.getRoutingOperationParamValueFinishedproduct(docBomId, routingOperationId, documentStandardParam.getCode(), documentStandardParam.getWireCore());
                        } else {
                            paramValue = technologyUtils.getRoutingOperationParamValue(docBomId, routingOperationId, documentStandardParam.getCode());
                        }
                        if (paramValue != null) {
                            documentStandardParam.setReferenceValue(paramValue);//取到有效值后才引用
                        }
                    }
                    documentStandardParamMapper.insert(documentStandardParam);
                }
 
                // 查找是否存在抽检规则
                RoutingOperation routingOperation = routingOperationMapper.selectById(routingOperationId);
                DocumentSamplingRule documentSamplingRule = documentSamplingRuleMapper.getSamplingRuleByOperationIdAndApplyType(routingOperation.getOperationId(), testType);
                addDocSamplingRule(docBomId, routingOperationId, null, documentSamplingRule, testType);
            }
            JoinDocumentBomRouting joinDocumentBomRouting = joinDocumentBomRoutingMapper.selectById(docBomId);
            JoinDocumentTestStandard joinDocumentTestStandard = new JoinDocumentTestStandard();
            joinDocumentTestStandard.setDocumentId(joinDocumentBomRouting.getDocumentId());
            joinDocumentTestStandard.setTestStandardId(documentTestStandard.getId());
            joinDocumentTestStandardMapper.insert(joinDocumentTestStandard);
        }
        return true;
    }
 
    @Override
    public boolean delDocTestStandardById(Long id) {
        DocumentTestStandard documentTestStandard = documentTestStandardMapper.selectById(id);
        Long docId = joinDocumentBomRoutingMapper.selectById(documentTestStandard.getDocBomId()).getDocumentId();
        //产出明细
        documentStandardParamMapper.delete(Wrappers.<DocumentStandardParam>lambdaQuery().eq(DocumentStandardParam::getTestStandardId, id));
        //删主表
        documentTestStandardMapper.deleteById(id);
        //删除工艺文件与检测标准关联表
        joinDocumentTestStandardMapper.delete(Wrappers.<JoinDocumentTestStandard>lambdaQuery().eq(JoinDocumentTestStandard::getTestStandardId, id));
        List<JoinDocumentTestStandard> joinDocumentTestStandardList = joinDocumentTestStandardMapper.selectList(Wrappers.<JoinDocumentTestStandard>lambdaQuery()
                .eq(JoinDocumentTestStandard::getDocumentId, docId));
        Document document = new Document();
        document.setId(docId);
        if(joinDocumentTestStandardList==null){
            document.setTestStandard(false);
        }
        baseMapper.updateById(doUpdateRealUser(document));
        return true;
    }
 
    @Override
    public R qryDocTestStandard(Long docBomId, Long routingOperationId) {
        List<DocumentTestStandard> documentTestStandardList = documentTestStandardMapper.selectList(Wrappers.<DocumentTestStandard>lambdaQuery().eq(DocumentTestStandard::getDocBomId, docBomId).eq(DocumentTestStandard::getRoutingOperationId, routingOperationId));
        return R.ok(documentTestStandardList);
    }
 
    @Override
    public R delDocTestStandardDetailById(Long id) {
        updateDocumentByStandardParamId(id);
        documentStandardParamMapper.deleteById(id);
        return R.ok();
    }
 
    @Override
    public R updDocTestStandardDetails(List<DocumentStandardParam> documentStandardParamList) {
        if (CollectionUtils.isEmpty(documentStandardParamList)) {
            return R.failed("提交数据为空");
        } else {
            for (DocumentStandardParam documentStandardParam : documentStandardParamList) {
                documentStandardParamMapper.updateById(documentStandardParam);
            }
            updateDocumentByStandardParamId(documentStandardParamList.get(0).getId());
            return R.ok();
        }
    }
 
    @Override
    public R qryDocTestStandardDetailsByStandardId(Long standardId) {
        List<DocumentStandardParam> documentStandardParamList = documentStandardParamMapper.selectList(Wrappers.<DocumentStandardParam>lambdaQuery().eq(DocumentStandardParam::getTestStandardId, standardId));
        return R.ok(documentStandardParamList);
    }
 
 
    @Override
    public boolean batchDel(List<Long> ids) {
        //验证是否可以删除
        List<Document> documentList = baseMapper.selectList(Wrappers.<Document>lambdaQuery()
                .eq(Document::getState, DocumentStateStringValues.ACCEPTED).in(Document::getId, ids));
        if (CollectionUtil.isNotEmpty(documentList)) {
            throw new RuntimeException("存在已接收工艺文件删除失败");
        }
        //删除对应检测标准数据
        List<JoinDocumentBomRouting> joinDocumentBomRoutingList = joinDocumentBomRoutingMapper.selectList(Wrappers.<JoinDocumentBomRouting>lambdaQuery()
                .in(JoinDocumentBomRouting::getDocumentId, ids));
        //删除中间表和检测标准
        delJoinAndTest(joinDocumentBomRoutingList);
        //删除工艺文件
        baseMapper.delete(Wrappers.<Document>lambdaQuery().in(Document::getId, ids));
        //删除检测标准关系
        joinDocumentTestStandardMapper.delete(Wrappers.<JoinDocumentTestStandard>lambdaQuery()
                .in(JoinDocumentTestStandard::getDocumentId, ids));
        //删除工艺文件物料信息
        documentMaterialCostMapper.delete(Wrappers.<DocumentMaterialCost>lambdaQuery()
                .in(DocumentMaterialCost::getDocumentId, ids));
        return true;
    }
 
 
    private void delJoinAndTest(List<JoinDocumentBomRouting> joinDocumentBomRoutingList) {
        if (CollectionUtil.isNotEmpty(joinDocumentBomRoutingList)) {
            //查询工艺文件中间表
            List<Long> jdbids = joinDocumentBomRoutingList.stream().map(JoinDocumentBomRouting::getId).collect(Collectors.toList());
            //工艺文件关联的检测标准
            List<DocumentTestStandard> documentTestStandardList = documentTestStandardMapper.selectList(Wrappers.<DocumentTestStandard>lambdaQuery()
                    .in(DocumentTestStandard::getDocBomId, jdbids));
            if (CollectionUtil.isNotEmpty(documentTestStandardList)) {
                //lambda 获取id
                List<Long> standardIds = documentTestStandardList.stream().map(DocumentTestStandard::getId).collect(Collectors.toList());
                //删除检测标准数据
                documentTestStandardMapper.deleteBatchIds(standardIds);
                documentStandardParamMapper.delete(Wrappers.<DocumentStandardParam>lambdaQuery().in(DocumentStandardParam::getTestStandardId, standardIds));
            }
            //删除关联关系
            joinDocumentBomRoutingMapper.deleteBatchIds(jdbids);
        }
    }
 
    private void delJoinAndTest(JoinDocumentBomRouting joinDocumentBomRouting) {
        if (null != joinDocumentBomRouting) {
            List<DocumentTestStandard> documentTestStandardList = documentTestStandardMapper.selectList(Wrappers.<DocumentTestStandard>lambdaQuery()
                    .eq(DocumentTestStandard::getDocBomId, joinDocumentBomRouting.getId()));
            if (CollectionUtil.isNotEmpty(documentTestStandardList)) {
                //lambda 获取id
                List<Long> standardIds = documentTestStandardList.stream().map(DocumentTestStandard::getId).collect(Collectors.toList());
                //删除检测标准数据
                documentTestStandardMapper.deleteBatchIds(standardIds);
                //删除子表
                documentStandardParamMapper.delete(Wrappers.<DocumentStandardParam>lambdaQuery().in(DocumentStandardParam::getTestStandardId, standardIds));
            }
        }
    }
 
    @Override
    public Document changeTestStandard(Long docBomId) {
        Long docId = joinDocumentBomRoutingMapper.selectById(docBomId).getDocumentId();
        Document document = new Document();
        document.setId(docId);
        document.setTestStandard(true);
        baseMapper.updateById(doUpdateRealUser(document));
        return document;
    }
 
 
    public void updateDocumentByStandardParamId(Long standardParamId){
        DocumentStandardParam documentStandardParam = documentStandardParamMapper
                .selectById(standardParamId);
        List<JoinDocumentTestStandard> joinDocumentTestStandardList = joinDocumentTestStandardMapper.selectList(Wrappers.<JoinDocumentTestStandard>lambdaQuery()
                .eq(JoinDocumentTestStandard::getTestStandardId, documentStandardParam.getTestStandardId()));
        Document document = new Document();
        document.setId(joinDocumentTestStandardList.get(0).getDocumentId());
        baseMapper.updateById(doUpdateRealUser(document));
    }
 
 
    public Document doUpdateRealUser(Document document){
        ZttUser currentUser = SecurityUtils.getUser();
        document.setUpdateRealUser(currentUser.getUsername());
        document.setUpdateRealTime(LocalDateTime.now());
        return document;
    }
 
    @Override
    public Boolean addDocSamplingRule(Long docBomId, Long routingOperationId, Long samplingRuleId, DocumentSamplingRule documentSamplingRule, String applyType) {
        if (samplingRuleId != null) {
            documentSamplingRule = documentSamplingRuleMapper.getSamplingRuleBySamplingRuleId(samplingRuleId);
            applyType = documentSamplingRule.getApplyType();
        }
 
        RoutingOperation routingOperation = routingOperationMapper.selectById(routingOperationId);
        DocumentSamplingRule currentDocumentSamplingRule = documentSamplingRuleMapper.selectOne(Wrappers.<DocumentSamplingRule>lambdaQuery()
                .eq(DocumentSamplingRule::getDocBomId, docBomId)
                .eq(DocumentSamplingRule::getSamplingOperationId, routingOperation.getOperationId())
                .eq(DocumentSamplingRule::getApplyType, applyType));
        if (currentDocumentSamplingRule == null) {
            // 查找是否配置了基础抽检规则
            if (documentSamplingRule != null) {
                documentSamplingRule.setDocBomId(docBomId);
                documentSamplingRule.setRoutingOperationId(routingOperationId);
                return SqlHelper.retBool(this.documentSamplingRuleMapper.insert(documentSamplingRule));
            }
        }
        return false;
    }
 
    @Override
    public List<DocumentSamplingRule> qryDocSamplingRule(Long docBomId, Long routingOperationId) {
        return this.documentSamplingRuleMapper.selectList(Wrappers.<DocumentSamplingRule>lambdaQuery()
                .eq(DocumentSamplingRule::getDocBomId, docBomId)
                .eq(DocumentSamplingRule::getRoutingOperationId, routingOperationId));
    }
 
    @Override
    public void export(HttpServletResponse response) throws IOException {
        //新建ExcelWriter
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("工艺文件检测标准导入模板", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //获取sheet0对象
            WriteSheet mainSheet = EasyExcel.writerSheet(0, "导入模板").head(DocumentTestStandardData.class).build();
            //向sheet0写入数据 传入空list这样只导出表头
            List<DocumentTestStandardData> list = new ArrayList<>();
            excelWriter.write(list, mainSheet);
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }
 
    @Override
    public void importExcel(List<DocumentTestStandardData> list) {
        if (CollectionUtil.isNotEmpty(list)) {
            Set<Long> docIds = new HashSet<>();
            for (DocumentTestStandardData standardData : list) {
                // 查找检测标准
                DocumentTestStandard standard = documentTestStandardMapper.getTestStandardByStandardNo(standardData.getStandardNo());
                if (standard == null) {
                    throw new RuntimeException("检测标准编号为:" + standardData.getStandardNo() + "的检测标准不存在");
                }
 
                // 查找工艺文件
                Document document = this.getOne(Wrappers.<Document>lambdaQuery().eq(Document::getNumber, standardData.getDocumentNo()));
                if (document == null) {
                    throw new RuntimeException("工艺文件编号为:" + standardData.getDocumentNo() + "的工艺文件不存在");
                }
                docIds.add(document.getId());
 
                // 查找工艺路线
                Routing routing = routingMapper.selectOne(Wrappers.<Routing>lambdaQuery().eq(Routing::getRoutingNo, standardData.getRoutingNo()));
                if (routing == null) {
                    throw new RuntimeException("工艺路线编号为:" + standardData.getRoutingNo() + "的工艺路线不存在");
                }
 
                // 查找工序
                Operation operation = operationMapper.selectOne(Wrappers.<Operation>lambdaQuery().eq(Operation::getOperationNo, standardData.getOperationNo()));
                if (operation == null) {
                    throw new RuntimeException("工序编号为:" + standardData.getOperationNo() + "的工序不存在");
                }
 
                // 查找零件
                Part part = partMapper.selectOne(Wrappers.<Part>lambdaQuery().eq(Part::getPartNo, standardData.getPartNo()));
                if (part == null) {
                    throw new RuntimeException("零件编号为:" + standardData.getPartNo() + "的零件不存在");
                }
 
                // 查找工艺文件与工艺、BOM关系表数据
                JoinDocumentBomRouting joinDocumentBomRouting = joinDocumentBomRoutingMapper.selectOne(Wrappers.<JoinDocumentBomRouting>lambdaQuery()
                        .eq(JoinDocumentBomRouting::getDocumentId, document.getId())
                        .eq(JoinDocumentBomRouting::getRoutingId, routing.getId())
                        .eq(JoinDocumentBomRouting::getPartId, part.getId()));
                if (joinDocumentBomRouting == null) {
                    throw new RuntimeException("工艺文件编号为:" + standardData.getDocumentNo() + "的工艺文件,工艺路线编号为:" + standardData.getRoutingNo() + "的工艺路线,零件编号为:" + standardData.getPartNo() + "的BOM结构不存在");
                }
 
                // 查找工艺工序
                RoutingOperation routingOperation = routingOperationMapper.selectOne(Wrappers.<RoutingOperation>lambdaQuery()
                        .eq(RoutingOperation::getRoutingId, routing.getId())
                        .eq(RoutingOperation::getOperationId, operation.getId()));
                if (routingOperation == null) {
                    throw new RuntimeException("工艺路线编号为:" + standardData.getRoutingNo() + "的工艺路线,工序编号为:" + standardData.getOperationNo() + "的工序,零件编号为:" + standardData.getPartNo() + "的工艺工序不存在");
                }
 
                // 查找是否已经绑定过相同检测标准
                int count = documentTestStandardMapper.selectCount(Wrappers.<DocumentTestStandard>lambdaQuery()
                        .eq(DocumentTestStandard::getDocBomId, joinDocumentBomRouting.getId())
                        .eq(DocumentTestStandard::getRoutingOperationId, routingOperation.getId())
                        .eq(DocumentTestStandard::getStandardNo, standard.getStandardNo()));
                if (count > 0) {
                    continue;
                }
 
                String testType = standard.getInspectionType();
                boolean isFinishedProduct = testType.equals("06finishedproduct");
                // 检测标准那边导入有问题,没有把name转成code
                List<DocumentStandardParam> documentStandardParamList = documentStandardParamMapper.getDocumentStandardParamListByStandardId(standard.getId());
                standard.setDocBomId(joinDocumentBomRouting.getId());// 工艺文件与bom关系表id
                standard.setRoutingOperationId(routingOperation.getId());// 工艺工序id
                documentTestStandardMapper.insert(standard);
                for (DocumentStandardParam documentStandardParam : documentStandardParamList) {
                    documentStandardParam.setTestStandardId(standard.getId());// 主表id
                    if (BooleanUtil.isTrue(documentStandardParam.getIsReference())) {
                        // 成品检的引用池范围:工艺文件中所有工艺路线下所有工序对应的工序参数;其他检引用池范围:该工序下的工艺参数
                        // 若引用工艺参数,则根据参数编号判断工艺项是否存在
                        String paramValue;
                        if (isFinishedProduct) {
                            paramValue = technologyUtils.getRoutingOperationParamValueFinishedproduct(joinDocumentBomRouting.getId(), routingOperation.getId(), documentStandardParam.getCode(), documentStandardParam.getWireCore());
                        } else {
                            paramValue = technologyUtils.getRoutingOperationParamValue(joinDocumentBomRouting.getId(), routingOperation.getId(), documentStandardParam.getCode());
                        }
                        if (paramValue != null) {
                            documentStandardParam.setReferenceValue(paramValue);// 取到有效值后才引用
                        }
                    }
                    documentStandardParamMapper.insert(documentStandardParam);
                }
 
                JoinDocumentTestStandard joinDocumentTestStandard = new JoinDocumentTestStandard();
                joinDocumentTestStandard.setDocumentId(document.getId());
                joinDocumentTestStandard.setTestStandardId(standard.getId());
                joinDocumentTestStandardMapper.insert(joinDocumentTestStandard);
            }
            if (docIds.size() > 0) {
                this.update(Wrappers.<Document>lambdaUpdate().set(Document::getTestStandard, true).in(Document::getId, docIds));
            }
        }
    }
}