lyh
5 天以前 fda571324684bc8d0945b3e2841305b1207fc3e9
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
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.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.NcProgramInfo;
import com.lxzn.framework.domain.webservice.request.PlmProgramSource;
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.webservice.DncWebService;
import com.lxzn.framework.domain.webservice.request.WsDispatch;
import com.lxzn.framework.domain.webservice.request.WsProcedureFinish;
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 {
 
    @Value("${ncPdm.file_path}")
    private String filePath;
    /**
     * url
     */
    @Value("${webservice.url}")
    private String url;
 
    /**
     * namespace
     */
    @Value("${webservice.namespace}")
    private String namespace;
 
    /**
     * method
     */
    @Value("${webservice.method}")
    private String method;
    @Resource
    private IDispatchInfoService dispatchInfoService;
    @Resource
    private IProcedureFinishService procedureFinishService;
    @Resource
    private IDeviceInfoService deviceInfoService;
    @Resource
    private IAssignFileStreamService assignFileStreamService;
    @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;
 
    /**
     * 派工任务下发接口
     * @param msg
     * @return
     */
    @Override
    public String issuedDispatchTask(@WebParam(name = "msg") String msg){
        log.info("MES派工任务下发原始数据 === {}", msg);
        List<WsDispatch> wsDispatchList = JSONObject.parseArray(msg, WsDispatch.class);
        for (WsDispatch wsDispatch : wsDispatchList) {
            DispatchInfo dispatchInfo = new DispatchInfo();
            BeanUtils.copyProperties(wsDispatch, dispatchInfo);
            dispatchInfoService.save(dispatchInfo);
            Map<Boolean,String> ncResult = disPatchTaskNc(dispatchInfo);
            if (ncResult.containsKey(false)) {
                // 返回具体的错误信息
                return MesResultModel.error("NC任务下发失败: " + ncResult.get(false));
            }
        }
        return MesResultModel.success("成功");
    }
 
 
    /**
     * 下发程序
     */
    public Map<Boolean,String> disPatchTaskNc(DispatchInfo dispatchInfo) {
        String processCode = dispatchInfo.getOperationSeqNo() + "_" + dispatchInfo.getEquipmentId();
        return assignFileStreamService.disPatchTaskNc(dispatchInfo.getEquipmentId(),
                dispatchInfo.getWorkshop(),dispatchInfo.getMdsItemCode(),processCode,dispatchInfo.getRevisionNo(),dispatchInfo.getId());
    }
 
    /**
     * 完工
     *
     * @param msg
     * @return
     */
    @Override
    public String issuedProcedureFinish(String msg) {
        log.info("MES完工原始数据 === {}", msg);
        List<WsProcedureFinish> wsProcedureFinishList = JSONObject.parseArray(msg, WsProcedureFinish.class);
        if (CollectionUtils.isEmpty(wsProcedureFinishList)) {
            return MesResultModel.error("MesResultModel");
        }
        List<ProcedureFinish> procedureFinishList = wsProcedureFinishList.stream()
                .map(source -> {
                    ProcedureFinish target = new ProcedureFinish();
                    BeanUtils.copyProperties(source, target);
                    return target;
                })
                .collect(Collectors.toList());
 
        procedureFinishService.saveBatch(procedureFinishList);
        //DNC系统依据工单号删除设备结构树上对应的NC程序及工控网NC程序
        for (ProcedureFinish procedureFinish : procedureFinishList) {
            //DNC系统依据工单号删除设备结构树上对应的NC程序及工控网NC程序
            if (procedureFinish.getEndineStatus().equals("3")){
                //删除设备结构树上对应的NC程序及工控网NC程序
                ProductInfo productInfo = productInfoService.getByProductNo("PLM");
                if (productInfo == null) {
                    log.error("======= 产品层级异常,请联系开发人员=======");
                    return MesResultModel.error("产品层级异常,请联系开发人员");
                }
                List<ComponentInfo> componentInfoList = componentInfoService.getByProductId(productInfo.getProductId());
                List<String
 
                        > comlist = new ArrayList<>();
                if (componentInfoList != null && !componentInfoList.isEmpty()) {
                    for (ComponentInfo cc : componentInfoList) {
                        comlist.add(cc.getComponentId());
                    }
                } else {
                    return MesResultModel.error("无部件信息,请联系开发人员");
                }
                String processCode=procedureFinish.getMdsItemCode();
                PartsInfo part = partsInfoService.getByCodeAndComIdList(procedureFinish.getMdsItemCode(),comlist);
                if (part == null) {
                    return MesResultModel.error("无此零件信息"+"__" + processCode+",请联系开发人员");
                }
                processCode = processCode.split("_")[0];
                //工序
                ProcessStream stream = processStreamService.findByProcessEquipment(procedureFinish.getEquipmentId(),
                        processCode,procedureFinish.getRevisionNo(),productInfo.getProductId(),part.getPartsId());
                if (stream == null) {
                    return MesResultModel.error("无此工序信息"+"__" + processCode+",请联系开发人员");
                }
                //查询对应NC程序
                List<ProcessStream> processStreamList = new ArrayList<>();
                processStreamList.add(stream);
                List<DocInfo> docFileList = docInfoService.getByProcessIds(processStreamList);
                if (docFileList == null || docFileList.isEmpty()) {
                    return MesResultModel.error("无此NC程序" + "__" + processCode + ",请联系开发人员");
                }
                docFileList.forEach(docFile -> {
                    docInfoService.deleteDocInfo(docFile.getDocId());
                });
            }
 
        }
        log.info("接收MES完工原始数据成功!");
        return MesResultModel.success("成功");
    }
 
 
    /**
     * 获取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(setTree(item));
        });
        return mesResultModel.get();
    }
 
    /**
     * 封装树结构
     1. 产品 集成数据
     2、部件 按照部门(车间 ae8nc_plant )维度建立
     3、零件 图号(零件号、零件名称) ae8part_no
     4、工序  工艺ID(工艺规程编号/临规编号)
     5. nc文件 (工序下)
     6.机床型号与机床操作系统组成设备类与工序进行绑定
     * @param plmProgramSource
     * @return
     */
    public MesResultModel setTree(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;
    }
 
    private MesResultModel createErrorModel(MesResultModel model, String errorMsg) {
        model.setSuccFlag("失败");
        model.setError(errorMsg);
        return model;
    }
 
    /**
     * * NC程序齐套接口(MES)-DNC系统接收到PLM传的NC程序,将程序包对应的零件号、工序号、设备编号传给MES系统
     * 定时扫描PlmProgramSourceInfo表中的数据,进行数据同步,每分钟同步一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void syncWorkmanship() {
        // 获取所有需要同步的数据
        List<PlmProgramSourceInfo> plmProgramSourceInfos = iPlmProgramSourceInfoService.list(
                new LambdaQueryWrapper<PlmProgramSourceInfo>()
                        .eq(PlmProgramSourceInfo::getMesStatus, "0")
                        .orderByAsc(PlmProgramSourceInfo::getId)
        );
 
        if (plmProgramSourceInfos.isEmpty()) {
            log.info("无待同步数据,跳过处理");
            return;
        }
 
        List<NcProgramInfo> ncProgramInfos = plmProgramSourceInfos.stream().map(item -> {
            NcProgramInfo ncProgramInfo = new NcProgramInfo();
            ncProgramInfo.setMdsItemCode(item.getCzkAe8nPartNo());
            ncProgramInfo.setRevisionNo(item.getRevisionNo());
            ncProgramInfo.setNcProgramName(item.getFileName());
            ncProgramInfo.setOpreationSeqNo(item.getCzkAe8nOpNo());
            ncProgramInfo.setEquipmentId(item.getCzkAe8nEquipNo());
            ncProgramInfo.setWorkshop(item.getCzkAe8nDivision());
//            ncProgramInfo.setMesId(item.getId()); // 确保生成符合要求的mesId
//            ncProgramInfo.setOperFlag();
            return ncProgramInfo;
        }).collect(Collectors.toList());
 
        log.info("WebService-NC程序齐套接口(MES)同步开始,时间: {}", new Date());
        try {
            String jsonPayload = JSONObject.toJSONString(ncProgramInfos);
            log.debug("上报数据: {}", jsonPayload);
 
            // 调用WebService并获取详细响应
            String result = CxfClientUtil.invokeService(url, jsonPayload, namespace, method);
            log.info("接口响应: {}", result);
 
            // 解析响应结果,只会有成功和失败
            if (result.contains("成功")) {
                List<PlmProgramSourceInfo> toUpdate = new ArrayList<>();
 
                plmProgramSourceInfos.forEach(item -> {
                    item.setMesStatus("1");
                    toUpdate.add(item);
                });
                // 批量更新状态
                if (!toUpdate.isEmpty()) {
                    iPlmProgramSourceInfoService.updateBatchById(toUpdate);
                    log.info("成功更新{}条数据状态", toUpdate.size());
                }
            }else {
                log.error("同步MES系统失败: {}", result);
            }
        } catch (Exception e) {
            log.error("同步MES系统失败: {}", e.getMessage(), e);
            // 仅标记处理失败的记录
            plmProgramSourceInfos.forEach(item -> item.setMesStatus("0"));
            iPlmProgramSourceInfoService.updateBatchById(plmProgramSourceInfos);
            throw new RuntimeException("同步失败,已回滚状态", e); // 触发事务回滚
        }
    }
 
    /**
     * 创建升版文件保存地址并复制文件
     * 层级结构: 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;
    }
 
    private static String buildRequestBody(NcProgramInfo ncProgramInfo) {
        StringBuilder body = new StringBuilder();
        body.append("mesId=").append(ncProgramInfo.getMesId())
                .append("&mdsItemCode=").append(ncProgramInfo.getMdsItemCode())
                .append("&revisionNo=").append(ncProgramInfo.getRevisionNo())
                .append("&opreationSeqNo=").append(ncProgramInfo.getOpreationSeqNo())
                .append("&equipmentId=").append(ncProgramInfo.getEquipmentId())
                .append("&workshop=").append(ncProgramInfo.getWorkshop());
        return body.toString();
    }
 
 
    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;
    }
}