From 7126eab629d31beb5164b576a44b865a6a00f07c Mon Sep 17 00:00:00 2001
From: lyh <925863403@qq.com>
Date: 星期三, 17 九月 2025 17:56:29 +0800
Subject: [PATCH] 420工控网修改回传

---
 src/main/java/com/lxzn/nc/service/impl/DocInfoServiceImpl.java |  316 +++++++++++++++++++++++----------------------------
 1 files changed, 143 insertions(+), 173 deletions(-)

diff --git a/src/main/java/com/lxzn/nc/service/impl/DocInfoServiceImpl.java b/src/main/java/com/lxzn/nc/service/impl/DocInfoServiceImpl.java
index ac02a61..b0dd5ed 100644
--- a/src/main/java/com/lxzn/nc/service/impl/DocInfoServiceImpl.java
+++ b/src/main/java/com/lxzn/nc/service/impl/DocInfoServiceImpl.java
@@ -45,7 +45,10 @@
 import javax.servlet.http.HttpServletResponse;
 import java.io.File;
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.nio.file.StandardCopyOption;
 import java.util.ArrayList;
 import java.util.Date;
@@ -177,209 +180,176 @@
     }
 
     @Override
-    @Transactional(rollbackFor = {Exception.class})
-    public boolean addDocInfoRec(String pathFile,File fileRec) {
-        // /dnc/NC/3140058/REC/
-        if (StringUtils.isEmpty(pathFile)) {
+    @Transactional(rollbackFor = Exception.class)
+    public boolean addDocInfoRec(String pathFile, File fileRec) {
+        // 鍙傛暟鏍¢獙
+        if (StringUtils.isEmpty(pathFile) || fileRec == null || !fileRec.exists()) {
+            log.error("Invalid parameters");
             return false;
         }
-        SingleDictionary singleDictionary=dictionaryService.findListFromTypeCode("virtual_equipment_id").get(0);
-        MultipartFile file = FileUtil.fileToMultipartFile(fileRec);
+        // 鑾峰彇鏂囨。鍒嗙被
         DocClassification docClass = docClassificationService.getByCode("REC");
-        if(docClass == null) {
+        if (docClass == null) {
             ExceptionCast.cast(DocumentCode.DOC_CLASS_ERROR);
-        }
-        //鏍规嵁璁惧缂栧彿鏌ヨ鏁版嵁
-        Integer recNum = pathFile.lastIndexOf("/REC/");
-        if (recNum == -1) {
             return false;
         }
-        String  recF =  pathFile.substring(0,recNum);//灏嗚繑鍥瀌ef}ab
-        Integer equipmentId = recF.lastIndexOf("/");
-        String deviceNo = recF.substring(equipmentId+1,recF.length());
+        // 澧炲己璺緞瑙f瀽閫昏緫
+        String deviceNo = extractDeviceNoFromPath(pathFile);
         if (StringUtils.isEmpty(deviceNo)) {
-            log.error("璁惧鍙蜂负绌�");
+            log.error("Failed to extract deviceNo from path: {}", pathFile);
             return false;
         }
-        log.info("deviceNo ==== " + deviceNo);
+        // 鑾峰彇璁惧淇℃伅
         DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(deviceNo);
         if (deviceInfo == null) {
+            log.error("Device not found: {}", deviceNo);
             return false;
         }
-
-        String docEquipmentId = null;
-        if (singleDictionary != null) {
-            docEquipmentId= String.valueOf(singleDictionary.getDicValue());
+        String originalSuffix = FileUtil.getFileSuffix(fileRec.getName());
+        if (!"zip".equalsIgnoreCase(originalSuffix) && !"rar".equalsIgnoreCase(originalSuffix)) {
+             processNonArchiveFile(fileRec, deviceInfo, docClass, originalSuffix);
         }
-        List<String> strings =  deviceGroupService.findListParentTreeAll(deviceInfo.getGroupId());
-        String fileSuffix = FileUtil.getFileSuffix(fileRec.getName());
-        if ( !fileSuffix.equals("zip") && !fileSuffix.equals("rar") ) {
-            //澶勭悊鏂囦欢 璁板綍骞朵笂鎶�
-            //1銆� 鍒ゆ柇绔彛鏄惁鑳藉璁块棶 鏂囦欢璺緞鍔�
-//            boolean btelnetPort =  TelnetUtil.telnetPort(serverIp,serverPort,10);
-//            if (!btelnetPort) {
-//                ExceptionCast.cast(ActivitiCode.ACT_DEVICE_DOC_FILELABLE);
-//            }
-            DncPassLog passInfoTxt = new DncPassLog();
+        return processArchiveFile(fileRec, deviceInfo, docClass);
+    }
 
-            String path = org.apache.commons.lang3.StringUtils.join(strings.toArray(), "/");
-            Date dateFirst = DateUtil.getNow();
-            passInfoTxt.setDayTime(DateUtil.format(dateFirst,DateUtil.STR_YEARMONTHDAY));
-
-            //浼戠湢 500姣
-            DncPassLog dncPassLog  = dncPassLogService.findDayTime(DateUtil.format(dateFirst,DateUtil.STR_YEARMONTHDAY));
-            Integer fileTxt = 0, fileNc =0;
-            if (dncPassLog !=null) {
-                fileTxt = dncPassLog.getSequenceNumber() + 1;
-                fileNc = fileTxt + 1;
-            } else {
-                fileTxt =  1;
-                fileNc = fileTxt + 1;
-            }
-            //澶勭悊鏂囦欢鍚嶇О  鏂囦欢璺緞
-            String sequence = String.format("%06d",fileTxt);
-            String sequenceNc = String.format("%06d",fileNc);
-            passInfoTxt.setSequenceNumber(fileTxt);
-            passInfoTxt.setSequenceOrder(sequence);
-            passInfoTxt.setCreateTime(dateFirst);
-            System.out.println(DateUtil.format(dateFirst,DateUtil.STR_DATE_TIME));
-            passInfoTxt.setPassType("01");
-            dncPassLogService.save(passInfoTxt);
-
-            DncPassLog passInfoNc = new DncPassLog();
-            passInfoNc.setSequenceNumber(fileNc);
-            passInfoNc.setSequenceOrder(sequenceNc);
-            passInfoNc.setDayTime(DateUtil.format(dateFirst,DateUtil.STR_YEARMONTHDAY));
-            passInfoNc.setPassType("02");
-            passInfoNc.setPassName(fileRec.getName());
-            try {
-                Thread.sleep(1000);
-                Date date = new Date();
-                passInfoNc.setCreateTime(date);
-                System.out.println(DateUtil.format(date,DateUtil.STR_DATE_TIME));
-            } catch (InterruptedException e) {
-                e.printStackTrace();
-            }
-
-            dncPassLogService.save(passInfoNc);
-
-            NcTxtFilePathInfo ncTxt = new NcTxtFilePathInfo();
-            ncTxt.setEquipmentId(deviceInfo.getDeviceNo());
-            if (deviceInfo.getDeviceNo().equals(docEquipmentId)) {
-                //鍘熸湁鍚嶇О鍔犳椂闂�
-                ncTxt.setFileNcName(fileRec.getName()+"_"+DateUtil.format(dateFirst,DateUtil.STR_YEARMONTHDAY));
-            }else {
-                ncTxt.setFileNcName("10B"+DateUtil.format(dateFirst,DateUtil.STR_YEARMONTHDAY)+sequenceNc);
-            }
-            ncTxt.setFileTxtName("10B"+DateUtil.format(dateFirst,DateUtil.STR_YEARMONTHDAY)+sequence);
-            ncTxt.setFilePath(path + "/"+ deviceInfo.getDeviceNo() + "/" );
-            ncTxt.setOrigFileName(fileRec.getName());
-            ncTxt.setOrigFileSuffix(fileSuffix);
-            ncTxt.setFileAddOrDelete(1);
-            String loFilePath = localFilePath + ncTxt.getFileTxtName() + ".nc";
-            String size = String.valueOf(fileRec.length());
-
-            try {
-                String allList = new String();
-                allList=(ncTxt.getFileTxtName()+"\n");
-                allList+=(ncTxt.getFileNcName()+"\n");
-                allList+=(ncTxt.getOrigFileName()+"\n");
-                allList+=(ncTxt.getOrigFileSuffix()+"\n");
-                allList+=(ncTxt.getFilePath()+"\n");
-                allList+=(ncTxt.getEquipmentId()+"\n");
-                allList+=(ncTxt.getFileAddOrDelete().toString()+"\n");
-                // 鏂囦欢澶у皬瀛楄妭  绗簩琛� 宸ユ帶缃戣繘琛屾枃浠跺垎鏋�
-                allList+= (size+"\n");
-
-                FileUtil.fileWriterSql(loFilePath,allList);
-
-                //瀵规瘮璁惧缂栧彿
-                if (deviceInfo.getDeviceNo().equals(docEquipmentId)) {
-                    String originalFilename = fileRec.getName();
-                    File virtualDeviceDir = new File(localFilePath);
-                    if (!virtualDeviceDir.exists() && !virtualDeviceDir.mkdirs()) {
-                        log.error("鏃犳硶鍒涘缓铏氭嫙璁惧鐩綍: {}", virtualDeviceDir.getAbsolutePath());
-                        return false;
-                    }
-                    // 3. 鏋勫缓鐩爣鏂囦欢璺緞
-                    File targetFile = new File(virtualDeviceDir, originalFilename);
-                    try {
-                        // 4. 浣跨敤NIO澶嶅埗鏂囦欢锛屽苟鏇挎崲宸插瓨鍦ㄧ殑鏂囦欢
-                        //鏇存崲鏂囦欢鍚嶏紝鏇存崲涓簄cTxt.getFileNcName()
-                        Files.copy(
-                                fileRec.toPath(),
-                                targetFile.toPath(),
-                                StandardCopyOption.REPLACE_EXISTING
-                        );
-                        log.info("铏氭嫙璁惧鏂囦欢宸蹭繚瀛樿嚦: {}", targetFile.getAbsolutePath());
-                    } catch (IOException e) {
-                        log.error("铏氭嫙璁惧鏂囦欢淇濆瓨澶辫触", e);
-                        return false;
-                    }
-                    return true;
-                }else {
-                    //鏂囦欢瑙f瀽閲嶆柊瑙勫垝
-                    //娣诲姞鏂囦欢鍚嶅瓧锛岀涓�琛�
-                    boolean copyFileNc = FileUtil.copyFileUpNameRec(fileRec,
-                            localFilePath + ncTxt.getFileNcName(),
-                            fileSuffix,"NC");
-                    if (!copyFileNc) {
-                        FileUtil.deleteNcFile(loFilePath);
-                    }
-                }
-            } catch (IOException e) {
-                e.printStackTrace();
+    // 澧炲己璺緞瑙f瀽鏂规硶
+    private String extractDeviceNoFromPath(String pathFile) {
+        // 缁熶竴澶勭悊璺緞鍒嗛殧绗�
+        String normalizedPath = pathFile.replace('\\', '/');
+        // 鏌ユ壘"/REC/"浣嶇疆
+        int recIndex = normalizedPath.lastIndexOf("/REC/");
+        if (recIndex != -1) {
+            String prefix = normalizedPath.substring(0, recIndex);
+            int lastSlash = prefix.lastIndexOf('/');
+            return (lastSlash != -1) ? prefix.substring(lastSlash + 1) : prefix;
+        }
+        // 澶勭悊娌℃湁缁撳熬鏂滄潬鐨勬儏鍐�
+        recIndex = normalizedPath.lastIndexOf("/REC");
+        if (recIndex != -1 && (recIndex + 4 == normalizedPath.length()
+                || normalizedPath.charAt(recIndex + 4) == '/')) {
+            String prefix = normalizedPath.substring(0, recIndex);
+            int lastSlash = prefix.lastIndexOf('/');
+            return (lastSlash != -1) ? prefix.substring(lastSlash + 1) : prefix;
+        }
+        // 灏濊瘯鍩轰簬璺緞娈佃В鏋�
+        String[] segments = normalizedPath.split("/");
+        for (int i = 0; i < segments.length; i++) {
+            if ("REC".equalsIgnoreCase(segments[i]) && i > 0) {
+                return segments[i - 1];
             }
         }
-        String fileName = FileUtil.getFilenameNonSuffix(file.getOriginalFilename());
-        FileUploadResult fileUploadResult = FileUtil.uploadFile(file);
 
-        if(fileUploadResult == null) {
+        return null;
+    }
+
+    // 闈炲帇缂╂枃浠跺鐞嗭紙浜嬪姟鍐咃級
+    private boolean processNonArchiveFile(File fileRec, DeviceInfo deviceInfo,
+                                          DocClassification docClass, String originalSuffix) {
+        try {
+            Date currentDate = new Date();
+            String dayTime = DateUtil.format(currentDate, DateUtil.STR_YEARMONTHDAY);
+            DncPassLog passLog = dncPassLogService.findDayTime(dayTime);
+            int newSequence = (passLog != null) ? passLog.getSequenceNumber() + 1 : 1;
+            DncPassLog txtLog = new DncPassLog();
+            txtLog.setDayTime(dayTime);
+            txtLog.setSequenceNumber(newSequence);
+            txtLog.setSequenceOrder(String.format("%06d", newSequence));
+            txtLog.setCreateTime(currentDate);
+            txtLog.setPassType("01");
+            dncPassLogService.save(txtLog);
+            DncPassLog ncLog = new DncPassLog();
+            ncLog.setDayTime(dayTime);
+            ncLog.setSequenceNumber(newSequence + 1);
+            ncLog.setSequenceOrder(String.format("%06d", newSequence + 1));
+            ncLog.setPassType("02");
+            ncLog.setPassName(fileRec.getName());
+            ncLog.setCreateTime(currentDate);
+            dncPassLogService.save(ncLog);
+            NcTxtFilePathInfo fileInfo = new NcTxtFilePathInfo();
+            fileInfo.setEquipmentId(deviceInfo.getDeviceNo());
+            fileInfo.setOrigFileName(fileRec.getName());
+            fileInfo.setOrigFileSuffix(originalSuffix);
+            fileInfo.setFileAddOrDelete(1);
+            List<String> groupPaths = deviceGroupService.findListParentTreeAll(deviceInfo.getGroupId());
+            String storagePath = String.join("/", groupPaths) + "/" + deviceInfo.getDeviceNo() + "/";
+            fileInfo.setFilePath(storagePath);
+            fileInfo.setFileTxtName("10B" + dayTime + String.format("%06d", newSequence));
+            fileInfo.setFileNcName("10B" + dayTime + String.format("%06d", newSequence + 1));
+            return savePhysicalDeviceFile(fileRec, fileInfo);
+        } catch (Exception e) {
+            log.error("Non-archive processing failed", e);
+            throw new RuntimeException(e);
+        }
+    }
+
+    // 鍘嬬缉鏂囦欢澶勭悊锛堜簨鍔″唴锛�
+    private boolean processArchiveFile(File fileRec, DeviceInfo deviceInfo, DocClassification docClass) {
+        MultipartFile multipartFile = FileUtil.fileToMultipartFile(fileRec);
+        FileUploadResult uploadResult = FileUtil.uploadFile(multipartFile);
+        if (uploadResult == null) return false;
+
+        // 妫�鏌ユ枃妗f槸鍚﹀凡瀛樺湪
+        String fileName = FileUtil.getFilenameNonSuffix(multipartFile.getOriginalFilename());
+        if (findByAttrAndDocName(fileName, 4, deviceInfo.getDeviceId()) != null) {
+            log.warn("Document already exists: {}", fileName);
             return false;
         }
-        DocInfo en = findByAttrAndDocName(fileName, 4, deviceInfo.getDeviceId());
-        if(en != null) {
-            return false;
-        }
-
+        // 淇濆瓨鏂囨。鍏崇郴
+        DocRelative docRelative = new DocRelative();
+        docRelative.setAttributionId(deviceInfo.getDeviceId());
+        docRelative.setAttributionType(4);
+        docRelative.setClassificationId(docClass.getClassificationId());
+        // 淇濆瓨鏂囨。淇℃伅锛堜娇鐢ㄤ笂浼犲悗鐨勬枃浠跺悕锛�
         DocInfo docInfo = new DocInfo();
         String docId = IdWorker.getIdStr();
         docInfo.setDocId(docId);
-        docInfo.setDocName(fileUploadResult.getFileName());
-        docInfo.setDocSuffix(fileUploadResult.getFileSuffix());
+        docInfo.setDocName(uploadResult.getFileName());
+        docInfo.setDocSuffix(uploadResult.getFileSuffix());
         docInfo.setDocStatus(2);
-        DocRelative dr = new DocRelative();
-        dr.setAttributionId(deviceInfo.getDeviceId());
-        dr.setDocId(docInfo.getDocId());
-        dr.setAttributionType(4);
-        dr.setClassificationId(docClass.getClassificationId());
+        // 淇濆瓨鏂囦欢璁板綍
+        DocFile docFile = new DocFile();
+        docFile.setDocId(docId);
+        docFile.setFileName(uploadResult.getFileName());
+        docFile.setFileEncodeName(uploadResult.getEncodeFileName());
+        docFile.setFilePath(uploadResult.getFilePath());
+        docFile.setFileSize(uploadResult.getFileSize());
+        docFile.setFileSuffix(uploadResult.getFileSuffix());
+        docFile.setUpdateUser("system");
         try {
-            boolean b = docRelativeService.save(dr);
-            if(!b) {
+            docRelative.setDocId(docId);
+            if (!docRelativeService.save(docRelative)) {
                 ExceptionCast.cast(DocumentCode.DOC_UPLOAD_ERROR);
             }
-        }catch (Exception e) {
-            e.printStackTrace();
+            if (!docFileService.addDocFile(docFile)) return false;
+            docInfo.setPublishVersion(docFile.getDocVersion());
+            docInfo.setPublishFileId(docFile.getFileId());
+            return super.save(docInfo);
+        } catch (Exception e) {
+            log.error("Archive processing failed", e);
+            throw new RuntimeException(e);
         }
-        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());
-        docFile.setUpdateUser("11");
-        boolean b =  docFileService.addDocFile(docFile);
-        if(!b) {
-            return false;
-        }
-        docInfo.setPublishVersion(docFile.getDocVersion());
-        docInfo.setPublishFileId(docFile.getFileId());
-        boolean saveBool = super.save(docInfo);
-        return saveBool;
-
     }
 
+    private boolean savePhysicalDeviceFile(File sourceFile, NcTxtFilePathInfo fileInfo) throws IOException {
+        // 鐢熸垚鍏冩暟鎹枃浠�
+        Path metaFilePath = Paths.get(localFilePath, fileInfo.getFileTxtName() + ".nc");
+        String metaContent = String.join("\n",
+                fileInfo.getFileTxtName(),
+                fileInfo.getFileNcName(),
+                fileInfo.getOrigFileName(),
+                fileInfo.getOrigFileSuffix(),
+                fileInfo.getFilePath(),
+                fileInfo.getEquipmentId(),
+                String.valueOf(fileInfo.getFileAddOrDelete()),
+                String.valueOf(sourceFile.length())
+        );
+        Files.write(metaFilePath, metaContent.getBytes(StandardCharsets.UTF_8));
+
+        // 澶嶅埗鏂囦欢鍒版柊浣嶇疆锛堜笉淇敼鍘熷鏂囦欢锛�
+        Path targetPath = Paths.get(localFilePath+"/", fileInfo.getFileNcName()+".NC");
+        Files.copy(sourceFile.toPath(), targetPath);
+        return true;
+    }
 
     @Override
     @Transactional(rollbackFor = {Exception.class})

--
Gitblit v1.9.3