lyh
2 天以前 b508ec38ddf9ed93d4435e8f1e3c4effef798aaa
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
package com.lxzn.webservice.impl;
 
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lxzn.activiti.service.IAssignFileStreamService;
import com.lxzn.framework.domain.activiti.response.ActivitiCode;
import com.lxzn.framework.domain.filesystem.response.FileUploadResult;
import com.lxzn.framework.domain.nc.*;
import com.lxzn.framework.domain.nc.response.DocumentCode;
import com.lxzn.framework.domain.webservice.DispatchInfo;
import com.lxzn.framework.domain.webservice.PlmProgramSourceInfo;
import com.lxzn.framework.domain.webservice.ProcedureFinish;
import com.lxzn.framework.domain.webservice.request.*;
import com.lxzn.framework.exception.ExceptionCast;
import com.lxzn.framework.model.response.CommonCode;
import com.lxzn.framework.utils.CxfClientUtil;
import com.lxzn.framework.utils.HttpRequest;
import com.lxzn.framework.utils.ValidateUtil;
import com.lxzn.framework.utils.ZipUtil;
import com.lxzn.framework.utils.file.FileUtil;
import com.lxzn.nc.service.*;
import com.lxzn.nc.service.impl.DeviceInfoServiceImpl;
import com.lxzn.webservice.DncWebService;
import com.lxzn.webservice.ext.MesResultModel;
import com.lxzn.webservice.service.IDispatchInfoService;
import com.lxzn.webservice.service.IPlmProgramSourceInfoService;
import com.lxzn.webservice.service.IProcedureFinishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
 
/**
 * @Author: Lius
 * @CreateTime: 2025-02-27
 * @Description:
 */
@Service
//@WebService(name = "DncWebService",
//        targetNamespace = "http://lxzn.webservice.com",
//        endpointInterface = "com.lxzn.webservice.DncWebService"
//)
@Slf4j
public class DncWebServiceImpl implements DncWebService {
    @Resource
    private IPlmProgramSourceInfoService iPlmProgramSourceInfoService;
    @Autowired
    private IProductInfoService productInfoService;
    @Autowired
    private IComponentInfoService componentInfoService;
    @Autowired
    private IPermissionStreamService permissionStreamService;
    @Autowired
    private IComponentDepartmentService componentDepartmentService;
    @Autowired
    private IComponentPermissionService componentPermissionService;
    @Autowired
    private IPartsInfoService partsInfoService;
    @Autowired
    private IPartsDepartmentService partsDepartmentService;
    @Autowired
    private IPartsPermissionService partsPermissionService;
    @Autowired
    private IProcessStreamService processStreamService;
    @Autowired
    private IDocInfoService docInfoService;
    @Autowired
    private IDocRelativeService docRelativeService;
    @Autowired
    private IDocFileService docFileService;
    @Autowired
    private IDocClassificationService docClassificationService;
    @Autowired
    private IDeviceManagementService deviceManagementService;
    @Autowired
    private DeviceInfoServiceImpl deviceInfoService;
    @Autowired
    private IDeviceGroupService deviceGroupService;
    /**
     * 获取NC文件及属性信息(集成PLM)
     *
     * @param msg
     * @return
     */
    @WebMethod
    @Override
    @Transactional
    public MesResultModel syncPlmNcLogProgram(@WebParam(name = "msg") String msg) {
        log.info("NC文件及属性信息原始数据 === {}", msg);
        List<PlmProgramSource> plmProgramSourceList = JSONObject.parseArray(msg, PlmProgramSource.class);
        AtomicReference<MesResultModel> mesResultModel= new AtomicReference<>(new MesResultModel());
        plmProgramSourceList.forEach(item -> {
            mesResultModel.set(setPlmTree(item));
        });
        return mesResultModel.get();
    }
 
    /**
     * 封装树结构
     1. 产品 集成数据
     2、部件 按照部门(车间 ae8nc_plant )维度建立
     3、零件 图号(零件号、零件名称) ae8part_no
     4、工序  工艺ID(工艺规程编号/临规编号)
     5. nc文件 (工序下)
     6.机床型号与机床操作系统组成设备类与工序进行绑定
     * @param plmProgramSource
     * @return
     */
    public MesResultModel setPlmTree(PlmProgramSource plmProgramSource) {
        MesResultModel model = new MesResultModel();
        model.setSuccFlag("成功");
        PlmProgramSourceInfo plmProgramSourceInfo = new PlmProgramSourceInfo();
        BeanUtils.copyProperties(plmProgramSource, plmProgramSourceInfo);
        plmProgramSourceInfo.setMesStatus("0");
        iPlmProgramSourceInfoService.save(plmProgramSourceInfo);
        // 产品
        ProductInfo productInfo = productInfoService.getByProductNo("PLM");
        if (productInfo == null) {
            log.error("======= 产品层级异常,请联系开发人员=======");
            return createErrorModel(model, "产品层级异常,请联系开发人员");
        }
 
        // 部件
        ComponentInfo compTotal = componentInfoService.getByCode(plmProgramSourceInfo.getCzkAe8nDivision());
        if (compTotal == null) {
            compTotal = new ComponentInfo();
            compTotal.setComponentCode(plmProgramSourceInfo.getCzkAe8nDivision());
            compTotal.setProductId(productInfo.getProductId());
            compTotal.setComponentName(plmProgramSourceInfo.getCzkAe8nDivision());
            compTotal.setComponentStatus(1);
            compTotal.setRankLevel(1);
            compTotal.setParentId(productInfo.getProductId());
            compTotal.setComponentId(IdWorker.getIdStr());
 
            if (!componentInfoService.save(compTotal)) {
                return createErrorModel(model, "添加部件层级,请联系开发人员");
            }
 
            if (!savePermissionList(compTotal, productInfo.getProductId())) {
                return createErrorModel(model, "添加权限失败,请联系开发人员");
            }
        }
 
        // 3、零件 图号(零件号) ae8part_no
        PartsInfo part = partsInfoService.getByCode(plmProgramSourceInfo.getCzkAe8nPartNo());
        if (part == null) {
            List<PartsDepartment> partsDepartPermList = new ArrayList<>();
            List<PermissionStream> partsPermList = new ArrayList<>();
            List<PartsPermission> partsUserPermList = new ArrayList<>();
 
            part = new PartsInfo();
            part.setPartsId(IdWorker.getIdStr());
            part.setComponentId(compTotal.getComponentId());
            part.setProductId(compTotal.getProductId());
            part.setPartsStatus(1);
            part.setPartsCode(plmProgramSourceInfo.getCzkAe8nPartNo());
            part.setPartsName(plmProgramSourceInfo.getCzkAe8nPartName());
            part.setPartsModel(plmProgramSourceInfo.getCzkAe8nPartNo());
 
            if (!partsInfoService.save(part)) {
                return createErrorModel(model, "添加零件层级,请联系开发人员");
            }
 
            // 权限
            List<PermissionStream> oldPermissionList = permissionStreamService.getAllByProductId(productInfo.getProductId());
            if (oldPermissionList != null && !oldPermissionList.isEmpty()) {
                for (PermissionStream p : oldPermissionList) {
                    if (ValidateUtil.validateString(p.getUserId())) {
                        // 用户权限
                        PartsPermission permission = new PartsPermission();
                        permission.setPartsId(part.getPartsId());
                        permission.setUserId(p.getUserId());
                        partsUserPermList.add(permission);
 
                        PermissionStream stream = new PermissionStream();
                        stream.setUserId(p.getUserId());
                        stream.setProductId(part.getProductId());
                        stream.setComponentId(part.getComponentId());
                        stream.setPartsId(part.getPartsId());
                        partsPermList.add(stream);
                    }
 
                    if (ValidateUtil.validateString(p.getDepartId())) {
                        // 部门权限
                        PartsDepartment department = new PartsDepartment();
                        department.setPartsId(part.getPartsId());
                        department.setDepartId(p.getDepartId());
                        partsDepartPermList.add(department);
 
                        PermissionStream stream = new PermissionStream();
                        stream.setProductId(part.getProductId());
                        stream.setComponentId(part.getComponentId());
                        stream.setPartsId(part.getPartsId());
                        stream.setDepartId(p.getDepartId());
                        partsPermList.add(stream);
                    }
                }
 
                if (!partsUserPermList.isEmpty() && !partsPermissionService.saveBatch(partsUserPermList)) {
                    return createErrorModel(model, "添加权限失败,请联系开发人员");
                }
 
                if (!partsDepartPermList.isEmpty() && !partsDepartmentService.saveBatch(partsDepartPermList)) {
                    return createErrorModel(model, "添加权限失败,请联系开发人员");
                }
 
                if (!partsPermList.isEmpty() && !permissionStreamService.saveBatch(partsPermList)) {
                    return createErrorModel(model, "添加权限失败,请联系开发人员");
                }
            }
        }
 
        // 4、工序  工艺ID(工艺规程编号/临规编号)
        List<ProcessStream> addProcessList = new ArrayList<>();
        List<ProcessStream> updateProcessList = new ArrayList<>();
        ProcessStream stream; // skgx_id
        String processCode = plmProgramSourceInfo.getCzkAe8nOpNo();
 
        stream = processStreamService.findByProcessNoAndPartsId(processCode, part.getPartsId());
        if (stream == null) {
            stream = new ProcessStream();
            stream.setProcessId(IdWorker.getIdStr());
            stream.setProductId(part.getProductId());
            stream.setComponentId(part.getComponentId());
            stream.setCraftVersion(plmProgramSourceInfo.getCzkAe8nOpRev());
            stream.setPartsId(part.getPartsId());
            stream.setProcessCode(processCode);
            stream.setProcessName(plmProgramSourceInfo.getCzkAe8nOpName());
            /*数控工序号*/
            stream.setCraftNo(plmProgramSourceInfo.getCzkAe8nOpNo());
            /*机床操作系统  ae8nc_os*/
            DeviceManagement deviceManagement = deviceManagementService.findEquipmentIdsFromEqId(
                    plmProgramSourceInfo.getCzkAe8nDivision(), plmProgramSourceInfo.getCzkAe8nEquipNo());
            if (deviceManagement != null && StringUtils.isNotEmpty(deviceManagement.getEquipmentIds())) {
                stream.setProcessingEquipmentCode(deviceManagement.getEquipmentIds());
            } else {
                stream.setProcessingEquipmentCode(plmProgramSourceInfo.getCzkAe8nEquipNo());
            }
            stream.setProcessingEquipmentOs(plmProgramSourceInfo.getCzkAe8nEquipsystem());
            stream.setProcessingEquipmentModel(plmProgramSourceInfo.getCzkAe8nEquipmentModel());
            addProcessList.add(stream);
        } else {
            stream.setProcessName(plmProgramSourceInfo.getCzkAe8nOpName());
            updateProcessList.add(stream);
 
        }
 
        if (!addProcessList.isEmpty() && !processStreamService.saveBatch(addProcessList)) {
            return createErrorModel(model, "添加工序,请联系开发人员");
        }
 
        if (!updateProcessList.isEmpty() && !processStreamService.updateBatchById(updateProcessList)) {
            return createErrorModel(model, "更新工序,请联系开发人员");
        }
 
        // 下载数据并解压
        DocClassification docClass = docClassificationService.getByCode("NC");
        if (docClass == null) {
            return createErrorModel(model, "下载数据并解压数据失败,请联系开发人员");
        }
        boolean b;
        try {
                File file = new File(plmProgramSource.getFileName());
                if(file.exists() && file.isFile() && file.length() > 0) {
                    if(plmProgramSource.getFiles() == null || plmProgramSource.getFiles().isEmpty()) {
                        ExceptionCast.cast(CommonCode.FAIL);
                    }
                    for(Map.Entry<String,byte[]> entry : plmProgramSource.getNcfiles().entrySet()) {
                        String suffix = FileUtil.getFileSuffix(entry.getKey());
                        DocInfo docInfo = docInfoService.findByAttrAndDocName(FileUtil.getFilenameNonSuffix(entry.getKey()), 5,
                                stream.getProcessId(),suffix);
                        //新增
                        FileUploadResult fileUploadResult = FileUtil.uploadFileByFileNameAndFis(entry.getKey(),new ByteArrayInputStream(entry.getValue()));
                        if(fileUploadResult == null) {
                            ExceptionCast.cast(DocumentCode.DOC_UPLOAD_ERROR);
                        }
                        if(docInfo == null) {
                            docInfo = new DocInfo();
                            String docId = IdWorker.getIdStr();
                            docInfo.setDocId(docId);
                            docInfo.setDocName(fileUploadResult.getFileName());
                            docInfo.setDocSuffix(fileUploadResult.getFileSuffix());
                            if (StrUtil.isNotEmpty(plmProgramSourceInfo.getCzkReleaseStatus())){
                                docInfo.setDocStatus(5);
                            }else {
                                docInfo.setDocStatus(4);
                            }
                            DocRelative docRelative = new DocRelative();
                            docRelative.setAttributionId(stream.getProcessId());
                            docRelative.setDocId(docInfo.getDocId());
                            docRelative.setAttributionType(5);
                            docRelative.setClassificationId(docClass.getClassificationId());
                            b = docRelativeService.save(docRelative);
                            if(!b) {
                                return createErrorModel(model, "添加文件,请联系开发人员");
                            }
                            if (getFile(docInfo, fileUploadResult, docFileService)) {
                                return createErrorModel(model, "添加文件,请联系开发人员");
                            }
                            b =  docInfoService.save(docInfo);
                        }else {
                            if (StringUtils.isNotEmpty(stream.getCraftVersion())&&StringUtils.isNotEmpty(plmProgramSource.getCzkAe8nOpRev())) {
                                //升版,保存原文件
                                if (!stream.getCraftVersion().equals(plmProgramSource.getCzkAe8nOpRev())) {
                                    this.createFileOldNcPathAndCopy(docInfo,plmProgramSourceInfo);
                                }
                            }
                            DocFile docFile = getDocFile(docInfo, fileUploadResult);
                            b = docFileService.addDocFile(docFile);
                            if(!b){
                                return createErrorModel(model, "升版失败,请联系开发人员");
                            }
                            docInfo.setPublishVersion(docFile.getDocVersion());
                            docInfo.setPublishFileId(docFile.getFileId());
                            b = docInfoService.updateById(docInfo);
                        }
                        if(!b){
                            return createErrorModel(model, "添加文件,请联系开发人员");
                        }
                    }
                    return model;
                }
        } catch (Exception e) {
            log.error(e.getMessage());
            model.setSuccFlag("失败");
            model.setError("下载数据并解压数据失败,请联系开发人员");
            return model;
        }
        return model;
    }
 
    /**
     * 封装树结构
     * 1. 产品 集成数据
     * 2、部件 按照部门(车间 nc_plant_name )维度建立
     * 3、零件 图号(零件号、零件名称) part_no
     * 4、工序  工艺ID(工艺规程编号/临规编号)
     * 5. nc文件 (工序下)
     * 6.机床型号与机床操作系统组成设备类与工序进行绑定
     * 集成3DE挂树
     * @param thirdDeProgramSource
     * @return
     */
    @Override
    @Transactional
    public MesResultModel processThirdDEProgram(ThirdDeProgramSource thirdDeProgramSource) {
        MesResultModel model = new MesResultModel();
        model.setSuccFlag("成功");
 
        try {
            log.info("3DE NC文件及属性信息原始数据 === {}", JSONObject.toJSONString(thirdDeProgramSource));
 
            // 产品 - 使用默认的3DE产品
            ProductInfo productInfo = productInfoService.getByProductNo("3DE");
            if (productInfo == null) {
                return createErrorModel(model, "3DE产品层级异常,请联系开发人员");
            }
 
            // 部件 - 按照车间维度建立
            ComponentInfo componentInfo = componentInfoService.getByCode(thirdDeProgramSource.getNcPlantNo());
            if (componentInfo == null) {
                componentInfo = new ComponentInfo();
                componentInfo.setComponentId(IdWorker.getIdStr());
                componentInfo.setComponentCode(thirdDeProgramSource.getNcPlantNo());
                componentInfo.setComponentName(thirdDeProgramSource.getNcPlantName());
                componentInfo.setComponentStatus(1);
                componentInfo.setRankLevel(1);
                componentInfo.setParentId(productInfo.getProductId());
                componentInfo.setProductId(productInfo.getProductId());
 
                if (!componentInfoService.save(componentInfo)) {
                    return createErrorModel(model, "添加3DE部件层级失败,请联系开发人员");
                }
                if (!savePermissionList(componentInfo, productInfo.getProductId())) {
                    return createErrorModel(model, "添加3DE部件权限失败,请联系开发人员");
                }
            }
 
            // 零件 - 图号(零件号、零件名称)
            PartsInfo partsInfo = partsInfoService.getByCode(thirdDeProgramSource.getPartNo());
            if (partsInfo == null) {
                partsInfo = new PartsInfo();
                partsInfo.setPartsId(IdWorker.getIdStr());
                partsInfo.setComponentId(componentInfo.getComponentId());
                partsInfo.setProductId(productInfo.getProductId());
                partsInfo.setPartsStatus(1);
                partsInfo.setPartsCode(thirdDeProgramSource.getPartNo());
                partsInfo.setPartsName(thirdDeProgramSource.getPartName());
                partsInfo.setPartsModel(thirdDeProgramSource.getPartNo());
 
                if (!partsInfoService.save(partsInfo)) {
                    return createErrorModel(model, "添加3DE零件层级失败,请联系开发人员");
                }
                // 添加零件权限
                if (!savePartsPermission(partsInfo, productInfo.getProductId())) {
                    return createErrorModel(model, "添加3DE零件权限失败,请联系开发人员");
                }
            }
 
            // 工序 - 工艺ID(工艺规程编号/临规编号)
            ProcessStream processStream = processStreamService.findByProcessNoAndPartsId(
                    thirdDeProgramSource.getSkgxId(), partsInfo.getPartsId());
            List<ProcessStream> addProcessList = new ArrayList<>();
            List<ProcessStream> updateProcessList = new ArrayList<>();
 
            if (processStream == null) {
                processStream = new ProcessStream();
                processStream.setProcessId(IdWorker.getIdStr());
                processStream.setProductId(productInfo.getProductId());
                processStream.setComponentId(componentInfo.getComponentId());
                processStream.setPartsId(partsInfo.getPartsId());
                processStream.setProcessCode(thirdDeProgramSource.getSkgxId());
                processStream.setProcessName(thirdDeProgramSource.getSkgxName());
                processStream.setCraftVersion(thirdDeProgramSource.getRevisionNo()); // 设置工艺版本
 
                // 设备信息处理
                DeviceManagement deviceManagement = deviceManagementService.findEquipmentIdsFromEqId(
                        thirdDeProgramSource.getNcPlantName(), thirdDeProgramSource.getEquipmentId());
 
                if (deviceManagement != null && StringUtils.isNotEmpty(deviceManagement.getEquipmentIds())) {
                    processStream.setProcessingEquipmentCode(deviceManagement.getEquipmentIds());
                } else {
                    processStream.setProcessingEquipmentCode(thirdDeProgramSource.getEquipmentId());
                }
                processStream.setProcessingEquipmentOs(thirdDeProgramSource.getNcOs());
                processStream.setProcessingEquipmentModel(thirdDeProgramSource.getNcJcid());
                addProcessList.add(processStream);
            } else {
                // 更新时检查版本是否变更
                if (!Objects.equals(processStream.getCraftVersion(), thirdDeProgramSource.getRevisionNo())) {
                    processStream.setCraftVersion(thirdDeProgramSource.getRevisionNo());
                }
                processStream.setProcessName(thirdDeProgramSource.getSkgxName());
                updateProcessList.add(processStream);
            }
 
            if (!addProcessList.isEmpty() && !processStreamService.saveBatch(addProcessList)) {
                return createErrorModel(model, "添加3DE工序失败,请联系开发人员");
            }
 
            if (!updateProcessList.isEmpty() && !processStreamService.updateBatchById(updateProcessList)) {
                return createErrorModel(model, "更新3DE工序失败,请联系开发人员");
            }
 
            // 文档分类
            DocClassification ncDocClass = docClassificationService.getByCode("NC");
            if (ncDocClass == null) {
                return createErrorModel(model, "NC文档分类不存在,请联系开发人员");
            }
 
            // send文档分类
            DocClassification sendDocClass = docClassificationService.getByCode("SEND");
            if (sendDocClass == null) {
                return createErrorModel(model, "SEND文档分类不存在,请联系开发人员");
            }
 
            // 处理NC文件
            if (thirdDeProgramSource.getNcFiles() != null && !thirdDeProgramSource.getNcFiles().isEmpty()) {
                for (Map.Entry<String, byte[]> entry : thirdDeProgramSource.getNcFiles().entrySet()) {
                    String fileName = entry.getKey();
                    byte[] fileContent = entry.getValue();
                    String suffix = FileUtil.getFileSuffix(fileName);
                    String baseName = FileUtil.getFilenameNonSuffix(fileName);
 
                    // 查找现有文档
                    DocInfo docInfo = docInfoService.findByAttrAndDocName(baseName, 5,
                            processStream.getProcessId(), suffix);
 
                    FileUploadResult fileUploadResult = FileUtil.uploadFileByFileNameAndFis(
                            fileName, new ByteArrayInputStream(fileContent));
 
                    if (fileUploadResult == null) {
                        return createErrorModel(model, "上传3DE NC文件失败");
                    }
 
                    boolean success;
                    if (docInfo == null) {
                        // 新增文档
                        docInfo = new DocInfo();
                        String docId = IdWorker.getIdStr();
                        docInfo.setDocId(docId);
                        docInfo.setDocName(fileUploadResult.getFileName());
                        docInfo.setDocSuffix(fileUploadResult.getFileSuffix());
                        docInfo.setDocStatus(5);
 
                        // 创建文档关联
                        DocRelative docRelative = new DocRelative();
                        docRelative.setAttributionId(processStream.getProcessId());
                        docRelative.setDocId(docInfo.getDocId());
                        docRelative.setAttributionType(5);
                        docRelative.setClassificationId(ncDocClass.getClassificationId());
 
                        if (!docRelativeService.save(docRelative)) {
                            return createErrorModel(model, "创建3DE文档关联失败");
                        }
 
                        // 保存文档文件
                        if (getFile(docInfo, fileUploadResult, docFileService)) {
                            return createErrorModel(model, "保存3DE文档文件失败");
                        }
 
                        success = docInfoService.save(docInfo);
 
                        // 获取最新文档文件
                        DocFile docFile = docFileService.getDocFileNearest(docId);
 
                        // 添加到设备
                        if (!linkToDevice(thirdDeProgramSource.getEquipmentId(), docInfo.getDocId(), docFile, sendDocClass)) {
                            return createErrorModel(model, "添加设备文档关联失败");
                        }
                    } else {
                        // 更新文档 - 处理版本控制
                        if (StringUtils.isNotEmpty(processStream.getCraftVersion()) &&
                                StringUtils.isNotEmpty(thirdDeProgramSource.getRevisionNo())) {
                            // 版本变更,保存旧版本文件
                            if (!Objects.equals(processStream.getCraftVersion(), thirdDeProgramSource.getRevisionNo())) {
                                this.createFileOldNcPathAndCopyFor3DE(docInfo, thirdDeProgramSource);
                            }
                        }
 
                        DocFile docFile = getDocFile(docInfo, fileUploadResult);
                        success = docFileService.addDocFile(docFile);
 
                        if (success) {
                            docInfo.setPublishVersion(docFile.getDocVersion());
                            docInfo.setPublishFileId(docFile.getFileId());
                            success = docInfoService.updateById(docInfo);
 
                            // 更新设备关联
                            if (!updateDeviceLink(thirdDeProgramSource.getEquipmentId(), docInfo.getDocId(), sendDocClass)) {
                                return createErrorModel(model, "更新设备文档关联失败");
                            }
                        }
                    }
 
                    if (!success) {
                        return createErrorModel(model, "处理3DE NC文件失败");
                    }
                }
            }
 
            return model;
        } catch (Exception e) {
            log.error("处理3DE程序数据异常: {}", e.getMessage(), e);
            return createErrorModel(model, "处理3DE程序数据异常: " + e.getMessage());
        }
    }
 
    /**
     * 添加到设备
     */
    private boolean linkToDevice(String equipmentId, String docId, DocFile docFile, DocClassification sendDocClass) {
        try {
            DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(equipmentId);
            if (deviceInfo == null) {
                log.error("DNC中设备不存在: {}", equipmentId);
                return false;
            }
            DocRelative deviceDocRelative = new DocRelative();
            deviceDocRelative.setAttributionId(deviceInfo.getDeviceId());
            deviceDocRelative.setDocId(docId);
            deviceDocRelative.setAttributionType(4);
            deviceDocRelative.setClassificationId(sendDocClass.getClassificationId());
            boolean saved = docRelativeService.save(deviceDocRelative);
            if (!saved) {
                log.error("保存设备文档关联失败: device={}, doc={}", equipmentId, docId);
                return false;
            }
            // 复制文件到设备路径
            List<String> groupPaths = deviceGroupService.findListParentTreeAll(deviceInfo.getGroupId());
            if (groupPaths != null && !groupPaths.isEmpty()) {
                String devicePath = String.join("/", groupPaths) + "/" + deviceInfo.getDeviceNo();
                // 复制文件
                boolean copySuccess = FileUtil.copyFileNc(
                        docFile.getFilePath(),
                        devicePath,
                        docFile.getFileEncodeName(),
                        docFile.getFileName(),
                        docFile.getFileSuffix());
 
                if (!copySuccess) {
                    log.error("文件复制失败: {} -> {}", docFile.getFilePath(), devicePath);
                    return false;
                }
 
                // 删除旧版本文件
                FileUtil.deleteZipFromToSend(
                        devicePath,
                        docFile.getFileName(),
                        docFile.getFileSuffix());
            }
 
            return true;
        } catch (Exception e) {
            log.error("添加设备文档关联异常: {}", e.getMessage(), e);
            return false;
        }
    }
 
    /**
     * 更新设备关联
     */
    private boolean updateDeviceLink(String equipmentId, String docId, DocClassification sendDocClass) {
        try {
            DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(equipmentId);
            if (deviceInfo == null) {
                log.error("DNC中设备不存在: {}", equipmentId);
                return false;
            }
 
            // 检查关联是否已存在
            DocRelative existingRel = docRelativeService.findDocRelative(docId,sendDocClass.getClassificationId(), 4,deviceInfo.getDeviceId());
            if (existingRel == null) {
                // 创建新关联
                DocRelative deviceDocRelative = new DocRelative();
                deviceDocRelative.setAttributionId(deviceInfo.getDeviceId());
                deviceDocRelative.setDocId(docId);
                deviceDocRelative.setAttributionType(4);
                deviceDocRelative.setClassificationId(sendDocClass.getClassificationId());
                return docRelativeService.save(deviceDocRelative);
            }
            return true;
        } catch (Exception e) {
            log.error("更新设备关联异常: {}", e.getMessage(), e);
            return false;
        }
    }
 
    /**
     * 为3DE数据创建旧版本NC文件备份
     */
    private boolean createFileOldNcPathAndCopyFor3DE(DocInfo docInfo, ThirdDeProgramSource thirdDeProgramSource) {
        DocFile docFile = docFileService.getDocFileNearest(docInfo.getDocId());
        if (docFile == null) {
            log.error("未找到最近版本的3DE文档文件,docId: {}", docInfo.getDocId());
            return false;
        }
        String directoryPath = String.join(File.separator,
                "3de_bak",
                thirdDeProgramSource.getNcPlantName(),
                thirdDeProgramSource.getPartNo(),
                thirdDeProgramSource.getSkgxId(),
                "");
 
        File directory = new File(directoryPath);
        if (!directory.exists() && !directory.mkdirs()) {
            log.error("创建3DE目录失败: {}", directoryPath);
            return false;
        }
 
        // 构建目标文件路径
        String targetFileName = buildTargetFileName(docFile);
        String targetFilePath = directoryPath + targetFileName;
 
        try {
            Path sourcePath = Paths.get(docFile.getFilePath());
            Path targetPath = Paths.get(targetFilePath);
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            log.info("3DE文件复制成功: {} -> {}", docFile.getFilePath(), targetFilePath);
            return true;
        } catch (IOException e) {
            log.error("3DE文件复制失败: {}", e.getMessage(), e);
            if (directory.exists() && isDirectoryEmpty(directory)) {
                directory.delete();
            }
            return false;
        }
    }
 
    /**
     * 保存零件权限
     */
    private boolean savePartsPermission(PartsInfo partsInfo, String productId) {
        List<PermissionStream> oldPermissionList = permissionStreamService.getAllByProductId(productId);
        if (CollectionUtils.isEmpty(oldPermissionList)) {
            return true;
        }
 
        List<PartsDepartment> partsDepartPermList = new ArrayList<>();
        List<PermissionStream> partsPermList = new ArrayList<>();
        List<PartsPermission> partsUserPermList = new ArrayList<>();
 
        for (PermissionStream p : oldPermissionList) {
            if (ValidateUtil.validateString(p.getUserId())) {
                // 用户权限
                PartsPermission permission = new PartsPermission();
                permission.setPartsId(partsInfo.getPartsId());
                permission.setUserId(p.getUserId());
                partsUserPermList.add(permission);
 
                PermissionStream stream = new PermissionStream();
                stream.setUserId(p.getUserId());
                stream.setProductId(partsInfo.getProductId());
                stream.setComponentId(partsInfo.getComponentId());
                stream.setPartsId(partsInfo.getPartsId());
                partsPermList.add(stream);
            }
 
            if (ValidateUtil.validateString(p.getDepartId())) {
                // 部门权限
                PartsDepartment department = new PartsDepartment();
                department.setPartsId(partsInfo.getPartsId());
                department.setDepartId(p.getDepartId());
                partsDepartPermList.add(department);
 
                PermissionStream stream = new PermissionStream();
                stream.setProductId(partsInfo.getProductId());
                stream.setComponentId(partsInfo.getComponentId());
                stream.setPartsId(partsInfo.getPartsId());
                stream.setDepartId(p.getDepartId());
                partsPermList.add(stream);
            }
        }
 
        boolean success = true;
        if (!partsUserPermList.isEmpty()) {
            success = success && partsPermissionService.saveBatch(partsUserPermList);
        }
        if (!partsDepartPermList.isEmpty()) {
            success = success && partsDepartmentService.saveBatch(partsDepartPermList);
        }
        if (!partsPermList.isEmpty()) {
            success = success && permissionStreamService.saveBatch(partsPermList);
        }
 
        return success;
    }
 
    private MesResultModel createErrorModel(MesResultModel model, String errorMsg) {
        model.setSuccFlag("失败");
        model.setError(errorMsg);
        return model;
    }
 
    /**
     * 创建升版文件保存地址并复制文件
     * 层级结构: plm_bak->ae8ncPlant(车间)->ae8partNo(零件图号)->skgxId(工序)->具体文件
     * @param docInfo 文档信息
     * @param plmProgramSourceInfo 程序源信息
     * @return 操作成功返回true,失败返回false
     */
    public boolean createFileOldNcPathAndCopy(DocInfo docInfo, PlmProgramSourceInfo plmProgramSourceInfo) {
        // 获取最近版本的文档文件
        DocFile docFile = docFileService.getDocFileNearest(docInfo.getDocId());
        if (docFile == null) {
            log.error("未找到最近版本的文档文件,docId: {}", docInfo.getDocId());
            return false;
        }
 
        // 构建保存路径
        String directoryPath = String.join(File.separator,
                "plm_bak",
                plmProgramSourceInfo.getCzkAe8nDivision(),
                plmProgramSourceInfo.getCzkAe8nPartNo(),
                plmProgramSourceInfo.getCzkAe8nOpNo(),
                ""); // 末尾添加分隔符
 
        File directory = new File(directoryPath);
 
        // 创建目录(如果不存在)
        if (!directory.exists() && !directory.mkdirs()) {
            log.error("创建目录失败: {}", directoryPath);
            return false;
        }
 
        // 构建目标文件路径
        String targetFileName = buildTargetFileName(docFile);
        String targetFilePath = directoryPath + targetFileName;
 
        // 复制源文件到目标路径
        try {
            Path sourcePath = Paths.get(docFile.getFilePath());
            Path targetPath = Paths.get(targetFilePath);
 
            // 使用Files.copy复制文件,REPLACE_EXISTING选项处理文件已存在的情况
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
 
            log.info("文件复制成功: {} -> {}", docFile.getFilePath(), targetFilePath);
            return true;
        } catch (IOException e) {
            log.error("文件复制失败: {}", e.getMessage(), e);
            // 失败时删除已创建的空目录
            if (directory.exists() && isDirectoryEmpty(directory)) {
                directory.delete();
            }
            return false;
        }
    }
 
    /**
     * 构建目标文件名(包含版本信息)
     * 格式: 原文件名_V版本号.后缀
     * 例如: drawing_V1.0.dwg
     */
    private String buildTargetFileName(DocFile docFile) {
        String baseName = FilenameUtils.getBaseName(docFile.getFileName());
        String version = docFile.getDocVersion() != null ? docFile.getDocVersion() : "1.0";
        String suffix = docFile.getFileSuffix() != null ? docFile.getFileSuffix() : "";
 
        // 确保版本号格式正确
        if (!version.startsWith("V")) {
            version = "V" + version;
        }
 
        // 确保后缀以点开头
        if (!suffix.isEmpty() && !suffix.startsWith(".")) {
            suffix = "." + suffix;
        }
 
        return baseName + "_" + version + suffix;
    }
 
    /**
     * 检查目录是否为空
     */
    private boolean isDirectoryEmpty(File directory) {
        if (!directory.isDirectory()) {
            return false;
        }
        String[] files = directory.list();
        return files == null || files.length == 0;
    }
 
 
    public static boolean getFile(DocInfo docInfo, FileUploadResult fileUploadResult, IDocFileService docFileService) {
        boolean b;
        DocFile docFile = new DocFile();
        docFile.setDocId(docInfo.getDocId());
        docFile.setFileName(fileUploadResult.getFileName());
        docFile.setFileEncodeName(fileUploadResult.getEncodeFileName());
        docFile.setFilePath(fileUploadResult.getFilePath());
        docFile.setFileSize(fileUploadResult.getFileSize());
        docFile.setFileSuffix(fileUploadResult.getFileSuffix());
        b =  docFileService.addDocFile(docFile);
        if(!b) {
            return true;
        }
        docInfo.setPublishVersion(docFile.getDocVersion());
        docInfo.setPublishFileId(docFile.getFileId());
        return false;
    }
 
    private static DocFile getDocFile(DocInfo docInfo, FileUploadResult fileUploadResult) {
        DocFile docFile = new DocFile();
        docFile.setDocId(docInfo.getDocId());
        docFile.setFileName(fileUploadResult.getFileName());
        docFile.setFileEncodeName(fileUploadResult.getEncodeFileName());
        docFile.setFilePath(fileUploadResult.getFilePath());
        docFile.setFileSize(fileUploadResult.getFileSize());
        docFile.setFileSuffix(fileUploadResult.getFileSuffix());
        return docFile;
    }
 
    private boolean savePermissionList(ComponentInfo comp, String totalOrSonId) {
        boolean b;
        List<PermissionStream> oldPermissionList = permissionStreamService.getAllByProductId(totalOrSonId);
        //权限
        List<ComponentDepartment> componentDepartmentList = new ArrayList<>();
        List<PermissionStream> componentDepartPermList = new ArrayList<>();
        List<ComponentPermission> componentPermissionList = new ArrayList<>();
        ComponentDepartment department;
        ComponentPermission permission;
        PermissionStream stream;
        if(oldPermissionList != null && !oldPermissionList.isEmpty()) {
            for (PermissionStream p : oldPermissionList) {
                if (ValidateUtil.validateString(p.getUserId())) {
                    //部门权限
                    permission = new ComponentPermission();
                    permission.setComponentId(comp.getComponentId());
                    permission.setUserId(p.getUserId());
                    componentPermissionList.add(permission);
 
                    stream = new PermissionStream();
                    stream.setUserId(p.getUserId());
                    stream.setProductId(comp.getProductId());
                    stream.setComponentId(comp.getComponentId());
                    componentDepartPermList.add(stream);
                }
                if (ValidateUtil.validateString(p.getDepartId())) {
                    //用户权限
                    department = new ComponentDepartment(comp.getComponentId(), p.getDepartId());
                    componentDepartmentList.add(department);
                    stream = new PermissionStream(comp.getProductId(), comp.getComponentId());
                    stream.setDepartId(p.getDepartId());
                    componentDepartPermList.add(stream);
                }
 
            }
        }
        if(!componentDepartmentList.isEmpty()) {
            b = componentDepartmentService.saveBatch(componentDepartmentList);
            if(!b) {
                return false;
            }
        }
        if(!componentPermissionList.isEmpty()) {
            b = componentPermissionService.saveBatch(componentPermissionList);
            if(!b) {
                return false;
            }
        }
        if(!componentDepartPermList.isEmpty()) {
            b = permissionStreamService.saveBatch(componentDepartPermList);
            if(!b) {
                return false;
            }
        }
        return true;
    }
 
 
    @Override
    public String readFileName(String itemCode){
        return "pdm_" + itemCode + ".zip";
    }
 
    /**
     * 从指定的 ZIP 压缩包中提取所有 .nc 文件的内容及其文件名
     *
     * @param zipFilePath ZIP 压缩包的文件路径
     * @return 包含文件名和对应文件内容的映射
     * @throws IOException 如果在读取压缩包或文件内容时发生 I/O 错误
     */
    public static Map<String, String> extractNcFilesWithNamesFromZip(String zipFilePath) throws IOException {
        // 用于存储文件名和对应文件内容的映射
        Map<String, String> ncFilesMap = new HashMap<>();
        // 使用 try-with-resources 语句确保 ZipFile 资源被正确关闭
        try (ZipFile zipFile = new ZipFile(zipFilePath)) {
            // 遍历压缩包中的每个条目
            for (ZipEntry entry : zipFile.stream().collect(Collectors.toList())) {
                // 检查条目是否为 .nc 文件
                if (entry.getName().endsWith(".nc")) {
                    // 用于存储单个 .nc 文件的内容
                    StringBuilder content = new StringBuilder();
                    // 使用 try-with-resources 语句确保输入流和读取器资源被正确关闭
                    try (InputStream inputStream = zipFile.getInputStream(entry);
                         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                        String line;
                        // 逐行读取文件内容
                        while ((line = reader.readLine()) != null) {
                            content.append(line).append("\n");
                        }
                        // 将文件名和文件内容添加到映射中
                        ncFilesMap.put(entry.getName(), content.toString());
                    }
                }
            }
        }
        return ncFilesMap;
    }
}