From 0debf5b7bb0246eaef1397975cdb16f4adb9e8d9 Mon Sep 17 00:00:00 2001
From: liding <756868258@qq.com>
Date: 星期四, 29 十月 2026 14:36:31 +0800
Subject: [PATCH] refactor(inspection-order): 1.检验委托单绑定机制支持多次下单 2.合格率统计口径调整 3.外购铜导体推送入库MES增加米重 4.报告英文字段调整

---
 cnas-process/src/main/java/com/ruoyi/process/service/impl/InspectionOrderServiceImpl.java |  379 ++++++++++++++++++++++++++++++++++--------------------
 1 files changed, 238 insertions(+), 141 deletions(-)

diff --git a/cnas-process/src/main/java/com/ruoyi/process/service/impl/InspectionOrderServiceImpl.java b/cnas-process/src/main/java/com/ruoyi/process/service/impl/InspectionOrderServiceImpl.java
index dba5579..ac756a0 100644
--- a/cnas-process/src/main/java/com/ruoyi/process/service/impl/InspectionOrderServiceImpl.java
+++ b/cnas-process/src/main/java/com/ruoyi/process/service/impl/InspectionOrderServiceImpl.java
@@ -2,7 +2,6 @@
 
 import cn.hutool.core.util.StrUtil;
 import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
@@ -17,24 +16,23 @@
 import com.ruoyi.common.utils.SecurityUtils;
 import com.ruoyi.framework.exception.ErrorException;
 import com.ruoyi.inspect.dto.InsPlaceOrderDto;
-import com.ruoyi.inspect.mapper.InsProductResultMapper;
-import com.ruoyi.inspect.mapper.InsSampleMapper;
 import com.ruoyi.inspect.pojo.InsOrder;
-import com.ruoyi.inspect.pojo.InsProductResult;
 import com.ruoyi.inspect.pojo.InsReport;
 import com.ruoyi.inspect.service.InsOrderService;
 import com.ruoyi.inspect.service.InsReportService;
 import com.ruoyi.inspect.util.HackLoopTableRenderPolicy;
 import com.ruoyi.process.dto.InspectionOrderDto;
+import com.ruoyi.process.dto.InspectionOrderBindingDto;
 import com.ruoyi.process.dto.InspectionOrderExportDto;
 import com.ruoyi.process.mapper.InspectionOrderBindLogMapper;
 import com.ruoyi.process.mapper.InspectionOrderMapper;
-import com.ruoyi.process.mapper.ProcessOrderDeviceMapper;
-import com.ruoyi.process.mapper.ProcessSampleMapper;
+import com.ruoyi.process.mapper.InspectionOrderAttachmentMapper;
+import com.ruoyi.process.mapper.InspectionOrderBindingMapper;
 import com.ruoyi.process.pojo.InspectionOrder;
+import com.ruoyi.process.pojo.InspectionOrderAttachment;
+import com.ruoyi.process.pojo.InspectionOrderBinding;
 import com.ruoyi.process.pojo.InspectionOrderBindLog;
 import com.ruoyi.process.pojo.InspectionOrderDetail;
-import com.ruoyi.process.pojo.ProcessOrderDevice;
 import com.ruoyi.process.service.*;
 import com.ruoyi.system.mapper.UserMapper;
 import com.ruoyi.system.mapper.CustomMapper;
@@ -54,13 +52,16 @@
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.nio.file.StandardCopyOption;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
 import java.time.LocalDateTime;
+import java.time.LocalDate;
 import java.time.format.DateTimeFormatter;
 import java.util.HashMap;
-import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
+import java.util.LinkedHashMap;
+import java.util.Objects;
+import java.util.UUID;
 
 /**
  * <p>
@@ -76,33 +77,21 @@
     @Resource
     private InspectionOrderBindLogMapper inspectionOrderBindLogMapper;
     @Resource
+    private InspectionOrderBindingMapper inspectionOrderBindingMapper;
+    @Resource
+    private InspectionOrderAttachmentMapper inspectionOrderAttachmentMapper;
+    @Resource
     private InspectionOrderDetailService inspectionOrderDetailService;
     @Resource
     private InsOrderService insOrderService;
-    @Resource
-    private InsSampleMapper insSampleMapper;
     @Resource
     private InsReportService insReportService;
     @Value("${wordUrl}")
     private String wordUrl;
     @Resource
-    private ProcessReportService processReportService;
-    @Resource
-    private ProcessOrderDeviceMapper processOrderDeviceMapper;
-    @Resource
-    private InsProductResultMapper insProductResultMapper;
-    @Resource
-    private ProcessOrderDeviceService processOrderDeviceService;
-    @Resource
     private UserMapper userMapper;
     @Resource
     private CustomMapper customMapper;
-    @Resource
-    private ProcessSampleService processSampleService;
-    @Resource
-    private ProcessSampleMapper processSampleMapper;
-    @Resource
-    private ProcessDealService processDealService;
     @Resource
     private NumberGenerator<InspectionOrder> numberGenerator;
 
@@ -149,47 +138,6 @@
         return inspectionOrder;
     }
 
-    private synchronized void addDeviceRecord(InspectionOrder inspectionOrder, Integer userId) {
-        // 鏌ヨ璁惧浣跨敤璁板綍鏌ヨ璇ヨ鍗曠殑浣跨敤璁板綍
-        Set<String> recordCodeset = processOrderDeviceMapper.selectDeviceNumber(inspectionOrder.getInspectionOrderId());
-        // 鑾峰彇璁㈠崟璁惧缂栧彿
-        List<InsProductResult> resultList = insProductResultMapper.selectResultByOrderId(inspectionOrder.getInsOrderId());
-        Set<String> deviceCodeSet = new HashSet<>();
-        for (InsProductResult result : resultList) {
-            // 娣诲姞璁惧缂栧彿
-            List<JSONObject> jsonObjects = JSON.parseArray(result.getEquipValue(), JSONObject.class);
-            for (JSONObject jsonObject : jsonObjects) {
-                if (!"".equals(jsonObject.get("v") + "")) {
-                    List<String> v = StrUtil.split(jsonObject.get("v") + "", "锛�");
-                    deviceCodeSet.addAll(v);
-                }
-            }
-        }
-        // 1.鍒ゆ柇鏄惁鏈夋病鏈夋坊鍔犵殑浣跨敤璁板綍
-        Set<String> orderDeviceNumbers = getDeviceDifference(deviceCodeSet, recordCodeset);
-        // 娣诲姞浣跨敤璁板綍, 鏍规嵁缂栧彿鏌ヨ璁惧id
-        if (CollectionUtils.isNotEmpty(orderDeviceNumbers)) {
-            List<Integer> orderDeviceIds = processOrderDeviceMapper.selectDeviceIdsByNumbers(orderDeviceNumbers);
-            List<ProcessOrderDevice> collect = orderDeviceIds.stream().map(deviceId -> {
-                ProcessOrderDevice processOrderDevice = new ProcessOrderDevice();
-                processOrderDevice.setInspectionOrderId(inspectionOrder.getInspectionOrderId());
-                processOrderDevice.setDeviceId(deviceId);
-                processOrderDevice.setSampleCode(inspectionOrder.getEntrustCode());
-                processOrderDevice.setUseBefore(1);
-                processOrderDevice.setUseAfter(1);
-                processOrderDevice.setUsePerson(userMapper.selectById(userId).getName());//浣跨敤浜�
-                processOrderDevice.setUsePersonId(userId);//浣跨敤浜篿d
-                return processOrderDevice;
-            }).collect(Collectors.toList());
-            processOrderDeviceService.saveBatch(collect);
-        }
-    }
-
-    private static Set<String> getDeviceDifference(Set<String> number1, Set<String> number2) {
-        return number1.stream().filter(s1 -> number2.stream().noneMatch(s2 -> s1.equals(s2)))
-                .collect(Collectors.toSet());
-    }
-
     /**
      * 妫�楠屽鎵樺崟淇敼
      *
@@ -198,9 +146,14 @@
      */
     @Override
     public boolean updateInspectionOrder(InspectionOrderDto InspectionOrder) {
-        InspectionOrder oldInspectionOrder = baseMapper.selectById(InspectionOrder.getInspectionOrderId());
+        InspectionOrder oldInspectionOrder = baseMapper.selectByIdForUpdate(InspectionOrder.getInspectionOrderId());
         if (oldInspectionOrder == null) {
             throw new ErrorException("妫�楠屽鎵樺崟涓嶅瓨鍦�");
+        }
+        Long bindingHistoryCount = inspectionOrderBindingMapper.selectCount(Wrappers.<InspectionOrderBinding>lambdaQuery()
+                .eq(InspectionOrderBinding::getInspectionOrderId, InspectionOrder.getInspectionOrderId()));
+        if (bindingHistoryCount > 0 && !Objects.equals(oldInspectionOrder.getCommissionUnitId(), InspectionOrder.getCommissionUnitId())) {
+            throw new ErrorException("宸叉湁涓嬪崟璁板綍锛屼笉鍏佽淇敼濮旀墭鍗曚綅");
         }
         normalizeCommissionParty(InspectionOrder);
         // 缂栧彿銆佸叧鑱斿叧绯汇�佹寮忓鎵樼紪鍙峰拰鎶ュ憡鍦板潃鍙兘鐢变笓鐢ㄦ祦绋嬬淮鎶ゃ��
@@ -235,12 +188,19 @@
      */
     @Override
     public boolean delInspectionOrder(Integer inspectionOrderId) {
-        InspectionOrder inspectionOrder = baseMapper.selectById(inspectionOrderId);
+        InspectionOrder inspectionOrder = baseMapper.selectByIdForUpdate(inspectionOrderId);
         if (inspectionOrder == null) {
             throw new ErrorException("妫�楠屽鎵樺崟涓嶅瓨鍦�");
         }
-        if (inspectionOrder.getInsOrderId() != null) {
-            throw new ErrorException("宸茬粦瀹氭垚鍝佷笅鍗曠殑妫�楠屽鎵樺崟涓嶅厑璁稿垹闄�");
+        Long bindingHistoryCount = inspectionOrderBindingMapper.selectCount(Wrappers.<InspectionOrderBinding>lambdaQuery()
+                .eq(InspectionOrderBinding::getInspectionOrderId, inspectionOrderId));
+        Long bindLogCount = inspectionOrderBindLogMapper.selectCount(Wrappers.<InspectionOrderBindLog>lambdaQuery()
+                .and(wrapper -> wrapper.eq(InspectionOrderBindLog::getOldInspectionOrderId, inspectionOrderId)
+                        .or().eq(InspectionOrderBindLog::getNewInspectionOrderId, inspectionOrderId)));
+        Long attachmentCount = inspectionOrderAttachmentMapper.selectCount(Wrappers.<InspectionOrderAttachment>lambdaQuery()
+                .eq(InspectionOrderAttachment::getInspectionOrderId, inspectionOrderId));
+        if (bindingHistoryCount > 0 || bindLogCount > 0 || attachmentCount > 0) {
+            throw new ErrorException("璇ユ楠屽鎵樺崟宸叉湁涓嬪崟鎴栭檮浠跺巻鍙诧紝涓嶅厑璁稿垹闄�");
         }
 
         inspectionOrderDetailService.remove(Wrappers.<InspectionOrderDetail>lambdaQuery()
@@ -258,6 +218,9 @@
     @Override
     public InspectionOrderDto getInspectionOrderOne(Integer inspectionOrderId) {
         InspectionOrder inspectionOrder = baseMapper.selectById(inspectionOrderId);
+        if (inspectionOrder == null) {
+            throw new ErrorException("妫�楠屽鎵樺崟涓嶅瓨鍦�");
+        }
         InspectionOrderDto inspectionOrderDto = new InspectionOrderDto();
         BeanUtils.copyProperties(inspectionOrder, inspectionOrderDto);
 
@@ -273,13 +236,33 @@
     }
 
     @Override
+    public IPage<InspectionOrderBindingDto> pageInspectionOrderBindings(Page page, Integer inspectionOrderId,
+                                                                         Boolean includeDeleted) {
+        if (inspectionOrderId == null || baseMapper.selectById(inspectionOrderId) == null) {
+            throw new ErrorException("妫�楠屽鎵樺崟涓嶅瓨鍦�");
+        }
+        return inspectionOrderBindingMapper.pageBindings(page, inspectionOrderId, includeDeleted);
+    }
+
+    @Override
+    public List<InspectionOrderAttachment> listInspectionOrderAttachments(Integer inspectionOrderId, Long bindingId) {
+        if (inspectionOrderId == null || baseMapper.selectById(inspectionOrderId) == null) {
+            throw new ErrorException("妫�楠屽鎵樺崟涓嶅瓨鍦�");
+        }
+        if (bindingId != null) {
+            InspectionOrderBinding binding = inspectionOrderBindingMapper.selectById(bindingId);
+            if (binding == null || !Objects.equals(binding.getInspectionOrderId(), inspectionOrderId)) {
+                throw new ErrorException("涓嬪崟璁板綍涓嶅睘浜庤妫�楠屽鎵樺崟");
+            }
+        }
+        return inspectionOrderAttachmentMapper.selectVisibleAttachments(inspectionOrderId, bindingId);
+    }
+
+    @Override
     public InspectionOrderDto getInspectionOrderForPlaceOrder(Integer inspectionOrderId) {
         InspectionOrder inspectionOrder = baseMapper.selectById(inspectionOrderId);
         if (inspectionOrder == null) {
             throw new ErrorException("妫�楠屽鎵樺崟涓嶅瓨鍦�");
-        }
-        if (inspectionOrder.getInsOrderId() != null) {
-            throw new ErrorException("璇ユ楠屽鎵樺崟宸茬粦瀹氭垚鍝佷笅鍗曪紝涓嶈兘閲嶅閫夋嫨");
         }
         return getInspectionOrderOne(inspectionOrderId);
     }
@@ -292,12 +275,26 @@
         if (insPlaceOrderDto.getInsOrder() == null) {
             throw new ErrorException("缂哄皯鎴愬搧涓嬪崟淇℃伅");
         }
-        InspectionOrder inspectionOrder = baseMapper.selectById(insPlaceOrderDto.getInspectionOrderId());
+        if (CollectionUtils.isEmpty(insPlaceOrderDto.getSampleList())) {
+            throw new ErrorException("璇峰~鍐欐湰娆℃牱鍝�");
+        }
+        String requestId = normalizeRequestId(insPlaceOrderDto.getRequestId());
+        Integer requestUserId = SecurityUtils.getUserId().intValue();
+        String requestHash = calculateRequestHash(insPlaceOrderDto);
+        if (inspectionOrderBindingMapper.lockRequestUser(requestUserId) == null) {
+            throw new ErrorException("褰撳墠鎿嶄綔浜轰笉瀛樺湪");
+        }
+        InspectionOrderBinding existing = inspectionOrderBindingMapper.selectByRequest(requestUserId, requestId);
+        if (existing != null) {
+            return resolveIdempotentRequest(existing, requestHash);
+        }
+        InspectionOrder inspectionOrder = baseMapper.selectByIdForUpdate(insPlaceOrderDto.getInspectionOrderId());
         if (inspectionOrder == null) {
             throw new ErrorException("妫�楠屽鎵樺崟涓嶅瓨鍦�");
         }
-        if (inspectionOrder.getInsOrderId() != null) {
-            throw new ErrorException("璇ユ楠屽鎵樺崟宸茬粦瀹氭垚鍝佷笅鍗曪紝涓嶈兘閲嶅鎻愪氦");
+        existing = inspectionOrderBindingMapper.selectByRequest(requestUserId, requestId);
+        if (existing != null) {
+            return resolveIdempotentRequest(existing, requestHash);
         }
         if (inspectionOrder.getCommissionUnitId() == null) {
             throw new ErrorException("璇峰厛瀹屽杽濮旀墭鍗曚綅");
@@ -310,16 +307,60 @@
         Integer insOrderId = insOrderService.addInsOrder(insPlaceOrderDto.getSampleList(), insPlaceOrderDto.getInsOrder());
         Long sampleTakerUserId = SecurityUtils.getUserId();
         User sampleTaker = sampleTakerUserId == null ? null : userMapper.selectById(sampleTakerUserId);
-        int updated = baseMapper.update(null, Wrappers.<InspectionOrder>lambdaUpdate()
-                .eq(InspectionOrder::getInspectionOrderId, inspectionOrder.getInspectionOrderId())
-                .isNull(InspectionOrder::getInsOrderId)
-                .set(InspectionOrder::getInsOrderId, insOrderId)
-                .set(InspectionOrder::getSampleTakerUserId, sampleTakerUserId == null ? null : sampleTakerUserId.intValue())
-                .set(InspectionOrder::getSampleTakerUser, sampleTaker == null ? null : sampleTaker.getName()));
-        if (updated != 1) {
-            throw new ErrorException("妫�楠屽鎵樺崟宸茶鍏朵粬涓嬪崟缁戝畾锛岃鍒锋柊鍚庨噸璇�");
-        }
+        InspectionOrderBinding binding = new InspectionOrderBinding();
+        binding.setInspectionOrderId(inspectionOrder.getInspectionOrderId());
+        binding.setInsOrderId(insOrderId);
+        binding.setSourceType("NEW");
+        binding.setRequestId(requestId);
+        binding.setRequestHash(requestHash);
+        binding.setRequestUserId(requestUserId);
+        binding.setSampleTakerUserId(sampleTakerUserId == null ? null : sampleTakerUserId.intValue());
+        binding.setSampleTakerUser(sampleTaker == null ? null : sampleTaker.getName());
+        binding.setSampleData(LocalDate.now());
+        binding.setOrderDeleted(0);
+        binding.setCreateUser(requestUserId);
+        binding.setCreateTime(LocalDateTime.now());
+        inspectionOrderBindingMapper.insert(binding);
         return insOrderId;
+    }
+
+    private String normalizeRequestId(String requestId) {
+        if (StrUtil.isBlank(requestId)) {
+            throw new ErrorException("缂哄皯涓嬪崟璇锋眰鍙凤紝璇峰埛鏂伴〉闈㈠悗閲嶈瘯");
+        }
+        try {
+            return UUID.fromString(requestId.trim()).toString();
+        } catch (IllegalArgumentException e) {
+            throw new ErrorException("涓嬪崟璇锋眰鍙锋牸寮忛敊璇紝璇峰埛鏂伴〉闈㈠悗閲嶈瘯");
+        }
+    }
+
+    private Integer resolveIdempotentRequest(InspectionOrderBinding existing, String requestHash) {
+        if (!Objects.equals(existing.getRequestHash(), requestHash)) {
+            throw new ErrorException("璇锋眰鍙峰凡琚叾浠栦笅鍗曞唴瀹逛娇鐢紝璇烽噸鏂板彂璧蜂笅鍗�");
+        }
+        if (Integer.valueOf(1).equals(existing.getOrderDeleted())) {
+            throw new ErrorException("鍘熻鍗曞凡鍒犻櫎锛岃閲嶆柊鍙戣捣涓嬪崟");
+        }
+        return existing.getInsOrderId();
+    }
+
+    private String calculateRequestHash(InsPlaceOrderDto dto) {
+        LinkedHashMap<String, Object> content = new LinkedHashMap<>();
+        content.put("inspectionOrderId", dto.getInspectionOrderId());
+        content.put("insOrder", dto.getInsOrder());
+        content.put("sampleList", dto.getSampleList());
+        try {
+            byte[] digest = MessageDigest.getInstance("SHA-256")
+                    .digest(JSON.toJSONString(content).getBytes(StandardCharsets.UTF_8));
+            StringBuilder result = new StringBuilder(64);
+            for (byte value : digest) {
+                result.append(String.format("%02x", value & 0xff));
+            }
+            return result.toString();
+        } catch (Exception e) {
+            throw new ErrorException("涓嬪崟璇锋眰鏍¢獙澶辫触");
+        }
     }
 
     private void fillInsOrderFromInspectionOrder(InspectionOrder inspectionOrder, InsOrder insOrder) {
@@ -361,16 +402,7 @@
 
     @Override
     public void syncEntrustCode(Integer insOrderId) {
-        if (insOrderId == null) {
-            return;
-        }
-        InsOrder insOrder = insOrderService.getById(insOrderId);
-        if (insOrder == null || StrUtil.isBlank(insOrder.getEntrustCode())) {
-            return;
-        }
-        baseMapper.update(null, Wrappers.<InspectionOrder>lambdaUpdate()
-                .eq(InspectionOrder::getInsOrderId, insOrderId)
-                .set(InspectionOrder::getEntrustCode, insOrder.getEntrustCode()));
+        // 濮旀墭缂栧彿灞炰簬鍏蜂綋鎴愬搧璁㈠崟锛岄〉闈㈤�氳繃缁戝畾鍏崇郴瀹炴椂璇诲彇锛屼笉鍐嶅洖鍐欏鎵樺崟涓昏〃銆�
     }
 
     @Override
@@ -382,12 +414,15 @@
         if (insReport == null || !Integer.valueOf(1).equals(insReport.getIsRatify())) {
             return;
         }
-        InspectionOrder inspectionOrder = baseMapper.selectOne(Wrappers.<InspectionOrder>lambdaQuery()
-                .eq(InspectionOrder::getInsOrderId, insReport.getInsOrderId())
+        InspectionOrderBinding binding = inspectionOrderBindingMapper.selectOne(Wrappers.<InspectionOrderBinding>lambdaQuery()
+                .eq(InspectionOrderBinding::getInsOrderId, insReport.getInsOrderId())
+                .eq(InspectionOrderBinding::getOrderDeleted, 0)
                 .last("limit 1"));
-        if (inspectionOrder == null) {
+        if (binding == null) {
             return;
         }
+        InspectionOrder inspectionOrder = baseMapper.selectById(binding.getInspectionOrderId());
+        if (inspectionOrder == null) return;
 
         String sourceUrl = StrUtil.isBlank(insReport.getUrlS()) ? insReport.getUrl() : insReport.getUrlS();
         if (StrUtil.isBlank(sourceUrl)) {
@@ -396,8 +431,8 @@
         String sourceFileName = sourceUrl.substring(sourceUrl.lastIndexOf('/') + 1);
         String extension = sourceFileName.lastIndexOf('.') >= 0
                 ? sourceFileName.substring(sourceFileName.lastIndexOf('.')) : ".docx";
-        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss"))
-                + "_" + inspectionOrder.getInspectionOrderCode() + "_濮旀墭鍗曟姤鍛�" + extension;
+        String fileName = inspectionOrder.getInspectionOrderCode() + "_order_" + insReport.getInsOrderId()
+                + "_report_" + insReportId + "_" + UUID.randomUUID() + extension;
         Path sourcePath = Paths.get(wordUrl + sourceUrl.replaceFirst("/word", ""));
         Path targetPath = Paths.get(wordUrl, fileName);
         try {
@@ -405,9 +440,26 @@
                 throw new ErrorException("姝e紡鎶ュ憡鏂囦欢涓嶅瓨鍦紝鏃犳硶鍚屾鍒版楠屽鎵樺崟");
             }
             Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
-            baseMapper.update(null, Wrappers.<InspectionOrder>lambdaUpdate()
-                    .eq(InspectionOrder::getInspectionOrderId, inspectionOrder.getInspectionOrderId())
-                    .set(InspectionOrder::getFileUrl, "/word/" + fileName));
+            InspectionOrderAttachment attachment = inspectionOrderAttachmentMapper.selectOne(
+                    Wrappers.<InspectionOrderAttachment>lambdaQuery()
+                            .eq(InspectionOrderAttachment::getInsReportId, insReportId).last("limit 1"));
+            if (attachment == null) {
+                attachment = new InspectionOrderAttachment();
+                attachment.setInsReportId(insReportId);
+                attachment.setSourceType("REPORT");
+                attachment.setCreateUser(SecurityUtils.getUserId().intValue());
+                attachment.setCreateTime(LocalDateTime.now());
+            }
+            attachment.setInspectionOrderId(binding.getInspectionOrderId());
+            attachment.setBindingId(binding.getId());
+            attachment.setFileName(fileName);
+            attachment.setFileUrl("/word/" + fileName);
+            attachment.setUpdateTime(LocalDateTime.now());
+            if (attachment.getId() == null) {
+                inspectionOrderAttachmentMapper.insert(attachment);
+            } else {
+                inspectionOrderAttachmentMapper.updateById(attachment);
+            }
         } catch (ErrorException e) {
             throw e;
         } catch (Exception e) {
@@ -428,25 +480,32 @@
                 || StrUtil.isNotBlank(insOrder.getEntrustCode())) {
             throw new ErrorException("褰撳墠涓嬪崟宸茶繘鍏ユ楠屾祦绋嬫垨宸茬敓鎴愬鎵樼紪鍙凤紝涓嶅厑璁稿彉鏇村叧鑱�");
         }
-        InspectionOrder target = baseMapper.selectById(inspectionOrderId);
-        if (target == null || target.getInsOrderId() != null) {
-            throw new ErrorException("鐩爣妫�楠屽鎵樺崟涓嶅瓨鍦ㄦ垨宸茶缁戝畾");
+        InspectionOrderBinding binding = inspectionOrderBindingMapper.selectByOrderIdForUpdate(insOrderId);
+        if (binding == null || Integer.valueOf(1).equals(binding.getOrderDeleted())) {
+            throw new ErrorException("鎴愬搧涓嬪崟鏈粦瀹氭湁鏁堟楠屽鎵樺崟");
         }
-        InspectionOrder oldInspectionOrder = baseMapper.selectOne(Wrappers.<InspectionOrder>lambdaQuery()
-                .eq(InspectionOrder::getInsOrderId, insOrderId));
-        baseMapper.update(null, Wrappers.<InspectionOrder>lambdaUpdate()
-                .eq(InspectionOrder::getInsOrderId, insOrderId)
-                .set(InspectionOrder::getInsOrderId, null));
-        int updated = baseMapper.update(null, Wrappers.<InspectionOrder>lambdaUpdate()
-                .eq(InspectionOrder::getInspectionOrderId, inspectionOrderId)
-                .isNull(InspectionOrder::getInsOrderId)
-                .set(InspectionOrder::getInsOrderId, insOrderId));
-        if (updated != 1) {
-            throw new ErrorException("鐩爣妫�楠屽鎵樺崟宸茶鍏朵粬涓嬪崟缁戝畾锛岃鍒锋柊鍚庨噸璇�");
+        InspectionOrder target = baseMapper.selectByIdForUpdate(inspectionOrderId);
+        if (target == null) {
+            throw new ErrorException("鐩爣妫�楠屽鎵樺崟涓嶅瓨鍦�");
         }
+        if (Objects.equals(binding.getInspectionOrderId(), inspectionOrderId)) {
+            throw new ErrorException("鐩爣妫�楠屽鎵樺崟涓庡綋鍓嶅鎵樺崟鐩稿悓");
+        }
+        if (!Objects.equals(target.getCommissionUnitId(), insOrder.getCompanyId())) {
+            throw new ErrorException("鐩爣妫�楠屽鎵樺崟涓庢垚鍝佽鍗曠殑濮旀墭鍗曚綅涓嶄竴鑷�");
+        }
+        Integer oldInspectionOrderId = binding.getInspectionOrderId();
+        binding.setInspectionOrderId(inspectionOrderId);
+        binding.setUpdateUser(SecurityUtils.getUserId().intValue());
+        binding.setUpdateTime(LocalDateTime.now());
+        inspectionOrderBindingMapper.updateById(binding);
+        inspectionOrderAttachmentMapper.update(null, Wrappers.<InspectionOrderAttachment>lambdaUpdate()
+                .eq(InspectionOrderAttachment::getBindingId, binding.getId())
+                .set(InspectionOrderAttachment::getInspectionOrderId, inspectionOrderId)
+                .set(InspectionOrderAttachment::getUpdateTime, LocalDateTime.now()));
         InspectionOrderBindLog bindLog = new InspectionOrderBindLog();
         bindLog.setInsOrderId(insOrderId);
-        bindLog.setOldInspectionOrderId(oldInspectionOrder == null ? null : oldInspectionOrder.getInspectionOrderId());
+        bindLog.setOldInspectionOrderId(oldInspectionOrderId);
         bindLog.setNewInspectionOrderId(inspectionOrderId);
         bindLog.setChangeReason(reason.trim());
         bindLog.setCreateUser(SecurityUtils.getUserId().intValue());
@@ -464,33 +523,71 @@
      */
     @Override
     public boolean uploadInspectionOrderFile(MultipartFile file, Integer inspectionOrderId) {
-        String urlString;
-        String pathName;
-        try {
-            String path = wordUrl;
-            File realpath = new File(path);
-            if (!realpath.exists()) {
-                realpath.mkdirs();
-            }
-            pathName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss")) + "_" + file.getOriginalFilename();
-            urlString = realpath + "/" + pathName;
-            file.transferTo(new File(urlString));
-
-            baseMapper.update(null, Wrappers.<InspectionOrder>lambdaUpdate()
-                    .eq(InspectionOrder::getInspectionOrderId, inspectionOrderId)
-                    .set(InspectionOrder::getFileUrl, "/word/" + pathName));
-
-
-        } catch (Exception e) {
-            throw new ErrorException("鏂囦欢涓婁紶澶辫触");
-        }
-        return true;
+        throw new ErrorException("璇峰湪涓嬪崟璁板綍涓�夋嫨鍏蜂綋璁㈠崟鍚庝笂浼犻檮浠�");
     }
 
     @Override
-    public void exportInspectionOrder(Integer inspectionOrderId, HttpServletResponse response) {
+    public boolean uploadInspectionOrderBindingFile(MultipartFile file, Long bindingId) {
+        if (file == null || file.isEmpty() || bindingId == null) {
+            throw new ErrorException("璇烽�夋嫨涓嬪崟璁板綍鍜屼笂浼犳枃浠�");
+        }
+        InspectionOrderBinding binding = inspectionOrderBindingMapper.selectById(bindingId);
+        if (binding == null || Integer.valueOf(1).equals(binding.getOrderDeleted())) {
+            throw new ErrorException("涓嬪崟璁板綍涓嶅瓨鍦ㄦ垨璁㈠崟宸插垹闄�");
+        }
+        try {
+            File realpath = new File(wordUrl);
+            if (!realpath.exists() && !realpath.mkdirs()) {
+                throw new ErrorException("鏂囦欢鐩綍鍒涘缓澶辫触");
+            }
+            String originalName = new File(file.getOriginalFilename() == null ? "attachment" : file.getOriginalFilename()).getName();
+            String pathName = "binding_" + bindingId + "_" + UUID.randomUUID() + "_" + originalName;
+            file.transferTo(new File(realpath, pathName));
+            InspectionOrderAttachment attachment = new InspectionOrderAttachment();
+            attachment.setInspectionOrderId(binding.getInspectionOrderId());
+            attachment.setBindingId(bindingId);
+            attachment.setSourceType("MANUAL");
+            attachment.setFileName(originalName);
+            attachment.setFileUrl("/word/" + pathName);
+            attachment.setCreateUser(SecurityUtils.getUserId().intValue());
+            attachment.setCreateTime(LocalDateTime.now());
+            inspectionOrderAttachmentMapper.insert(attachment);
+            return true;
+        } catch (ErrorException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new ErrorException("鏂囦欢涓婁紶澶辫触");
+        }
+    }
+
+    @Override
+    public void exportInspectionOrder(Integer inspectionOrderId, Long bindingId, HttpServletResponse response) {
         InspectionOrder inspectionOrder = baseMapper.selectById(inspectionOrderId);
+        if (inspectionOrder == null) {
+            throw new ErrorException("妫�楠屽鎵樺崟涓嶅瓨鍦�");
+        }
         InspectionOrderExportDto inspectionOrderExportDto = extracted(inspectionOrder);
+        if (bindingId == null) {
+            inspectionOrderExportDto.setEntrustCode(null);
+            inspectionOrderExportDto.setSampleTakerUser(null);
+            inspectionOrderExportDto.setSampleTakerUserId(null);
+            inspectionOrderExportDto.setSampleData(null);
+            inspectionOrderExportDto.setSampleDataString(null);
+        } else {
+            InspectionOrderBinding binding = inspectionOrderBindingMapper.selectById(bindingId);
+            if (binding == null || !Objects.equals(binding.getInspectionOrderId(), inspectionOrderId)) {
+                throw new ErrorException("涓嬪崟璁板綍涓嶅睘浜庤妫�楠屽鎵樺崟");
+            }
+            InsOrder insOrder = insOrderService.getById(binding.getInsOrderId());
+            inspectionOrderExportDto.setEntrustCode(insOrder == null ? null : insOrder.getEntrustCode());
+            inspectionOrderExportDto.setSampleTakerUser(binding.getSampleTakerUser());
+            inspectionOrderExportDto.setSampleTakerUserId(binding.getSampleTakerUserId());
+            inspectionOrderExportDto.setSampleData(binding.getSampleData());
+            if (binding.getSampleData() != null) {
+                inspectionOrderExportDto.setSampleDataString(binding.getSampleData()
+                        .format(DateTimeFormatter.ofPattern("yyyy骞碝M鏈坉d鏃�")));
+            }
+        }
         List<InspectionOrderDetail> list = inspectionOrderDetailService.list(Wrappers.<InspectionOrderDetail>lambdaQuery()
                 .eq(InspectionOrderDetail::getInspectionOrderId, inspectionOrderId));
         int index = 1;

--
Gitblit v1.9.3