From 56e6e0bf18c39a933aec78762b636fdf2efa8d68 Mon Sep 17 00:00:00 2001
From: zouyu <2723363702@qq.com>
Date: 星期一, 08 十二月 2025 17:59:24 +0800
Subject: [PATCH] 外购成品检验报告生成功能

---
 inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java | 1359 +++++++++++++++++++++++++++++++++++++---------------------
 1 files changed, 855 insertions(+), 504 deletions(-)

diff --git a/inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java b/inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java
index c1f9c46..7cd35f6 100644
--- a/inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java
+++ b/inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java
@@ -2,6 +2,7 @@
 
 import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.collection.CollUtil;
+import cn.hutool.core.collection.CollectionUtil;
 import cn.hutool.core.date.DateTime;
 import cn.hutool.core.date.DateUtil;
 import cn.hutool.core.util.ObjectUtil;
@@ -32,9 +33,11 @@
 import com.ruoyi.basic.service.StandardTemplateService;
 import com.ruoyi.common.constant.DictDataConstants;
 import com.ruoyi.common.constant.InsOrderTypeConstants;
+import com.ruoyi.common.constant.MenuJumpPathConstants;
 import com.ruoyi.common.core.domain.entity.Custom;
 import com.ruoyi.common.core.domain.entity.InformationNotification;
 import com.ruoyi.common.core.domain.entity.User;
+import com.ruoyi.common.enums.OrderType;
 import com.ruoyi.common.utils.*;
 import com.ruoyi.framework.exception.ErrorException;
 import com.ruoyi.inspect.dto.*;
@@ -44,9 +47,8 @@
 import com.ruoyi.inspect.util.HackLoopTableRenderPolicy;
 import com.ruoyi.inspect.vo.InsOrderPlanTaskSwitchVo;
 import com.ruoyi.inspect.vo.InsOrderPlanVO;
+import com.ruoyi.inspect.vo.InsSampleUserVO;
 import com.ruoyi.performance.mapper.AuxiliaryOutputWorkingHoursMapper;
-import com.ruoyi.performance.mapper.PerformanceShiftMapper;
-import com.ruoyi.performance.mapper.ShiftTimeMapper;
 import com.ruoyi.performance.pojo.AuxiliaryOutputWorkingHours;
 import com.ruoyi.performance.service.AuxiliaryOutputWorkingHoursService;
 import com.ruoyi.system.mapper.CustomMapper;
@@ -55,8 +57,8 @@
 import com.ruoyi.system.service.InformationNotificationService;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.poi.xwpf.usermodel.*;
-import org.jetbrains.annotations.NotNull;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.core.io.ClassPathResource;
 import org.springframework.mock.web.MockMultipartFile;
 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 import org.springframework.stereotype.Service;
@@ -69,13 +71,11 @@
 import java.math.RoundingMode;
 import java.nio.file.Files;
 import java.nio.file.Paths;
+import java.text.DecimalFormat;
 import java.text.SimpleDateFormat;
-import java.time.LocalDate;
 import java.time.LocalDateTime;
-import java.time.LocalTime;
 import java.time.format.DateTimeFormatter;
 import java.util.*;
-import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
@@ -102,14 +102,9 @@
     private InsOrderStateMapper insOrderStateMapper;
     @Resource
     private InsProductMapper insProductMapper;
-    @Resource
-    private ShiftTimeMapper shiftTimeMapper;
-    @Resource
-    private PerformanceShiftMapper performanceShiftMapper;
+
     @Value("${wordUrl}")
     private String wordUrl;
-    @Value("${twoCode}")
-    private String twoCode;
     @Resource
     private InsReportMapper insReportMapper;
     @Resource
@@ -117,11 +112,9 @@
     @Resource
     private InsProductUserMapper insProductUserMapper;
     @Resource
-    private InsUnPassService insUnPassService;
+    private AuxiliaryOutputWorkingHoursService auxiliaryOutputWorkingHoursService;
     @Resource
     private AuxiliaryOutputWorkingHoursMapper auxiliaryOutputWorkingHoursMapper;
-    @Resource
-    private AuxiliaryOutputWorkingHoursService auxiliaryOutputWorkingHoursService;
     @Resource
     private InformationNotificationService informationNotificationService;
     @Resource
@@ -130,11 +123,12 @@
     private CustomMapper customMapper;
     @Value("${file.path}")
     private String imgUrl;
-
     @Resource
     private InsOrderFileMapper insOrderFileMapper;
     @Resource
     private IfsInventoryQuantityMapper ifsInventoryQuantityMapper;
+    @Resource
+    private IfsPartPropsRecordMapper ifsPartPropsRecordMapper;
     @Resource
     private InsReportService insReportService;
     @Resource
@@ -149,8 +143,7 @@
     private InsOrderFactoryVerifyMapper insOrderFactoryVerifyMapper;
     @Resource
     private InsOrderFactoryVerifyItemService insOrderFactoryVerifyItemService;
-    @Value("${file.licenseUrl}")
-    private String licenseUrl;
+
     @Resource
     private SpotCheckQuarterItemMapper spotCheckQuarterItemMapper;
     @Resource
@@ -161,15 +154,19 @@
     private InsOrderDeviceRecordService insOrderDeviceRecordService;
     @Resource
     private ISysDictTypeService iSysDictTypeService;
+    @Resource
+    private InsOrderRatesService insOrderRatesService;
+    @Resource
+    private InsProductDeviationWarningService insProductDeviationWarningService;
+    @Resource
+    private InsProductDeviationWarningDetailService insProductDeviationWarningDetailService;
 
 
     @Override
     public IPage<InsOrderPlanVO> selectInsOrderPlanList(Page page, InsOrderPlanDTO insOrderPlanDTO) {
         // todo: 浠呯湅鑷繁鎴栬�呭疄楠屽
         //鑾峰彇褰撳墠浜烘墍灞炲疄楠屽id
-
         String laboratory = null;
-
         String userName = null;
         Integer userId = null;
         if (ObjectUtil.isNotEmpty(insOrderPlanDTO.getUserId())) {
@@ -235,17 +232,19 @@
 
         // 鏌ヨ鍘傚瀵嗗害
         String supplierDensity = "";
-        SampleProductDto sampleProductDto = list.get(0);
+        if (CollectionUtils.isNotEmpty(list)) {
+            SampleProductDto sampleProductDto = list.get(0);
 
-        // 鍒ゆ柇鏈夋病鏈夌粦瀹氬瀷鍙�
-        String modelValue = insSampleMapper.selectSupplierDensityModel(sampleProductDto.getSample(),
-                order.getProduction(),
-                sampleProductDto.getModel());
-        if (StringUtils.isNotBlank(modelValue)) {
-            supplierDensity = modelValue;
-        } else {
-            supplierDensity = insSampleMapper.selectSupplierDensity(sampleProductDto.getSample(),
-                    order.getProduction());
+            // 鍒ゆ柇鏈夋病鏈夌粦瀹氬瀷鍙�
+            String modelValue = insSampleMapper.selectSupplierDensityModel(sampleProductDto.getSample(),
+                    order.getProduction(),
+                    sampleProductDto.getModel());
+            if (StringUtils.isNotBlank(modelValue)) {
+                supplierDensity = modelValue;
+            } else {
+                supplierDensity = insSampleMapper.selectSupplierDensity(sampleProductDto.getSample(),
+                        order.getProduction());
+            }
         }
         map.put("supplierDensity", supplierDensity);
         return map;
@@ -256,16 +255,13 @@
         List<InsProduct> insProducts = new ArrayList<>();
         switch (dto.getType()) {
             case 0:
-                insProducts = insSampleMapper.getInsProduct1(dto.getId(), dto.getLaboratory(), dto.getCableTag(), dto.getRepetitionTag(), null);
-                //鏍峰搧
-                break;
             case 4:
-                //鐢电紗閰嶇疆
-                insProducts = insSampleMapper.getInsProduct1(dto.getId(), dto.getLaboratory(), dto.getCableTag(), dto.getRepetitionTag(), null);
+                //濮旀墭
+                insProducts = insSampleMapper.getInsProduct1(dto.getId(), dto.getLaboratory(), dto.getCableTag(), dto.getRepetitionTag());
                 break;
             case 5:
                 //鍘熸潗鏂欎笅鍗�
-                insProducts = insSampleMapper.getInsProduct6(dto.getId(), dto.getLaboratory(), dto.getRawMaterialTag(), null);
+                insProducts = insSampleMapper.getInsProduct6(dto.getId(), dto.getLaboratory(), dto.getRawMaterialTag());
                 break;
         }
         if (BeanUtil.isEmpty(insProducts)) {
@@ -278,7 +274,8 @@
     }
 
     @Override
-    public List<String> checkSubmitPlan(Integer orderId, String laboratory) {
+    public Map<String,Object> checkSubmitPlan(Integer orderId, String laboratory) {
+        Map<String, Object> map = new HashMap<>();
         List<String> collect = new ArrayList<>();
         List<InsSample> insSamples = insSampleMapper.selectList(Wrappers.<InsSample>lambdaQuery().eq(InsSample::getInsOrderId, orderId).select(InsSample::getId));
         List<Integer> ids = insSamples.stream().map(a -> a.getId()).collect(Collectors.toList());
@@ -304,7 +301,19 @@
                 return insProduct.getInspectionItem() + "-" + insProduct.getInspectionItemSubclass();
             }).collect(Collectors.toList());
         }
-        return collect;
+        //鏌ヨifs鎷嗗垎璁㈠崟鏄惁鏈夊凡涓嬪崟浣嗘槸鏈瀹岀殑鍗曞瓙
+        long count = 0L;
+        InsOrder insOrder = insOrderMapper.selectById(orderId);
+        if(Objects.nonNull(insOrder.getIfsInventoryId())){
+            IfsInventoryQuantity one = ifsInventoryQuantityMapper.selectById(insOrder.getIfsInventoryId());
+            //杩囨护鍑轰笉鍚堟牸鎴栨湭鎻愪氦鐨勫崟瀛�
+            count = ifsInventoryQuantityMapper.selectSplitOrderList(one.getPartNo(),one.getLineNo(),one.getReleaseNo(),one.getReceiptNo(),one.getOrderNo())
+                    .stream()
+                    .filter(f->(Objects.nonNull(f.getInsOrderId()) && !Objects.equals(f.getInsOrderId(),orderId)) && (Objects.isNull(f.getInsResult()) || 0==f.getInsResult())).count();
+        }
+        map.put("errorMsg",collect);
+        map.put("unInsOrderCount",count);
+        return map;
     }
 
     @Override
@@ -362,15 +371,16 @@
 
     @Override
     @Transactional(rollbackFor = Exception.class)
-    public void saveInsContext(Map<String, Object> insContext, Integer currentTable, Integer currentSampleId, Integer orderId, String sonLaboratory) {
+    public void saveInsContext(SaveInsContextDto saveInsContextDto) {
+        Map<String, Object> insContext = JSON.parseObject(saveInsContextDto.getParam(), Map.class);
         Integer userId = SecurityUtils.getUserId().intValue();
-        InsSample insSample = insSampleMapper.selectById(currentSampleId);
+        InsSample insSample = insSampleMapper.selectById(saveInsContextDto.getSampleId());
         insContext.forEach((k, v) -> {
             JSONObject jo = JSON.parseObject(JSON.toJSONString(v));
             InsProduct insProduct = new InsProduct();
             insProduct.setId(Integer.parseInt(k));
             InsProduct product = insProductMapper.selectById(insProduct.getId());
-            if (currentTable.equals(product.getTemplateId()) && currentSampleId.equals(product.getInsSampleId())) {
+            if (saveInsContextDto.getCurrentTable().equals(product.getTemplateId()) && saveInsContextDto.getSampleId().equals(product.getInsSampleId())) {
                 List<InsProductResult> oldResults = insProductResultMapper.selectList(Wrappers.<InsProductResult>lambdaQuery()
                         .eq(InsProductResult::getInsProductId, insProduct.getId()));
                 InsProductResult newResult = new InsProductResult();
@@ -500,22 +510,34 @@
                     }
                 }
 
-                //鏌ヨ妫�楠屽崟淇℃伅
                 // 娣诲姞宸ユ椂
-                InsProduct finalInsProduct = insProductMapper.selectById(product.getId());
-                threadPoolTaskExecutor.execute(() -> {
-                    InsOrder insOrder = insOrderMapper.selectById(insSample.getInsOrderId());
-                    this.addAuxiliary(userId, finalInsProduct, insOrder);
-                });
+                // 鍒ゆ柇鏄惁鍙槸鍙備笌璁$畻鍊�, 鍙備笌璁$畻鍊煎疄闄呮病鏈夊~鍐�
+                if (StringUtils.isNotBlank(newResult.getInsValue()) && !newResult.getInsValue().equals("[]")) {
+                    threadPoolTaskExecutor.execute(() -> {
+                        InsProduct finalInsProduct = insProductMapper.selectById(product.getId());
+                        InsOrder insOrder = insOrderMapper.selectById(insSample.getInsOrderId());
+                        this.addAuxiliary(userId, finalInsProduct, insOrder);
+                    });
+                } else {
+                    // 鍒ゆ柇鏄惁鏄病鏈夋楠屽�肩殑鍐呭
+                    if (saveInsContextDto.getIsNoTestValue() != null && saveInsContextDto.getIsNoTestValue() == 1) {
+                        threadPoolTaskExecutor.execute(() -> {
+                            InsProduct finalInsProduct = insProductMapper.selectById(product.getId());
+                            InsOrder insOrder = insOrderMapper.selectById(insSample.getInsOrderId());
+                            this.addAuxiliary(userId, finalInsProduct, insOrder);
+                        });
+                    }
+                }
+
             }
         });
         String sampleIdStr = insContext.keySet().stream().findFirst().orElse(null);
         if (sampleIdStr != null) {
-            int count = insProductMapper.selectInsProductCountByOrderId(orderId);
+            int count = insProductMapper.selectInsProductCountByOrderId(saveInsContextDto.getOrderId());
             if (count == 0) {
                 insOrderStateMapper.update(new InsOrderState(), Wrappers.<InsOrderState>lambdaUpdate()
-                        .eq(InsOrderState::getInsOrderId, orderId)
-                        .eq(InsOrderState::getLaboratory, sonLaboratory)
+                        .eq(InsOrderState::getInsOrderId, saveInsContextDto.getOrderId())
+                        .eq(InsOrderState::getLaboratory, saveInsContextDto.getSonLaboratory())
                         .set(InsOrderState::getInsState, 2));
             }
         }
@@ -523,55 +545,60 @@
 
         // 娣诲姞璁惧璁板綍
         threadPoolTaskExecutor.execute(() -> {
-            InsOrder order = insOrderMapper.selectById(insSample.getInsOrderId());
-            User user = userMapper.selectById(userId);
-            // 鏌ヨ璁惧浣跨敤璁板綍鏌ヨ璇ヨ鍗曠殑浣跨敤璁板綍
-            List<InsOrderDeviceRecordDto> deviceRecordDtoList = insOrderDeviceRecordMapper.selectDeviceNumber(insSample.getInsOrderId());
-            Set<String> recordCodeset = deviceRecordDtoList.stream().map(InsOrderDeviceRecordDto::getManagementNumber).collect(Collectors.toSet());
+            // 娣诲姞璁惧浣跨敤璁板綍
+            addDeviceRecord(insSample, userId);
+        });
+    }
 
-            // 鑾峰彇璁㈠崟璁惧缂栧彿
-            List<InsProductResult> resultList = insProductResultMapper.selectResultByOrderId(insSample.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);
-                    }
+    private synchronized void addDeviceRecord(InsSample insSample, Integer userId) {
+        InsOrder order = insOrderMapper.selectById(insSample.getInsOrderId());
+        User user = userMapper.selectById(userId);
+        // 鏌ヨ璁惧浣跨敤璁板綍鏌ヨ璇ヨ鍗曠殑浣跨敤璁板綍
+        List<InsOrderDeviceRecordDto> deviceRecordDtoList = insOrderDeviceRecordMapper.selectDeviceNumber(insSample.getInsOrderId());
+        Set<String> recordCodeset = deviceRecordDtoList.stream().map(InsOrderDeviceRecordDto::getManagementNumber).collect(Collectors.toSet());
+
+        // 鑾峰彇璁㈠崟璁惧缂栧彿
+        List<InsProductResult> resultList = insProductResultMapper.selectResultByOrderId(insSample.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 = insOrderDeviceRecordMapper.selectDeviceIdsByNumbers(orderDeviceNumbers);
-                List<InsOrderDeviceRecord> collect = orderDeviceIds.stream().map(deviceId -> {
-                    InsOrderDeviceRecord insOrderDeviceRecord = new InsOrderDeviceRecord();
-                    insOrderDeviceRecord.setInsOrderId(insSample.getInsOrderId());
-                    insOrderDeviceRecord.setDeviceId(deviceId);
-                    insOrderDeviceRecord.setSampleCode(order.getEntrustCode());
-                    insOrderDeviceRecord.setUseBefore(1);
-                    insOrderDeviceRecord.setUseAfter(1);
-                    insOrderDeviceRecord.setUsePerson(user.getName());
-                    insOrderDeviceRecord.setUsePersonId(user.getId());
-                    return insOrderDeviceRecord;
-                }).collect(Collectors.toList());
+        }
+        // 1.鍒ゆ柇鏄惁鏈夋病鏈夋坊鍔犵殑浣跨敤璁板綍
+        Set<String> orderDeviceNumbers = getDeviceDifference(deviceCodeSet, recordCodeset);
+        // 娣诲姞浣跨敤璁板綍, 鏍规嵁缂栧彿鏌ヨ璁惧id
+        if (CollectionUtils.isNotEmpty(orderDeviceNumbers)) {
+            List<Integer> orderDeviceIds = insOrderDeviceRecordMapper.selectDeviceIdsByNumbers(orderDeviceNumbers);
+            List<InsOrderDeviceRecord> collect = orderDeviceIds.stream().map(deviceId -> {
+                InsOrderDeviceRecord insOrderDeviceRecord = new InsOrderDeviceRecord();
+                insOrderDeviceRecord.setInsOrderId(insSample.getInsOrderId());
+                insOrderDeviceRecord.setDeviceId(deviceId);
+                insOrderDeviceRecord.setSampleCode(order.getEntrustCode());
+                insOrderDeviceRecord.setUseBefore(1);
+                insOrderDeviceRecord.setUseAfter(1);
+                insOrderDeviceRecord.setUsePerson(user.getName());
+                insOrderDeviceRecord.setUsePersonId(user.getId());
+                return insOrderDeviceRecord;
+            }).collect(Collectors.toList());
 
-                insOrderDeviceRecordService.saveBatch(collect);
+            insOrderDeviceRecordService.saveBatch(collect);
 
-            }
+        }
 
-            // 2.鍒ゆ柇鏄惁鍙栨秷浜嗚澶囦娇鐢�
-            Set<String> repoprNumbers = getDeviceDifference(recordCodeset, deviceCodeSet);
-            if (CollectionUtils.isNotEmpty(repoprNumbers)) {
-                List<Integer> reportDeviceIds = insOrderDeviceRecordMapper.selectDeviceIdsByNumbers(repoprNumbers);
-                insOrderDeviceRecordMapper.delete(Wrappers.<InsOrderDeviceRecord>lambdaQuery()
-                        .in(InsOrderDeviceRecord::getDeviceId, reportDeviceIds)
-                        .eq(InsOrderDeviceRecord::getInsOrderId, insSample.getInsOrderId()));
-            }
-        });
+        // 2.鍒ゆ柇鏄惁鍙栨秷浜嗚澶囦娇鐢�
+        Set<String> repoprNumbers = getDeviceDifference(recordCodeset, deviceCodeSet);
+        if (CollectionUtils.isNotEmpty(repoprNumbers)) {
+            List<Integer> reportDeviceIds = insOrderDeviceRecordMapper.selectDeviceIdsByNumbers(repoprNumbers);
+            insOrderDeviceRecordMapper.delete(Wrappers.<InsOrderDeviceRecord>lambdaQuery()
+                    .in(InsOrderDeviceRecord::getDeviceId, reportDeviceIds)
+                    .eq(InsOrderDeviceRecord::getInsOrderId, insSample.getInsOrderId()));
+        }
     }
 
     private static Set<String> getDeviceDifference(Set<String> number1, Set<String> number2) {
@@ -598,20 +625,6 @@
      */
     private void getTemplateThing(InsOrder order, List<InsProduct> insProducts) {
         Set<Integer> set = new HashSet<>();
-        // 妫�楠岄」鍒嗙被+妫�楠岄」+妫�楠屽瓙椤圭殑鎷兼帴
-//        List<String> itemNameList = insProducts.stream().map(insProduct -> {
-//            String itemName = "";
-//            if (StringUtils.isNotBlank(insProduct.getInspectionItemClass())) {
-//                itemName += insProduct.getInspectionItemClass().trim();
-//            }
-//            if (StringUtils.isNotBlank(insProduct.getInspectionItem())) {
-//                itemName += insProduct.getInspectionItem().trim();
-//            }
-//            if (StringUtils.isNotBlank(insProduct.getInspectionItemSubclass())) {
-//                itemName += insProduct.getInspectionItemSubclass().trim();
-//            }
-//            return itemName;
-//        }).collect(Collectors.toList());
         // 鏌ヨ璁㈠崟鐘舵�佸垽鏂槸鍚︽槸鏌ュ巻鍙叉ā鏉�
         if (order.getIsFirstSubmit() != null && order.getIsFirstSubmit().equals(1)) {
             InsOrderState insOrderState = insOrderStateMapper.selectOne(Wrappers.<InsOrderState>lambdaQuery()
@@ -670,7 +683,7 @@
     }
 
     /**
-     * todo: 娓呴櫎娌℃湁浣跨敤鐨勬楠岄」
+     * todo: 鍘熷璁板綍妯℃澘娓呴櫎娌℃湁浣跨敤鐨勬楠岄」(鏆傛椂鏈塨ug鏃犳硶浣跨敤)
      * @param sheet
      * @param itemNameList
      */
@@ -755,9 +768,9 @@
 
     @Override
     @Transactional(rollbackFor = Exception.class)
-    public int submitPlan(Integer orderId, String laboratory, Integer verifyUser, String entrustCode) {
+    public int submitPlan(Integer orderId, String laboratory, Integer verifyUser, String entrustCode,Boolean registerInsResults) {
         InsOrder order = insOrderMapper.selectById(orderId);
-        // 鍒ゆ柇鏄惁鏈夐噸澶嶇紪鍙�, 鏈夐噸澶嶇紪鍙峰仛鎻愰啋
+        // 1. 鍒ゆ柇鏄惁鏈夐噸澶嶇紪鍙�, 鏈夐噸澶嶇紪鍙峰仛鎻愰啋
         Long codeCount = insOrderMapper.selectCount(Wrappers.<InsOrder>lambdaQuery()
                 .ne(InsOrder::getState, -1)
                 .ne(InsOrder::getIfsInventoryId, order.getIfsInventoryId())
@@ -766,7 +779,7 @@
             throw new ErrorException("褰撳墠缂栧彿鏈夐噸澶�, 璇峰厛鍘讳慨鏀归噸澶嶇紪鍙�");
         }
 
-        // 鍒ゆ柇璇ヨ鍗曟槸鍚︽槸绗竴娆$敓浜�
+        // 2. 鍒ゆ柇璇ヨ鍗曟槸鍚︽槸绗竴娆$敓浜�(鍚庣画鎶ュ憡鐢熸垚鍙彇绗竴娆℃彁浜ゆ椂闂�)
         if (!(order.getIsFirstSubmit() != null && order.getIsFirstSubmit().equals(1))) {
             insOrderMapper.update(null, Wrappers.<InsOrder>lambdaUpdate()
                     .eq(InsOrder::getId, orderId)
@@ -774,11 +787,12 @@
                     .set(InsOrder::getFirstSubmitDate, LocalDateTime.now()));
         }
 
+        // 3. 鍒ゆ柇鏄惁鏈夋湭妫�椤�
         List<InsSample> insSamples = insSampleMapper.selectList(Wrappers.<InsSample>lambdaQuery()
                 .eq(InsSample::getInsOrderId, orderId).select(InsSample::getId));
-        List<Integer> ids = insSamples.stream().map(a -> a.getId()).collect(Collectors.toList());
+        List<Integer> InsSampleIds = insSamples.stream().map(InsSample::getId).collect(Collectors.toList());
         List<InsProduct> insProducts = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
-                .in(InsProduct::getInsSampleId, ids)
+                .in(InsProduct::getInsSampleId, InsSampleIds)
                 .eq(InsProduct::getSonLaboratory, laboratory)
                 .eq(InsProduct::getState, 1)
                 .and(wrapper -> wrapper
@@ -786,37 +800,37 @@
                         .or()
                         .eq(InsProduct::getInsResult, 2)
                 )
-                .isNull(InsProduct::getInsFiberId)
-                .isNull(InsProduct::getInsFibersId)
                 .ne(InsProduct::getIsBinding, 1));
-        insProducts.addAll(insProductMapper.selectFiberInsProduct(ids, laboratory));
+        insProducts.addAll(insProductMapper.selectFiberInsProduct(InsSampleIds, laboratory));
         if (insProducts.size() > 0) {
             String str = "";
             int count = 0;
             for (InsProduct product : insProducts) {
                 count++;
-                str += "<br/>" + count + "锛�" + product.getInspectionItem() + " " + product.getInspectionItemSubclass() + "<br/>";
-
+                str +=  (count != 0 ? "\n" : "") + count + "锛�" +
+                        product.getInspectionItemClass() + " " +
+                        product.getInspectionItem() + " " +
+                        product.getInspectionItemSubclass();
             }
             if (ObjectUtils.isNotEmpty(str)) {
-                throw new ErrorException("<strong>瀛樺湪寰呮楠岀殑椤圭洰锛�</strong><br/>" + str);
+                throw new ErrorException("瀛樺湪寰呮楠岀殑椤圭洰锛�" + str);
             }
         }
+
+        // 4.淇敼妫�娴嬬粨鏋�
         insOrderStateMapper.update(null, Wrappers.<InsOrderState>lambdaUpdate().eq(InsOrderState::getInsOrderId, orderId)
                 .eq(InsOrderState::getLaboratory, laboratory)
                 .set(InsOrderState::getInsTime, LocalDateTime.now())
                 .set(InsOrderState::getInsState, 3)
                 .set(InsOrderState::getVerifyUser, verifyUser));
 
-        // 鍙戦�佹秷鎭�
+
+        // 5.鍙戦�佹秷鎭�氱煡缁欏鏍镐汉
         // 鏌ヨ褰撳墠浜轰俊鎭�
         Integer userId = SecurityUtils.getUserId().intValue();
         String userName = insProductMapper.selectUserById(userId).get("name");
-
         // 鏌ヨ鍙戦�佷汉淇℃伅
         String sendUserAccount = insProductMapper.selectUserById(verifyUser).get("account");
-
-
         InformationNotification info = new InformationNotification();
         info.setCreateUser(userName);
         info.setMessageType("2");
@@ -825,18 +839,19 @@
         info.setSenderId(userId);
         info.setConsigneeId(verifyUser);
         info.setViewStatus(false);
-        info.setJumpPath("b1-inspect-orderPlan-review");
+        info.setJumpPath(MenuJumpPathConstants.INSPECTION_REVIEW);
         informationNotificationService.addInformationNotification(info);
 
-        //澶嶆牳浜�--妫�楠屽崟鐩稿叧璐熻矗浜�
+        // 6.澶嶆牳浜�--鏂板妫�楠屽崟鐩稿叧璐熻矗浜�
         InsSampleUser insSampleUser = new InsSampleUser();
         insSampleUser.setUserId(verifyUser);
         insSampleUser.setInsSampleId(orderId);
         insSampleUser.setState(1);
         insSampleUser.setSonLaboratory(laboratory);
         insSampleUserMapper.insert(insSampleUser);
-        /*鏍¢獙涓�涓媟esult琛�*/
-        CompletableFuture.supplyAsync(() -> {
+
+        // 7.鏍¢獙涓�涓媟esult琛�(閬垮厤鍑虹幇澶氫釜妫�楠岄」缁撴灉)
+        threadPoolTaskExecutor.execute(() -> {
             List<Integer> ips = insProducts.stream().map(InsProduct::getId).distinct().collect(Collectors.toList());
             for (Integer ip : ips) {
                 List<InsProductResult> insProductResults = insProductResultMapper.selectList(Wrappers.<InsProductResult>lambdaQuery()
@@ -847,26 +862,245 @@
                     }
                 }
             }
-            return null;
         });
 
-        // 鎻愪氦鐢熸垚鎶ュ憡
+        // 8.鎻愪氦鐢熸垚鎶ュ憡
         this.generateReport(orderId);
 
-        // 娣诲姞涓存椂pdf鐢熸垚鍦板潃
+        // 9.娣诲姞涓存椂pdf鐢熸垚鍦板潃
         InsReport report = insReportMapper.selectOne(Wrappers.<InsReport>lambdaQuery()
                 .eq(InsReport::getInsOrderId, orderId));
         String tempUrlPdf = this.wordToPdfTemp(report.getUrl().replace("/word", wordUrl));
         report.setTempUrlPdf("/word/" + tempUrlPdf);
         insReportMapper.updateById(report);
 
-        // 鏌ヨ璁㈠崟
+        // 10.鍘熷璁板綍妯℃澘澶嶅埗(娣诲姞澶囦唤, 閬垮厤淇敼鍘熷妯℃澘褰卞搷鍒板凡缁忓畬鎴愮殑鍗曞瓙)
+        this.templateCopy(orderId, InsSampleIds);
+
+        // 11.鎴愬搧鎶芥牱娣诲姞鍚堟牸鐘舵��
+        // 鍒ゆ柇鏄惁鏈夋娊鏍蜂俊鎭�
+        if (order.getQuarterItemId() != null) {
+            // 鍒ゆ柇鏄惁鏈変笉鍚堟牸
+            this.addProductSpotCheck(insSamples, order);
+        }
+
+
+        // 12.娣诲姞璁㈠崟璐圭敤缁熻淇℃伅
+        List<InsProduct> productList = insProductMapper.selectProductByOrderId(orderId);
+        // 鍒犻櫎鍘熸湰璐圭敤淇℃伅
+        insOrderRatesService.remove(Wrappers.<InsOrderRates>lambdaQuery()
+                .eq(InsOrderRates::getInsOrderId, orderId));
+        List<InsOrderRates> orderRatesList = productList.stream().map(insProduct -> {
+            InsOrderRates insOrderRates = new InsOrderRates();
+            insOrderRates.setInsOrderId(orderId);
+            insOrderRates.setInsSampleId(insProduct.getInsSampleId());
+            insOrderRates.setInsProductId(insProduct.getId());
+            insOrderRates.setSampleCode(insProduct.getSampleCode());
+            insOrderRates.setEntrustCode(order.getEntrustCode());
+            insOrderRates.setInspectionItemClass(insProduct.getInspectionItemClass());
+            insOrderRates.setInspectionItem(insProduct.getInspectionItem());
+            insOrderRates.setInspectionItemSubclass(insProduct.getInspectionItemSubclass());
+            insOrderRates.setCableTag(insProduct.getCableTag());
+            insOrderRates.setRates(insProduct.getRates());
+            insOrderRates.setManHourGroup(insProduct.getManHourGroup());
+            return insOrderRates;
+        }).collect(Collectors.toList());
+        insOrderRatesService.saveBatch(orderRatesList);
+
+
+        // 13.鍙戦�佷紒涓氬井淇¢�氱煡
+        // 鏌ヨ鍘熸潗鏂�
+        IfsInventoryQuantity ifsInventoryQuantity = ifsInventoryQuantityMapper.selectById(order.getIfsInventoryId());
+        // 鏌ヨ鏍峰搧淇℃伅
         InsSample insSample = insSampleMapper.selectOne(Wrappers.<InsSample>lambdaQuery()
                 .eq(InsSample::getInsOrderId, orderId)
                 .last("limit 1"));
-        // 鏌ヨ鍘熸潗鏂�
-        IfsInventoryQuantity ifsInventoryQuantity = ifsInventoryQuantityMapper.selectById(order.getIfsInventoryId());
+        threadPoolTaskExecutor.execute(() -> {
+            String message = "";
+            message += "鑰愪笣绯荤粺妫�楠屼换鍔″鏍搁�氱煡";
+            message += "\n鎻愪氦浜�: " + userName;
+            message += "\n濮旀墭缂栧彿: " + order.getEntrustCode();
+            message += "\n鏍峰搧鍚嶇О: " + insSample.getModel();
+            message += "\n瑙勬牸鍨嬪彿: " + order.getPartDetail();
+            if (ifsInventoryQuantity != null) {
+                message += "\n鎵规鍙�: " + ifsInventoryQuantity.getUpdateBatchNo();
+            }
+            //鍙戦�佷紒涓氬井淇℃秷鎭�氱煡  鎻愪氦澶嶆牳
+            try {
+                WxCpUtils.inform(sendUserAccount, message, null);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        });
+        // 14.ifs绉诲簱(鍘熸潗鏂欓渶瑕佽繘琛岀Щ搴撴搷浣�) --> 鏈�鍚庢墽琛�,鍥犱负澶辫触鏃犳硶鍥炴粴
+        if (ifsInventoryQuantity != null) {
+            // 鐧昏妫�楠岀粨鏋�
+            // 鍒ゆ柇鏄惁鏈変笉鍚堟牸, 鏈変笉鍚堟牸涓嶈兘绉诲簱
+            // todo: ifs绉诲簱
+            insReportService.isRawMaterial(order,registerInsResults,false);
 
+            // 15 鍒ゆ柇褰撳墠鏍峰搧鏄惁涓哄師鏉愭枡, 鍘熸潗鏂欓渶瑕佽繘琛屾暟鎹垎鏋�, 鍒ゆ柇涔嬪墠10鏉℃暟鎹悓涓�涓緵搴斿晢, 鍚屼竴涓楠岄」鐨勫亸宸槸鍚﹁秴杩�10%
+            // 鏌ヨifs淇℃伅鑾峰彇鑾峰彇鍓�10涓緵搴斿晢涓�鏍风殑, 妫�楠岄」涓�鏍蜂俊鎭�
+            threadPoolTaskExecutor.execute(() -> {
+                // 娣诲姞鍒嗘瀽鏁版嵁
+                addAnalysis(productList, ifsInventoryQuantity, order, sendUserAccount);
+            });
+        } else {
+            // 淇敼鎴愬搧鐘舵��
+            // 鍒ゆ柇鏄惁鏈変笉鍚堟牸
+            Long unqualifiedCount = insReportService.getUnqualifiedCount(order);
+            if (unqualifiedCount.equals(0L)) {
+                insOrderMapper.update(null, Wrappers.<InsOrder>lambdaUpdate()
+                        .eq(InsOrder::getId, order.getId())
+                        .set(InsOrder::getInsResult, 1));
+            } else {
+                insOrderMapper.update(null, Wrappers.<InsOrder>lambdaUpdate()
+                        .eq(InsOrder::getId, order.getId())
+                        .set(InsOrder::getInsResult, 0));
+            }
+        }
+        return 1;
+    }
+
+    /**
+     * *****娣诲姞鍒嗘瀽鏁版嵁******
+     * @param productList
+     * @param ifsInventoryQuantity
+     * @param order
+     */
+    private void addAnalysis(List<InsProduct> productList, IfsInventoryQuantity ifsInventoryQuantity, InsOrder order, String sendUserAccount) {
+        for (InsProduct insProduct : productList) {
+            // 鍒ゆ柇鏄惁鏄暟鍊肩被鍨�
+            if (insProduct.getInspectionValueType().equals("1") && insProduct.getInsResult().equals(1)) {
+                List<InsProductDeviationWarningDetail> insProductAnalysisDtoList = insProductMapper.selectAnalysis(insProduct, ifsInventoryQuantity.getSupplierName());
+
+                if (CollectionUtils.isEmpty(insProductAnalysisDtoList)) {
+                    continue;
+                }
+
+                // 鍒ゆ柇褰撳墠妫�娴嬮」鏄惁鍋忓樊瓒呰繃10%
+                List<String> laseValueList = insProductAnalysisDtoList.stream().map(InsProductDeviationWarningDetail::getTestValue)
+                        .collect(Collectors.toList());
+
+                double deviation = isDeviationOverTenPercent(laseValueList, insProduct.getLastValue());
+
+                double asked = isDeviationOverTenPercentByAsked(insProduct.getAsk(), insProduct.getLastValue());
+                // 鍒ゆ柇鍋忓樊鏄惁澶т簬10
+                if (deviation > 10 || asked > 10) {
+                    // 鍒ゆ柇涔嬪墠鏄惁娣诲姞杩�, 娣诲姞杩囦笉闇�瑕佹坊鍔�
+                    long count = insProductDeviationWarningService.count(Wrappers.<InsProductDeviationWarning>lambdaQuery()
+                            .eq(InsProductDeviationWarning::getInsProductId, insProduct.getId()));
+                    if (count == 0L) {
+                        // 鍙戦�侀�氱煡, 骞朵笖娣诲姞鏁版嵁
+                        // 娣诲姞涓昏〃淇℃伅
+                        InsProductDeviationWarning deviationWarning = new InsProductDeviationWarning();
+                        deviationWarning.setInsOrderId(order.getId());
+                        deviationWarning.setInsSampleId(insProduct.getInsSampleId());
+                        deviationWarning.setInsProductId(insProduct.getId());
+                        deviationWarning.setEntrustCode(order.getEntrustCode());
+                        deviationWarning.setSampleCode(insProduct.getSampleCode());
+                        deviationWarning.setSupplierName(ifsInventoryQuantity.getSupplierName());
+                        deviationWarning.setDeviationValue(Double.toString(deviation));
+                        deviationWarning.setDetectionTime(insProduct.getUpdateTime());
+                        insProductDeviationWarningService.save(deviationWarning);
+
+                        // 娣诲姞璇︽儏鏁版嵁
+                        InsProductDeviationWarningDetail deviationWarningDetail = new InsProductDeviationWarningDetail();
+                        deviationWarningDetail.setInsOrderId(order.getId());
+                        deviationWarningDetail.setInsSampleId(insProduct.getInsSampleId());
+                        deviationWarningDetail.setInsProductId(insProduct.getId());
+                        deviationWarningDetail.setEntrustCode(order.getEntrustCode());
+                        deviationWarningDetail.setSampleCode(insProduct.getSampleCode());
+                        deviationWarningDetail.setSupplierName(ifsInventoryQuantity.getSupplierName());
+                        deviationWarningDetail.setTestValue(insProduct.getLastValue());
+                        deviationWarningDetail.setDetectionTime(insProduct.getCreateTime());
+                        deviationWarningDetail.setIsIssue(deviation > 10 ? 1 : 0);
+                        deviationWarningDetail.setIsIssueAsked(asked > 10 ? 1 : 0);
+
+                        insProductAnalysisDtoList.add(deviationWarningDetail);
+
+                        // 娣诲姞id
+                        for (InsProductDeviationWarningDetail warningDetail : insProductAnalysisDtoList) {
+                            warningDetail.setDeviationWarningId(deviationWarning.getDeviationWarningId());
+                        }
+
+                        insProductDeviationWarningDetailService.saveBatch(insProductAnalysisDtoList);
+
+                        //鍙戦�佷紒涓氬井淇℃秷鎭�氱煡  妫�楠岄」棰勮棰勮閫氱煡
+                        try {
+                            String message = "";
+                            message += "妫�楠岄」棰勮棰勮閫氱煡";
+                            message += "\n濮旀墭缂栧彿: " + order.getEntrustCode();
+                            message += "\n鏍峰搧鍚嶇О: " + order.getSample();
+                            message += "\n瑙勬牸鍨嬪彿: " + order.getPartDetail();
+                            message += "\n鎵规鍙�: " + ifsInventoryQuantity.getUpdateBatchNo();
+                            message += "\n渚涘簲鍟嗗悕绉�: " + ifsInventoryQuantity.getSupplierName();
+                            message += "\n妫�楠岄」: " + insProduct.getInspectionItem() + insProduct.getInspectionItemSubclass();
+                            message += "\n鍋忓樊瓒呰繃浜� 10%";
+                            // 鍙戦�佺粰鎻愪氦浜�
+//                            WxCpUtils.inform(sendUserAccount, message, null);
+//
+//                            // todo: 鍙戦�佺粰妫�娴嬩腑蹇冧富浠�(鍥哄畾姝�)
+//                            WxCpUtils.inform("ZT-004704", message, null);
+                        } catch (Exception e) {
+                            e.printStackTrace();
+                            log.error("鍋忓樊棰勮浼佷笟寰俊閫氱煡鎶ラ敊");
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * *****璁$畻鍋忓樊****
+     * @param data
+     * @param targetStr
+     * @return
+     */
+    public static double isDeviationOverTenPercent(List<String> data, String targetStr) {
+        if (data.isEmpty()) {
+            return 0;
+        }
+        List<Double> doubleData = data.stream()
+                .map(Double::parseDouble)
+                .collect(Collectors.toList());
+        double sum = doubleData.stream().mapToDouble(Double::doubleValue).sum();
+        double average = sum / doubleData.size();
+
+        double target = Double.parseDouble(targetStr);
+        double deviationPercent = Math.abs(target - average) / average * 100;
+
+        // 淇濈暀涓や綅灏忔暟
+        DecimalFormat df = new DecimalFormat("#.00");
+        String formatted = df.format(deviationPercent);
+        return Double.parseDouble(formatted);
+    }
+
+    /**
+     * *****璁$畻鍋忓樊****
+     * @param targetStr
+     * @return
+     */
+    public static double isDeviationOverTenPercentByAsked(String asked, String targetStr) {
+        if(!isNumeric(asked)) return 0;
+        double average = Double.parseDouble(asked);
+
+        double target = Double.parseDouble(targetStr);
+        double deviationPercent = Math.abs(target - average) / average * 100;
+
+        // 淇濈暀涓や綅灏忔暟
+        DecimalFormat df = new DecimalFormat("#.00");
+        String formatted = df.format(deviationPercent);
+        return Double.parseDouble(formatted);
+    }
+
+    /**
+     * ******鍘熷璁板綍妯℃澘澶嶅埗*****
+     * @param orderId
+     * @param ids
+     */
+    private void templateCopy(Integer orderId, List<Integer> ids) {
         // 鍒犻櫎鍘熸湰妯℃澘
         insOrderStandardTemplateService.remove(Wrappers.<InsOrderStandardTemplate>lambdaQuery()
                 .eq(InsOrderStandardTemplate::getInsOrderId, orderId));
@@ -890,137 +1124,6 @@
                     insOrderStandardTemplateService.save(insOrderStandardTemplate);
                 }
             }
-        }
-
-        // 鎴愬搧鎶芥牱娣诲姞鍚堟牸鐘舵��
-        // 鍒ゆ柇鏄惁鏈夋娊鏍蜂俊鎭�
-        if (order.getQuarterItemId() != null) {
-            // 鍒ゆ柇鏄惁鏈変笉鍚堟牸
-            Long unqualifiedCount = 0L;
-            if (CollectionUtils.isNotEmpty(insSamples)) {
-                unqualifiedCount = insProductMapper.selectCount(Wrappers.<InsProduct>lambdaQuery()
-                        .in(InsProduct::getInsSampleId, insSamples.stream().map(InsSample::getId).collect(Collectors.toList()))
-                        .eq(InsProduct::getInsResult, 0));
-
-                // 鍒ゆ柇濡傛灉鏈変笉鍚堟牸鐨勬楠岄」, 鍒ゆ柇鏈夋病鏈夋楠岄」澶嶆祴, 澶嶆牳鍚堟牸涔熺畻鍚堟牸閫氳繃
-                if (!unqualifiedCount.equals(0L)) {
-                    List<InsProduct> productList = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
-                            .in(InsProduct::getInsSampleId, insSamples.stream().map(InsSample::getId).collect(Collectors.toList()))
-                            .eq(InsProduct::getInsResult, 0));
-
-                    boolean flag = true;
-                    for (InsProduct insProduct : productList) {
-                        Long unqualifiedProductCount = insUnqualifiedRetestProductMapper.selectCount(Wrappers.<InsUnqualifiedRetestProduct>lambdaQuery()
-                                .eq(InsUnqualifiedRetestProduct::getInsProductId, insProduct.getId())
-                                .ne(InsUnqualifiedRetestProduct::getInsResult, 0));
-                        if (unqualifiedProductCount != 2) {
-                            flag = false;
-                        }
-                    }
-                    if (flag) {
-                        unqualifiedCount = 0L;
-                    }
-                }
-            }
-            spotCheckQuarterItemMapper.update(null, Wrappers.<SpotCheckQuarterItem>lambdaUpdate()
-                    .eq(SpotCheckQuarterItem::getQuarterItemId, order.getQuarterItemId())
-                    .set(SpotCheckQuarterItem::getResult, unqualifiedCount.equals(0L) ? "鍚堟牸" : "涓嶅悎鏍�"));
-
-        }
-
-        // 鍙戦�佷紒涓氬井淇¢�氱煡
-        threadPoolTaskExecutor.execute(() -> {
-            String message = "";
-            message += "妫�楠屼换鍔″鏍搁�氱煡";
-            message += "\n鎻愪氦浜�: " + userName;
-            message += "\n濮旀墭缂栧彿: " + order.getEntrustCode();
-            message += "\n鏍峰搧鍚嶇О: " + insSample.getModel();
-            message += "\n瑙勬牸鍨嬪彿: " + order.getPartDetail();
-            if (ifsInventoryQuantity != null) {
-                message += "\n鎵规鍙�: " + ifsInventoryQuantity.getUpdateBatchNo();
-            }
-            //鍙戦�佷紒涓氬井淇℃秷鎭�氱煡  鎻愪氦澶嶆牳
-            try {
-                WxCpUtils.inform(sendUserAccount, message, null);
-            } catch (Exception e) {
-                throw new RuntimeException(e);
-            }
-        });
-
-        // ifs绉诲簱
-        if (ifsInventoryQuantity != null) {
-            // 鐧昏妫�楠岀粨鏋�
-            // 鍒ゆ柇鏄惁鏈変笉鍚堟牸, 鏈変笉鍚堟牸涓嶈兘绉诲簱
-            // todo: ifs绉诲簱
-            insReportService.isRawMaterial(order);
-        } else {
-            // 淇敼鎴愬搧鐘舵��
-            // 鍒ゆ柇鏄惁鏈変笉鍚堟牸
-            Long unqualifiedCount = insReportService.getUnqualifiedCount(order);
-            if (unqualifiedCount.equals(0L)) {
-                insOrderMapper.update(null, Wrappers.<InsOrder>lambdaUpdate()
-                        .eq(InsOrder::getId, order.getId())
-                        .set(InsOrder::getInsResult, 1));
-            } else {
-                insOrderMapper.update(null, Wrappers.<InsOrder>lambdaUpdate()
-                        .eq(InsOrder::getId, order.getId())
-                        .set(InsOrder::getInsResult, 0));
-            }
-        }
-
-        return 1;
-    }
-
-    public int pxToCm(int px) {
-        return px / 9;
-    }
-
-    // 鑾峰彇涓や釜localDateTime鐨勬瘡涓�澶�
-    public static List<LocalDateTime> getLocalDateTimesBetween(LocalDateTime start, LocalDateTime end) {
-        List<LocalDateTime> localDateTimes = new ArrayList<>();
-        LocalDate currentDate = start.toLocalDate();
-        LocalDateTime currentLocalDateTime = start;
-        while (!currentDate.isAfter(end.toLocalDate())) {
-            localDateTimes.add(currentLocalDateTime);
-            currentLocalDateTime = currentLocalDateTime.plusDays(1);
-            currentDate = currentDate.plusDays(1);
-        }
-        return localDateTimes;
-    }
-
-    public static String getWeek(String dayStr) {
-        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-        try {
-            Date date = sdf.parse(dayStr);
-            Calendar calendar = Calendar.getInstance();
-            calendar.setTime(date);
-            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
-            int day = calendar.get(Calendar.DAY_OF_MONTH);
-            return getWeekDay(dayOfWeek);
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-        return null;
-    }
-
-    public static String getWeekDay(int dayOfWeek) {
-        switch (dayOfWeek) {
-            case Calendar.MONDAY:
-                return "鍛ㄤ竴";
-            case Calendar.TUESDAY:
-                return "鍛ㄤ簩";
-            case Calendar.WEDNESDAY:
-                return "鍛ㄤ笁";
-            case Calendar.THURSDAY:
-                return "鍛ㄥ洓";
-            case Calendar.FRIDAY:
-                return "鍛ㄤ簲";
-            case Calendar.SATURDAY:
-                return "鍛ㄥ叚";
-            case Calendar.SUNDAY:
-                return "鍛ㄦ棩";
-            default:
-                return "鏈煡";
         }
     }
 
@@ -1092,7 +1195,7 @@
                 IfsInventoryQuantity ifsInventoryQuantity = ifsInventoryQuantityMapper.selectById(order.getIfsInventoryId());
 
                 String message = "";
-                message += "鎶ュ憡缂栧埗瀹℃壒閫氱煡";
+                message += "鑰愪笣绯荤粺鎶ュ憡缂栧埗瀹℃壒閫氱煡";
                 message += "\n妫�楠屼汉: " + userName;
                 message += "\n澶嶆牳浜�: " + chenkUserName;
                 message += "\n濮旀墭缂栧彿: " + order.getEntrustCode();
@@ -1134,7 +1237,7 @@
                 IfsInventoryQuantity ifsInventoryQuantity = ifsInventoryQuantityMapper.selectById(order.getIfsInventoryId());
 
                 String message = "";
-                message += "妫�楠屼换鍔″鏍搁��鍥為�氱煡";
+                message += "鑰愪笣绯荤粺妫�楠屼换鍔″鏍搁��鍥為�氱煡";
                 message += "\n澶嶆牳浜�: " + userName;
                 message += "\n濮旀墭缂栧彿: " + order.getEntrustCode();
                 message += "\n鏍峰搧鍚嶇О: " + insSample.getModel();
@@ -1159,7 +1262,6 @@
      * @param orderId
      */
     private void generateReport(Integer orderId) {
-        List<InsUnPass> insUnPasses = new ArrayList<>();
         /*鏍峰搧涓嬬殑椤圭洰鍙鏈変竴涓」鐩笉鍚堟牸鍒欐楠岀粨鏋滀负0,鍚﹀垯涓�1*/
         //杩欓噷鐨刬nsSamples鏄鍗曚笅鐨勬墍鏈夋牱鍝佸寘鎷�("/")
         List<InsSample> insSamples = insSampleMapper.selectList(Wrappers.<InsSample>lambdaQuery().eq(InsSample::getInsOrderId, orderId));
@@ -1175,25 +1277,7 @@
                 insSample.setInsResult(1);
             }
             insSampleMapper.updateById(insSample);
-            /*澶嶆牳閫氳繃鍚庯紝灏嗕笉鍚堟牸鐨勯」鐩俊鎭坊鍔犲埌ins_un_pass琛ㄤ腑*/
-            for (InsProduct insProduct : insProducts) {
-                if (insProduct.getInsResult() == 0) {
-                    InsUnPass insUnPass = new InsUnPass();
-                    insUnPass.setId(null);
-                    insUnPass.setModel(insSample.getModel());
-                    insUnPass.setSample(insSample.getSample());
-                    insUnPass.setInspectionItem(insProduct.getInspectionItem());
-                    insUnPass.setInspectionItemSubclass(insProduct.getInspectionItemSubclass());
-                    insUnPass.setLastValue(insProduct.getLastValue());
-                    insUnPass.setEntrustCode(insOrderMapper.selectById(orderId).getEntrustCode());
-                    List<Integer> userIds = insProductUserMapper.selectList(Wrappers.<InsProductUser>lambdaQuery().eq(InsProductUser::getInsProductId, insProduct.getId())).stream().map(InsProductUser::getCreateUser).distinct().collect(Collectors.toList());
-                    String name = userMapper.selectBatchIds(userIds).stream().map(User::getName).collect(Collectors.joining(","));
-                    insUnPass.setName(name);
-                    insUnPasses.add(insUnPass);
-                }
-            }
         }
-        insUnPassService.saveBatch(insUnPasses);
         InsOrder insOrder = insOrderMapper.selectById(orderId);
         // 鎶芥鍙樻垚濮旀墭妫�楠�
         if (insOrder.getOrderType().equals(InsOrderTypeConstants.SPOT_CHECK)) {
@@ -1246,36 +1330,13 @@
     }
 
     /**
-     * 鑾峰彇涓嶅悎鏍兼暟鎹�
-     * @return
-     */
-    @Override
-    public List<InsProduct> getInsProductUnqualified(InsOrderPlanProductDto dto) {
-        List<InsProduct> insProducts = new ArrayList<>();
-        switch (dto.getType()) {
-            case 0:
-                //鏍峰搧
-                insProducts = insSampleMapper.getInsProduct1(dto.getId(), dto.getLaboratory(), dto.getCableTag(), dto.getRepetitionTag(), "1");
-                break;
-            case 4:
-                //鐢电紗閰嶇疆
-                insProducts = insSampleMapper.getInsProduct1(dto.getId(), dto.getLaboratory(), dto.getCableTag(), dto.getRepetitionTag(), "1");
-                break;
-            case 5:
-                //鍘熸潗鏂欎笅鍗�
-                insProducts = insSampleMapper.getInsProduct6(dto.getId(), dto.getLaboratory(), dto.getRawMaterialTag(), "1");
-                break;
-        }
-        return insProducts;
-    }
-
-    /**
      * 鏂板涓嶅悎鏍煎娴嬪唴瀹�
-     * @param ids
      * @return
      */
     @Override
-    public boolean addDisqualificationRetest(List<Integer> ids) {
+    public boolean addDisqualificationRetest(List<InsProduct> insProductsList) {
+        List<Integer> ids = insProductsList.stream().map(InsProduct::getId).collect(Collectors.toList());
+
         // 鍒ゆ柇涔嬪墠鏄惁娣诲姞杩�
         Long count = insUnqualifiedRetestProductMapper.selectCount(Wrappers.<InsUnqualifiedRetestProduct>lambdaQuery()
                 .in(InsUnqualifiedRetestProduct::getInsProductId, ids));
@@ -1285,6 +1346,20 @@
 
         // 鏌ヨ涓嶅悎鏍煎唴瀹�
         List<InsUnqualifiedRetestProduct> list = insUnqualifiedRetestProductMapper.selectRetestProduct(ids);
+        // 寰幆鍒ゆ柇鏄惁鏄粦瀹氬��, 缁戝畾鍊间慨鏀规楠岃姹�
+        for (InsUnqualifiedRetestProduct insUnqualifiedRetestProduct : list) {
+            for (InsProduct insProduct : insProductsList) {
+                if (insProduct.getIsBinding().equals(1)) {
+                    insUnqualifiedRetestProduct.setIsBinding(1);
+                    insUnqualifiedRetestProduct.setAsk(null);
+                    insUnqualifiedRetestProduct.setTell(null);
+                    insUnqualifiedRetestProduct.setPrice(null);
+                    insUnqualifiedRetestProduct.setManHour(null);
+                    insUnqualifiedRetestProduct.setSection(null);
+                }
+            }
+        }
+
         // 鏂板涓嶅悎鏍煎唴瀹�
         insUnqualifiedRetestProductService.saveBatch(list);
         list.forEach(insUnqualifiedRetestProduct -> {
@@ -1296,38 +1371,29 @@
     }
 
     @Override
-    public List<InsProduct> getInsProductUnqualifiedRetest(Integer id, Integer type, String laboratory, String cableTag, String rawMaterialTag, String retestTag) {
+    public List<InsProduct> getInsProductUnqualifiedRetest(InsOrderPlanProductDto dto) {
 
         List<InsProduct> insProducts = new ArrayList<>();
-        switch (type) {
+        switch (dto.getType()) {
             case 0:
-                //鏍峰搧
-                insProducts = insUnqualifiedRetestProductMapper.getInsProductUnqualifiedRetest1(id, laboratory, retestTag);
-                break;
             case 4:
-                //鐢电紗閰嶇疆
-                insProducts = insUnqualifiedRetestProductMapper.getInsProductUnqualifiedRetest5(id, laboratory, cableTag, retestTag);
+                //濮旀墭
+                insProducts = insUnqualifiedRetestProductMapper.getInsProductUnqualifiedRetest1(dto.getId(), dto.getLaboratory(), dto.getCableTag(), dto.getRepetitionTag(), dto.getRetestTag());
                 break;
             case 5:
                 //鍘熸潗鏂欎笅鍗�
-                insProducts = insUnqualifiedRetestProductMapper.getInsProductUnqualifiedRetest6(id, laboratory, rawMaterialTag, retestTag);
+                insProducts = insUnqualifiedRetestProductMapper.getInsProductUnqualifiedRetest6(dto.getId(), dto.getLaboratory(), dto.getRawMaterialTag(), dto.getRetestTag());
                 break;
         }
         if (BeanUtil.isEmpty(insProducts)) {
             return null;
         }
-        InsOrder order = insOrderMapper.selectFirstSubmit(id);
+        InsOrder order = insOrderMapper.selectFirstSubmit(dto.getId());
         getTemplateThing(order, Collections.unmodifiableList(insProducts));
         return insProducts;
     }
 
 
-    /**
-     * 淇濆瓨涓嶅悎鏍煎娴嬫楠屽唴瀹�
-     * @param currentTable
-     * @param orderId
-     * @param sonLaboratory
-     */
     @Override
     @Transactional(rollbackFor = Exception.class)
     public void saveUnqualifiedContext(Map<String, Object> insContext, Integer currentTable, Integer currentSampleId, Integer orderId, String sonLaboratory) {
@@ -1345,13 +1411,12 @@
                     BeanUtil.copyProperties(oldResults.get(0), newResult);
                 }
                 newResult.setRetestProductId(Integer.parseInt(k));
-
+                /*鏍¢獙涓�涓媟esult琛�*/
                 if (oldResults.size() > 1) {
                     for (int i = 1; i < oldResults.size(); i++) {
                         insUnqualifiedRetestResultMapper.deleteById(oldResults.get(i));
                     }
                 }
-
                 //妫�楠屽��
                 if (jo.get("insValue") != null) {
                     JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(jo.get("insValue")));
@@ -1382,6 +1447,8 @@
                     for (Object o : jsonArray2) {
                         JSONObject comValue = JSON.parseObject(JSON.toJSONString(o));
                         Map<String, Object> map = new HashMap<>();
+                        map.put("r", JSON.toJSONString(comValue.get("r")));
+                        map.put("c", JSON.toJSONString(comValue.get("c")));
                         map.put("v", JSON.parseObject(JSON.toJSONString(comValue.get("v"))).get("v"));
                         cv.add(map);
                     }
@@ -1444,41 +1511,18 @@
                 insProductUserMapper.insert(new InsProductUser(null, userId, LocalDateTime.now(), insProduct.getId()));
 
 
-                InsSample insSample = insSampleMapper.selectById(insProductMapper.selectById(insProduct.getId()).getInsSampleId());
-                insSample.setInsState(1);
-                Long l = insProductMapper.selectCount(Wrappers.<InsProduct>lambdaQuery()
-                        .eq(InsProduct::getInsSampleId, insSample.getId()));
-                Long l1 = insProductMapper.selectCount(Wrappers.<InsProduct>lambdaQuery()
-                        .eq(InsProduct::getInsSampleId, insSample.getId())
-                        .and(wrapper -> wrapper
-                                .isNotNull(InsProduct::getInsResult)
-                                .or()
-                                .ne(InsProduct::getInsResult, 2)
-                        ));
-                if (Objects.equals(l, l1)) {
-                    insSample.setInsState(2);
-                }
-                insSampleMapper.updateById(insSample);
                 /*鏍¢獙涓�涓媟esult琛�*/
                 List<InsUnqualifiedRetestResult> insProductResults = insUnqualifiedRetestResultMapper.selectList(Wrappers.<InsUnqualifiedRetestResult>lambdaQuery()
-                        .eq(InsUnqualifiedRetestResult::getRetestProductId, insProduct.getId()));
+                        .eq(InsUnqualifiedRetestResult::getRetestProductId, product.getId()));
                 if (insProductResults.size() > 1) {
                     for (int i = 1; i < insProductResults.size(); i++) {
                         insUnqualifiedRetestResultMapper.deleteById(insProductResults.get(i));
                     }
                 }
+
             }
         });
-        String sampleIdStr = insContext.keySet().stream().findFirst().orElse(null);
-        if (sampleIdStr != null) {
-            int count = insProductMapper.selectInsProductCountByOrderId(orderId);
-            if (count == 0) {
-                insOrderStateMapper.update(new InsOrderState(), Wrappers.<InsOrderState>lambdaUpdate()
-                        .eq(InsOrderState::getInsOrderId, orderId)
-                        .eq(InsOrderState::getLaboratory, sonLaboratory)
-                        .set(InsOrderState::getInsState, 2));
-            }
-        }
+
     }
 
     /**
@@ -1588,6 +1632,95 @@
     /*****************************************************  灏忔姤鍛�    ***************************************************************************/
 
     /**
+     * 璁剧疆琛ㄦ牸鏍峰紡
+     * @param max 鏍囪瘑鏈�澶т釜鏁�
+     * @return
+     */
+    private TableStyle setTableStyle(int max){
+        //璁剧疆鏍峰紡
+        TableStyle tableStyle = new TableStyle();
+        if(max<=5){
+            for (int i = 1; i <= max; i++) {
+                // 鏍规嵁妫�楠岀粨鏋滀釜鏁颁慨鏀归暱搴�
+                switch (i) {
+                    case 1:
+                        tableStyle.setColWidths(new int[]{650, 2900, 850, 2300, 2100, 1200});
+                        break;
+                    case 2:
+                        tableStyle.setColWidths(new int[]{650, 2700, 850, 2200, 1200, 1200, 1200});
+                        break;
+                    case 3:
+                        tableStyle.setColWidths(new int[]{650, 2700, 850, 1600, 1000, 1000, 1000, 1200});
+                        break;
+                    case 4:
+                        tableStyle.setColWidths(new int[]{650, 2400, 850, 1500, 850, 850, 850, 850, 1200});
+                        break;
+                    case 5:
+                        tableStyle.setColWidths(new int[]{650, 2200, 850, 1350, 770, 770, 770, 770, 770, 1100});
+                        break;
+                }
+            }
+        }
+
+        tableStyle.setWidth("10000");
+        tableStyle.setAlign(TableRowAlign.CENTER);
+        BorderStyle borderStyle = new BorderStyle();
+        borderStyle.setColor("000000");
+        borderStyle.setType(XWPFTable.XWPFBorderType.SINGLE);
+        borderStyle.setSize(4);
+        tableStyle.setLeftBorder(borderStyle);
+        tableStyle.setRightBorder(borderStyle);
+        tableStyle.setInsideHBorder(borderStyle); // 璁剧疆姘村钩鍐呰竟妗�
+        tableStyle.setInsideVBorder(borderStyle);
+        return tableStyle;
+    }
+
+    /**
+     * 澶勭悊鏈夌數缂嗛鑹叉爣璇嗙殑妫�娴嬮」
+     * @param cableTags 鐢电紗棰滆壊鏍囪瘑
+     * @param collect   妫�娴嬮」鍒楄〃
+     * @param startIndex 璧峰涓嬫爣
+     * @param endIndex   缁撴潫涓嬫爣
+     * @return
+     */
+    private List<SampleProductExportDto> transformSampleProduct(List<String> cableTags,Map<String, List<SampleProductExportDto>> collect,int startIndex,int endIndex){
+        List<SampleProductExportDto> sampleProductExportDtos = new ArrayList<>();
+        for (String s : collect.keySet()) {
+            List<String> lastValueList = new ArrayList<>();
+            SampleProductExportDto dto = new SampleProductExportDto();
+            BeanUtil.copyProperties(collect.get(s).get(0),dto);
+            Set<String> tellSet = new HashSet<>();
+            for (int i = startIndex; i < endIndex; i++) {
+                String cableTag = cableTags.get(i);
+                for (SampleProductExportDto sDto : collect.get(s)) {
+                    tellSet.add(sDto.getTell());
+                    if(sDto.getCableTag().equals(cableTag)){
+                        lastValueList.add(sDto.getLastValue());
+                    }
+                }
+            }
+            //鍒囧壊鐢电紗閰嶇疆椤�
+            dto.setTell(String.join("\n",tellSet));
+            dto.setLastValueList(lastValueList);
+            sampleProductExportDtos.add(dto);
+        }
+        return sampleProductExportDtos;
+    }
+
+    /**
+     * 妫�娴嬮」鎺掑簭
+     * @param sourceMap
+     * @param targetMap
+     */
+    private void sortSampleProduct(Map<String, List<SampleProductExportDto>> sourceMap,Map<String, List<SampleProductExportDto>> targetMap){
+        List<Map.Entry<String, List<SampleProductExportDto>>> entries = new ArrayList<>(sourceMap.entrySet());
+        entries.sort(Comparator.comparingInt(o -> (o.getValue().get(0).getSort() == null ? 0 : o.getValue().get(0).getSort())));
+        for (Map.Entry<String, List<SampleProductExportDto>> entry : entries) {
+            targetMap.put(entry.getKey(), entry.getValue());
+        }
+    }
+
+    /**
      * 灏忔姤鍛婄敓鎴�
      * @param orderId
      * @param insOrder
@@ -1605,11 +1738,17 @@
         enterFactoryReport.setSample(insOrder.getSample());
         // 鑾峰彇ifs鏁版嵁
         IfsInventoryQuantity ifsInventoryQuantity = ifsInventoryQuantityMapper.selectById(insOrder.getIfsInventoryId());
+        //鏌ヨ闆朵欢灞炴��
+        IfsPartPropsRecord ifsPartPropsRecord = ifsPartPropsRecordMapper.selectOne(Wrappers.<IfsPartPropsRecord>lambdaQuery()
+                .eq(IfsPartPropsRecord::getIfsInventoryId, ifsInventoryQuantity.getId()));
+        if(Objects.nonNull(ifsPartPropsRecord)){
+            enterFactoryReport.setOuterColor(ifsPartPropsRecord.getOuterColor());
+        }
         enterFactoryReport.setQtyArrived(ifsInventoryQuantity.getQtyArrived() == null ? "" :
                 ifsInventoryQuantity.getQtyArrived().stripTrailingZeros().toPlainString() + ifsInventoryQuantity.getBuyUnitMeas());
         enterFactoryReport.setQuantity(insOrder.getTestQuantity());
         enterFactoryReport.setPartDesc(insOrder.getPartDetail());
-        enterFactoryReport.setSupplierName("**********");
+        enterFactoryReport.setSupplierName(ifsInventoryQuantity.getSupplierName());
         enterFactoryReport.setLotBatchNo(ifsInventoryQuantity.getUpdateBatchNo());
 
         // 妫�娴嬩緷鎹�
@@ -1627,6 +1766,7 @@
         List<RowRenderData> rows = new ArrayList<>();
         List<TextRenderData> text = new ArrayList<>();
         RowRenderData rowRenderData = null;
+        List<Map<String,Object>> cableTagEnclosureTables = new ArrayList<>();
 
         // 鏌ヨ妫�楠屽唴瀹�
         List<SampleProductExportDto> sampleProductDto2s = insOrderMapper.selectSampleBySampleId(insSamples.stream()
@@ -1637,21 +1777,173 @@
 
         List<SampleProductExportDto> sampleList = new ArrayList<>();
         Integer max = insSamples.stream().mapToInt(InsSample::getQuantity).sum();
+        TableRenderData tableRenderData = new TableRenderData();
+        String templateName;
+        if(StringUtils.equals(OrderType.WG.getValue(),ifsInventoryQuantity.getOrderType())){
+            //杩囨护涓嶅垽瀹氱殑妫�娴嬮」
+            List<SampleProductExportDto> filterItems = sampleProductDto2s.stream().filter(f -> f.getInsResult() != 3).collect(Collectors.toList());
+            int maxCableTag = 5;//鍗曚釜琛ㄦ牸锛岀數缂嗛鑹叉爣璇嗘渶澶т釜鏁�
+            templateName = "/static/small-wg-report-template.docx";
+            //鏌ヨ妫�楠屽崟娑堟伅
+            InsSampleUserVO insSampleUser = insSampleUserMapper.selectUserNameByOrderId(orderId);
+            if(Objects.nonNull(insSampleUser)){
+                enterFactoryReport.setPartDesc(insSampleUser.getModel());
+                enterFactoryReport.setInspector(insSampleUser.getInspector());
+                enterFactoryReport.setInspectDate(insSampleUser.getInspectDate());
+            }
 
-        // 杞垚Mpa杩涜鎺掑簭
-        Map<String, List<SampleProductExportDto>> sortedMap = sampleProductDto2s.stream()
-                .filter(sampleProductDto2 -> StringUtils.isNotBlank(sampleProductDto2.getInspectionItem()))
-                .collect(Collectors.groupingBy(SampleProductExportDto::getInspectionItem));
-        List<Map.Entry<String, List<SampleProductExportDto>>> entries = new ArrayList<>(sortedMap.entrySet());
-        entries.sort((o1, o2) -> (o1.getValue().get(0).getSort() == null ? 0 : o1.getValue().get(0).getSort())
-                - (o2.getValue().get(0).getSort() == null ? 0 : o2.getValue().get(0).getSort()));
-        // 鍒涘缓涓�涓� LinkedHashMap 鏉ヤ繚鎸佹彃鍏ラ『搴�
-        Map<String, List<SampleProductExportDto>> item = new LinkedHashMap<>();
-        for (Map.Entry<String, List<SampleProductExportDto>> entry : entries) {
-            item.put(entry.getKey(), entry.getValue());
+            Map<String, List<SampleProductExportDto>> item = new LinkedHashMap<>();//闈炵數缂嗛厤缃娴嬮」
+            Map<String, List<SampleProductExportDto>> cableTagItem = new LinkedHashMap<>();//鐢电紗閰嶇疆妫�娴嬮」
+            Map<String, List<SampleProductExportDto>> cableTagEnclosureItem = new LinkedHashMap<>();//鐢电紗閰嶇疆妫�娴嬮」闄勪欢
+
+            AtomicInteger finalIndex = new AtomicInteger(1);
+            List<String> cableTags = insOrderMapper.selectSampleCableTag(insSample.getId());
+            max = cableTags.size();
+            //澶勭悊鐢电紗閰嶇疆妫�娴嬮」
+            Map<String, List<SampleProductExportDto>> tempMap = new HashMap<>();
+            Map<String, List<SampleProductExportDto>> tempMap2 = new HashMap<>();
+            Map<String, List<SampleProductExportDto>> listMap2 = filterItems.stream()
+                    .filter(f -> StringUtils.isNotBlank(f.getCableTag()) && StringUtils.isNotBlank(f.getInspectionItem()))
+                    .collect(Collectors.groupingBy(SampleProductExportDto::getInspectionItem));
+            for (String key : listMap2.keySet()) {
+                List<SampleProductExportDto> sampleProductExportDtos;
+                List<SampleProductExportDto> sampleProductExportDtos2;
+                //澶勭悊鐢电紗閰嶇疆椤�
+                Map<String, List<SampleProductExportDto>> collect = listMap2.get(key).stream().collect(Collectors.groupingBy(SampleProductExportDto::getInspectionItemSubclass));
+                if(cableTags.size()>maxCableTag){
+                    sampleProductExportDtos = transformSampleProduct(cableTags,collect,0,maxCableTag);
+                    sampleProductExportDtos2 = transformSampleProduct(cableTags,collect,maxCableTag,cableTags.size());
+                    tempMap2.put(key,sampleProductExportDtos2);
+                }else{
+                    sampleProductExportDtos = transformSampleProduct(cableTags,collect,0,cableTags.size());
+                }
+                tempMap.put(key,sampleProductExportDtos);
+            }
+            sortSampleProduct(tempMap,cableTagItem);
+            int tagNum = Math.min(max,maxCableTag);
+            List<String> tagList = cableTags.subList(0,tagNum);
+            handlerSampleItems(cableTagItem,finalIndex,sampleList,tagNum,text,rows,rowRenderData,resultCh,tagList,true);
+
+            if(CollectionUtil.isNotEmpty(tempMap2)){
+                sortSampleProduct(tempMap2,cableTagEnclosureItem);
+                //鐢熸垚闄勪欢鐢电紗琛ㄦ牸
+                TableRenderData tableRenderData2 = new TableRenderData();
+                List<String> newCableTags = cableTags.subList(maxCableTag,cableTags.size());
+                AtomicInteger finalIndex2 = new AtomicInteger(1);
+                List<TextRenderData> newText = new ArrayList<TextRenderData>();
+                List<RowRenderData> newRows = new ArrayList<>();
+                RowRenderData newRowRenderData = null;
+                handlerSampleItems(cableTagEnclosureItem,finalIndex2, new ArrayList<>(),newCableTags.size(),newText,newRows,newRowRenderData,resultCh,newCableTags,true);
+                tableRenderData2.setRows(newRows);
+                tableRenderData2.setTableStyle(setTableStyle(newCableTags.size()));
+                HashMap<String, Object> tableMap = new HashMap<>();
+                tableMap.put("enclosureTable",tableRenderData2);
+                tableMap.put("resultCh", resultCh);
+                tableMap.put("writeUrl", null);
+                tableMap.put("examineUrl", null);
+                tableMap.put("ratifyUrl", null);
+                tableMap.put("writeDateUrl", null);
+                tableMap.put("examineDateUrl", null);
+                tableMap.put("ratifyDateUrl", null);
+                tableMap.put("seal1", null);
+                cableTagEnclosureTables.add(tableMap);
+            }
+
+            //澶勭悊闈炵數缂嗛厤缃娴嬮」
+            Map<String, List<SampleProductExportDto>> listMap = filterItems.stream()
+                    .filter(f -> StringUtils.isBlank(f.getCableTag()) && StringUtils.isNotBlank(f.getInspectionItem()))
+                    .collect(Collectors.groupingBy(SampleProductExportDto::getInspectionItem));
+            sortSampleProduct(listMap,item);
+            text = new ArrayList<>();
+            sampleList = new ArrayList<>();
+            handlerSampleItems(item,finalIndex,sampleList,tagNum,text,rows,rowRenderData,resultCh,cableTags,false);
+            tableRenderData.setRows(rows);
+            tableRenderData.setTableStyle(setTableStyle(tagNum));
+            if (!resultCh.get().equals("")) {
+                resultCh.set("缁忔楠岋紝" + resultCh.get() + "鎵�妫�椤圭洰涓嶅悎鏍硷紝鍏朵綑鎵�妫�椤圭洰鍧囧悎鏍笺�傦紙鐩栫珷鏈夋晥锛�");
+            } else {
+                resultCh.set("鏈骇鍝佺鍚堢浉鍏虫爣鍑嗚姹傦紝缁忔楠屽悎鏍煎噯浜堝嚭鍘傦紙鐩栫珷鏈夋晥锛�");
+            }
+
+        }else{
+            templateName = "/static/small-report-template.docx";
+            // 杞垚Mpa杩涜鎺掑簭
+            Map<String, List<SampleProductExportDto>> sortedMap = sampleProductDto2s.stream()
+                    .filter(sampleProductDto2 -> StringUtils.isNotBlank(sampleProductDto2.getInspectionItem()))
+                    .collect(Collectors.groupingBy(SampleProductExportDto::getInspectionItem));
+//            List<Map.Entry<String, List<SampleProductExportDto>>> entries = new ArrayList<>(sortedMap.entrySet());
+//            entries.sort(Comparator.comparingInt(o -> (o.getValue().get(0).getSort() == null ? 0 : o.getValue().get(0).getSort())));
+//            // 鍒涘缓涓�涓� LinkedHashMap 鏉ヤ繚鎸佹彃鍏ラ『搴�
+            Map<String, List<SampleProductExportDto>> item = new LinkedHashMap<>();
+//            for (Map.Entry<String, List<SampleProductExportDto>> entry : entries) {
+//                item.put(entry.getKey(), entry.getValue());
+//            }
+            sortSampleProduct(sortedMap,item);
+
+
+            AtomicInteger finalIndex = new AtomicInteger(1);
+            handlerSampleItems(item,finalIndex,sampleList,max,text,rows,rowRenderData,resultCh,null,true);
+            tableRenderData.setRows(rows);
+            tableRenderData.setTableStyle(setTableStyle(max));
+
+            if (!resultCh.get().equals("")) {
+                resultCh.set("缁忔楠岋紝" + resultCh.get() + "鎵�妫�椤圭洰涓嶅悎鏍硷紝鍏朵綑鎵�妫�椤圭洰鍧囧悎鏍笺��");
+            } else {
+                resultCh.set("缁忔楠屾鎵�" + enterFactoryReport.getSample() + "鍚勯」鐩潎绗﹀悎妫�楠岃鑼冭姹傘��");
+            }
         }
 
-        AtomicInteger finalIndex = new AtomicInteger(1);
+        ConfigureBuilder builder = Configure.builder();
+        builder.useSpringEL(true);
+
+        InputStream inputStream = this.getClass().getResourceAsStream(templateName);
+        XWPFTemplate template = XWPFTemplate.compile(inputStream, builder.build()).render(
+                new HashMap<String, Object>() {{
+                    put("report", enterFactoryReport);
+                    put("standardMethod", standardMethod2.toString().equals("null") ? "" : standardMethod2);
+                    put("orderType", orderType);
+                    put("table", tableRenderData);
+                    put("enclosureTables", cableTagEnclosureTables.isEmpty()?null:cableTagEnclosureTables);
+                    put("resultCh", resultCh);
+                    put("writeUrl", null);
+                    put("examineUrl", null);
+                    put("ratifyUrl", null);
+                    put("writeDateUrl", null);
+                    put("examineDateUrl", null);
+                    put("ratifyDateUrl", null);
+                    put("seal1", null);
+                }});
+        try {
+            // 淇敼鎹㈣鍜屽悎骞堕棶棰�
+            updaeMerge(template.getXWPFDocument(), true);
+            String name = insReport.getCode().replace("/", "") + "-J.docx";
+            template.writeAndClose(Files.newOutputStream(Paths.get(wordUrl + "/" + name)));
+            insReport.setUrl("/word/" + name);
+            insReport.setIsPass(0);
+            insReport.setWriteUserId(SecurityUtils.getUserId().intValue());//鎻愪氦浜�
+            insReport.setWriteTime(LocalDateTime.now());//鎻愪氦鏃堕棿
+            // 鏌ヨ鎶ュ憡, 鍒ゆ柇涔嬪墠鏄惁娣诲姞杩�, 娣诲姞杩囧垹闄�
+            insReportMapper.delete(Wrappers.<InsReport>lambdaQuery()
+                    .eq(InsReport::getInsOrderId, insOrder.getId()));
+            insReportMapper.insert(insReport);
+            inputStream.close();
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * 澶勭悊甯歌妫�娴嬮」
+     * @param item
+     * @param finalIndex
+     * @param sampleList
+     * @param max
+     * @param text
+     * @param rows
+     * @param rowRenderData
+     * @param resultCh
+     */
+    private static void handlerSampleItems(Map<String, List<SampleProductExportDto>> item,AtomicInteger finalIndex,List<SampleProductExportDto> sampleList,Integer max,List<TextRenderData> text,List<RowRenderData> rows,RowRenderData rowRenderData,AtomicReference<String> resultCh,List<String> cableTagList,Boolean hasAddHead ){
         item.forEach((s, sampleProductDtoInside) -> {
             // 娣诲姞妫�楠岄」
             SampleProductExportDto dto2 = new SampleProductExportDto();
@@ -1667,16 +1959,20 @@
                     String productName = productDto2.getInspectionItemClass() + productDto2.getInspectionItem();
                     if (map.containsKey(productName)) {
                         // 濡傛灉鍚嶇О宸茬粡瀛樺湪锛屾坊鍔� lastValue 鍊煎埌 lastValueList 鍒楄〃
-                        map.get(productName)
-                                .getLastValueList()
-                                .add(productDto2.getLastValue());
+                        if(CollectionUtil.isEmpty(map.get(productName).getLastValueList())){
+                            map.get(productName)
+                                    .getLastValueList()
+                                    .add(productDto2.getLastValue());
+                        }
                         map.get(productName)
                                 .getInsResultList()
                                 .add(productDto2.getInsResult());
                     } else {
                         // 濡傛灉鍚嶇О涓嶅瓨鍦紝鐩存帴鏀惧叆 map
-                        productDto2.setLastValueList(new ArrayList<>()); // 妫�楠屽唴瀹�
-                        productDto2.getLastValueList().add(productDto2.getLastValue());
+                        if(CollectionUtil.isEmpty(productDto2.getLastValueList())){
+                            productDto2.setLastValueList(new ArrayList<>()); // 妫�楠屽唴瀹�
+                            productDto2.getLastValueList().add(productDto2.getLastValue());
+                        }
                         productDto2.setInsResultList(new ArrayList<>()); // 缁撴灉
                         productDto2.getInsResultList().add(productDto2.getInsResult());
 
@@ -1708,16 +2004,20 @@
                     String productName = productDto2.getInspectionItemClass() + productDto2.getInspectionItem() + productDto2.getInspectionItemSubclass();
                     if (map.containsKey(productName)) {
                         // 濡傛灉鍚嶇О宸茬粡瀛樺湪锛屾坊鍔� lastValue 鍊煎埌 lastValueList 鍒楄〃
-                        map.get(productName)
-                                .getLastValueList()
-                                .add(productDto2.getLastValue());
+                        if(CollectionUtil.isEmpty(map.get(productName).getLastValueList())){
+                            map.get(productName)
+                                    .getLastValueList()
+                                    .add(productDto2.getLastValue());
+                        }
                         map.get(productName)
                                 .getInsResultList()
                                 .add(productDto2.getInsResult());
                     } else {
                         // 濡傛灉鍚嶇О涓嶅瓨鍦紝鐩存帴鏀惧叆 map
-                        productDto2.setLastValueList(new ArrayList<>()); // 妫�楠屽唴瀹�
-                        productDto2.getLastValueList().add(productDto2.getLastValue());
+                        if(CollectionUtil.isEmpty(productDto2.getLastValueList())){
+                            productDto2.setLastValueList(new ArrayList<>()); // 妫�楠屽唴瀹�
+                            productDto2.getLastValueList().add(productDto2.getLastValue());
+                        }
                         productDto2.setInsResultList(new ArrayList<>()); // 缁撴灉
                         productDto2.getInsResultList().add(productDto2.getInsResult());
 
@@ -1735,8 +2035,9 @@
         });
 
         // 娣诲姞灏忔姤鍛婅〃澶�
-        text = addSmallHead(text, max, rows);
-
+        if(hasAddHead){
+            text = addSmallHead(text, max, rows,cableTagList);
+        }
 
         // 涓棿妫�娴嬪�兼坊鍔�
         for (int i = 0; i < sampleList.size(); i++) {
@@ -1753,7 +2054,7 @@
 
             // 妫�楠岄」鐩�
             TextRenderData middleRenderData2 = new TextRenderData();
-            middleRenderData2.setText(sample.getInspectionName());
+            middleRenderData2.setText(sample.getInspectionName()+"鈭�"+sample.getInspectionName()+i);
             Style middleStyle2 = new Style();
             middleStyle2.setFontFamily("瀹嬩綋");
             middleStyle2.setColor("000000");
@@ -1840,7 +2141,7 @@
                     TextRenderData middleRenderData6 = new TextRenderData();
                     middleRenderData6.setText((StringUtils.isNotEmpty(sample.getLastValue()) ?
                             sample.getLastValue() : "")
-                            + "鈭�" + (7 + i));
+                            + "鈭�" + (finalIndex.get() +"_"+ i));
                     Style middleStyle6 = new Style();
                     middleStyle6.setFontFamily("瀹嬩綋");
                     middleStyle6.setColor("000000");
@@ -1878,7 +2179,7 @@
                             String type;
                             if (count.equals(0)) {
                                 // 娣诲姞涓嶅悎鏍兼弿杩�
-                                String item1 = (max == 1 ? "" : "绗�" + Integer.toString(index) + "娆�")
+                                String item1 = (max == 1 ? "" : "绗�" + index + "娆�")
                                         + sample.getInspectionItem()
                                         + (StringUtils.isBlank(sample.getInspectionItemSubclass()) ? "" : "" + sample.getInspectionItemSubclass());
                                 if (resultCh.get().equals("")) {
@@ -1918,99 +2219,17 @@
             text = new ArrayList<>();
         }
 
-        TableRenderData tableRenderData = new TableRenderData();
-        tableRenderData.setRows(rows);
-
-        //璁剧疆鏍峰紡
-        TableStyle tableStyle = new TableStyle();
-        for (int i = 1; i <= max; i++) {
-            // 鏍规嵁鍑忓帇閭g粨鏋滀釜鏁颁慨鏀归暱搴�
-            switch (i) {
-                case 1:
-                    tableStyle.setColWidths(new int[]{650, 2900, 850, 2300, 2100, 1200});
-                    break;
-                case 2:
-                    tableStyle.setColWidths(new int[]{650, 2700, 850, 2200, 1200, 1200, 1200});
-                    break;
-                case 3:
-                    tableStyle.setColWidths(new int[]{650, 2700, 850, 1600, 1000, 1000, 1000, 1200});
-                    break;
-                case 4:
-                    tableStyle.setColWidths(new int[]{650, 2400, 850, 1500, 850, 850, 850, 850, 1200});
-                    break;
-                case 5:
-                    tableStyle.setColWidths(new int[]{650, 2200, 850, 1350, 750, 750, 750, 750, 750, 1200});
-                    break;
-            }
-        }
-        tableStyle.setWidth("10000");
-        tableStyle.setAlign(TableRowAlign.CENTER);
-        BorderStyle borderStyle = new BorderStyle();
-        borderStyle.setColor("000000");
-        borderStyle.setType(XWPFTable.XWPFBorderType.SINGLE);
-        borderStyle.setSize(4);
-        tableStyle.setLeftBorder(borderStyle);
-        tableStyle.setRightBorder(borderStyle);
-        tableStyle.setInsideHBorder(borderStyle); // 璁剧疆姘村钩鍐呰竟妗�
-        tableStyle.setInsideVBorder(borderStyle);
-        tableRenderData.setTableStyle(tableStyle);
-
-        if (!resultCh.get().equals("")) {
-            resultCh.set("缁忔楠岋紝" + resultCh.get() + "鎵�妫�椤圭洰涓嶅悎鏍硷紝鍏朵綑鎵�妫�椤圭洰鍧囧悎鏍笺��");
-        } else {
-            resultCh.set("缁忔楠屾鎵�" + enterFactoryReport.getSample() + "鍚勯」鐩潎绗﹀悎妫�楠岃鑼冭姹傘��");
-        }
-
-        ConfigureBuilder builder = Configure.builder();
-        builder.useSpringEL(true);
-        // 鑾峰彇褰撳墠鏃堕棿
-        LocalDate currentDate = LocalDate.now();
-        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
-        String formattedDate = currentDate.format(formatter);
-
-        InputStream inputStream = this.getClass().getResourceAsStream("/static/small-report-template.docx");
-        XWPFTemplate template = XWPFTemplate.compile(inputStream, builder.build()).render(
-                new HashMap<String, Object>() {{
-                    put("report", enterFactoryReport);
-                    put("standardMethod", standardMethod2.toString().equals("null") ? "" : standardMethod2);
-                    put("orderType", orderType);
-                    put("table", tableRenderData);
-                    put("resultCh", resultCh);
-                    put("writeUrl", null);
-                    put("examineUrl", null);
-                    put("ratifyUrl", null);
-                    put("writeDateUrl", null);
-                    put("examineDateUrl", null);
-                    put("ratifyDateUrl", null);
-                    put("seal1", null);
-                }});
-        try {
-            // 淇敼鎹㈣鍜屽悎骞堕棶棰�
-            updaeMerge(template.getXWPFDocument(), true);
-            String name = insReport.getCode().replace("/", "") + "-J.docx";
-            template.writeAndClose(Files.newOutputStream(Paths.get(wordUrl + "/" + name)));
-            insReport.setUrl("/word/" + name);
-            insReport.setIsPass(0);
-            insReport.setWriteUserId(SecurityUtils.getUserId().intValue());//鎻愪氦浜�
-            insReport.setWriteTime(LocalDateTime.now());//鎻愪氦鏃堕棿
-            // 鏌ヨ鎶ュ憡, 鍒ゆ柇涔嬪墠鏄惁娣诲姞杩�, 娣诲姞杩囧垹闄�
-            insReportMapper.delete(Wrappers.<InsReport>lambdaQuery()
-                    .eq(InsReport::getInsOrderId, insOrder.getId()));
-            insReportMapper.insert(insReport);
-
-        } catch (IOException e) {
-            throw new RuntimeException(e);
-        }
     }
 
+
     /**
-     * 娣诲姞灏忓疂琛ㄥご
+     * 娣诲姞灏忔姤鍛婅〃澶�
      * @param text
      * @param max
      * @param rows
      * @return
      */
-    private static List<TextRenderData> addSmallHead(List<TextRenderData> text, Integer max, List<RowRenderData> rows) {
+    private static List<TextRenderData> addSmallHead(List<TextRenderData> text, Integer max, List<RowRenderData> rows,List<String> cableTagList) {
         RowRenderData rowRenderData;
 //        // 澶�
         TextRenderData headRenderData1 = new TextRenderData();
@@ -2068,7 +2287,7 @@
         text = new ArrayList<>();
 
         // 绗簩琛�(鍙兘娌℃湁)
-        if (max > 1) {
+        if (max > 1 && CollectionUtil.isEmpty(cableTagList)) {
             TextRenderData tagRenderData1 = new TextRenderData();
             tagRenderData1.setText("");
             Style tagStyle1 = new Style();
@@ -2122,8 +2341,62 @@
             rowRenderData = Rows.of(text4).center().rowAtleastHeight(1).create();
             rows.add(rowRenderData);
             text = new ArrayList<>();
+        }
+        //濡傛灉鏈夌數缂嗛鑹诧紝鐢熸垚棰滆壊鏍囪瘑琛�
+        if(CollectionUtil.isNotEmpty(cableTagList)){
+            TextRenderData tagRenderData1 = new TextRenderData();
+            tagRenderData1.setText("");
+            Style tagStyle1 = new Style();
+            tagStyle1.setFontFamily("瀹嬩綋");
+            tagStyle1.setColor("000000");
+            tagRenderData1.setStyle(tagStyle1);
+            text.add(tagRenderData1);
 
+            TextRenderData tagRenderData2 = new TextRenderData();
+            tagRenderData2.setText("缁濈紭绾胯姱棰滆壊鍜屾爣蹇�");
+            Style tagStyle2 = new Style();
+            tagStyle2.setFontFamily("瀹嬩綋");
+            tagStyle2.setColor("000000");
+            tagRenderData2.setStyle(tagStyle2);
+            text.add(tagRenderData2);
 
+            TextRenderData tagRenderData4 = new TextRenderData();
+            tagRenderData4.setText("/");
+            Style tagStyle4 = new Style();
+            tagStyle4.setFontFamily("瀹嬩綋");
+            tagStyle4.setColor("000000");
+            tagRenderData4.setStyle(tagStyle4);
+            text.add(tagRenderData4);
+
+            TextRenderData tagRenderData5 = new TextRenderData();
+            tagRenderData5.setText("/");
+            Style tagStyle5 = new Style();
+            tagStyle5.setFontFamily("瀹嬩綋");
+            tagStyle5.setColor("000000");
+            tagRenderData5.setStyle(tagStyle5);
+            text.add(tagRenderData5);
+
+            for (String cableTag : cableTagList) {
+                TextRenderData tagRenderData6 = new TextRenderData();
+                tagRenderData6.setText(cableTag);
+                Style tagStyle6 = new Style();
+                tagStyle6.setFontFamily("瀹嬩綋");
+                tagStyle6.setColor("000000");
+                tagRenderData6.setStyle(tagStyle6);
+                text.add(tagRenderData6);
+            }
+            TextRenderData tagRenderData7 = new TextRenderData();
+            tagRenderData7.setText("/");
+            Style tagStyle7 = new Style();
+            tagStyle7.setFontFamily("瀹嬩綋");
+            tagStyle7.setColor("000000");
+            tagRenderData7.setStyle(tagStyle7);
+            text.add(tagRenderData7);
+
+            TextRenderData[] text4 = text.toArray(new TextRenderData[0]);
+            rowRenderData = Rows.of(text4).center().rowAtleastHeight(1).create();
+            rows.add(rowRenderData);
+            text = new ArrayList<>();
         }
 
         return text;
@@ -2138,7 +2411,6 @@
      * @param
      */
     private void addBitReport(Integer orderId, InsOrder insOrder) {
-        Map<String, String> user = insProductMapper.selectUserById(insOrder.getUserId());
         //samples鏄笉鍖呮嫭甯︽湁"/"鐨勬牱鍝�
         List<SampleProductDto> samples = insSampleMapper.selectSampleProductListByOrderId(orderId);
         InsReport insReport = new InsReport();
@@ -2157,7 +2429,6 @@
         boolean isOneSample = samples.size() == 1 ? true : false;
         /*鍩虹鎶ュ憡(鏍规嵁缁樺埗鐨勫師濮嬭褰曟ā鐗堝舰鎴�)*/
         samples.forEach(a -> {
-            Map<Integer, String> map2 = new HashMap<>();
             models.add(a.getModel());
             String standardMethodCode = baseMapper.getStandardMethodCode(a.getStandardMethodListId());
             if (StrUtil.isNotBlank(a.getSpecialStandardMethod())) {
@@ -2503,6 +2774,7 @@
         InputStream inputStream = this.getClass().getResourceAsStream("/static/report-template.docx");
         Configure configure = Configure.builder()
                 .bind("deviceList", new HackLoopTableRenderPolicy())
+                .useSpringEL(true)
                 .build();
 
         XWPFTemplate template = XWPFTemplate.compile(inputStream, configure).render(
@@ -2551,6 +2823,7 @@
             insReportMapper.delete(Wrappers.<InsReport>lambdaQuery()
                     .eq(InsReport::getInsOrderId, insOrder.getId()));
             insReportMapper.insert(insReport);
+            inputStream.close();
         } catch (IOException e) {
             throw new RuntimeException(e);
         }
@@ -4105,7 +4378,7 @@
     }
 
     /**
-     * 淇濆瓨鍏冩闃块噷杩涜揣楠岃瘉鍘熷璁板綍
+     * *****淇濆瓨鍏冩闃块噷杩涜揣楠岃瘉鍘熷璁板綍*****
      * @param insOrderId 璁㈠崟Id
      * @param examineUserId  澶嶆牳浜篒d
      * @param writeUserId  妫�楠屽憳Id
@@ -4225,6 +4498,11 @@
 
         // 淇濆瓨鍒伴檮浠堕噷闈�
         uploadFile(insOrderId, multipartFile);
+        try {
+            inputStream.close();
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
 
     }
 
@@ -4255,7 +4533,7 @@
 
 
     /**
-     * 鏍煎紡鍖栬繘鍘傞獙璇佸唴瀹�
+     * ***鏍煎紡鍖栬繘鍘傞獙璇佸唴瀹�****
      * @param basicType
      * @return
      */
@@ -4284,7 +4562,7 @@
     }
 
     /**
-     * word杞崲pdf
+     * ***word杞崲pdf***
      * @param path
      * @return
      */
@@ -4301,11 +4579,10 @@
         FileOutputStream os = null;
         try {
             //鍑瘉 涓嶇劧鍒囨崲鍚庢湁姘村嵃
-            InputStream is = Files.newInputStream(new File(licenseUrl).toPath());
+            InputStream is = new ClassPathResource("/lib/license.xml").getInputStream();
             License license = new License();
             license.setLicense(is);
             if (!license.getIsLicensed()) {
-                System.out.println("License楠岃瘉涓嶉�氳繃...");
                 return null;
             }
             //鐢熸垚涓�涓┖鐨凱DF鏂囦欢
@@ -4333,6 +4610,43 @@
     }
 
     /**
+     * *****淇敼鎴愬搧鎶芥牱鐘舵��******
+     * @param insSamples
+     * @param order
+     */
+    private void addProductSpotCheck(List<InsSample> insSamples, InsOrder order) {
+        Long unqualifiedCount = 0L;
+        if (CollectionUtils.isNotEmpty(insSamples)) {
+            unqualifiedCount = insProductMapper.selectCount(Wrappers.<InsProduct>lambdaQuery()
+                    .in(InsProduct::getInsSampleId, insSamples.stream().map(InsSample::getId).collect(Collectors.toList()))
+                    .eq(InsProduct::getInsResult, 0));
+
+            // 鍒ゆ柇濡傛灉鏈変笉鍚堟牸鐨勬楠岄」, 鍒ゆ柇鏈夋病鏈夋楠岄」澶嶆祴, 澶嶆牳鍚堟牸涔熺畻鍚堟牸閫氳繃
+            if (!unqualifiedCount.equals(0L)) {
+                List<InsProduct> productList = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
+                        .in(InsProduct::getInsSampleId, insSamples.stream().map(InsSample::getId).collect(Collectors.toList()))
+                        .eq(InsProduct::getInsResult, 0));
+
+                boolean flag = true;
+                for (InsProduct insProduct : productList) {
+                    Long unqualifiedProductCount = insUnqualifiedRetestProductMapper.selectCount(Wrappers.<InsUnqualifiedRetestProduct>lambdaQuery()
+                            .eq(InsUnqualifiedRetestProduct::getInsProductId, insProduct.getId())
+                            .ne(InsUnqualifiedRetestProduct::getInsResult, 0));
+                    if (unqualifiedProductCount != 2) {
+                        flag = false;
+                    }
+                }
+                if (flag) {
+                    unqualifiedCount = 0L;
+                }
+            }
+        }
+        spotCheckQuarterItemMapper.update(null, Wrappers.<SpotCheckQuarterItem>lambdaUpdate()
+                .eq(SpotCheckQuarterItem::getQuarterItemId, order.getQuarterItemId())
+                .set(SpotCheckQuarterItem::getResult, unqualifiedCount.equals(0L) ? "鍚堟牸" : "涓嶅悎鏍�"));
+    }
+
+    /**
      * 娣诲姞宸ユ椂
      * @param userId
      * @param insProduct
@@ -4343,43 +4657,80 @@
             return;
         }
 
-        //棣栧厛鍒ゆ柇褰撳墠浜虹殑褰撳墠鏃堕棿鏄惁鏄帓鐝椂闂村唴,濡傛灉涓嶆槸灏辨槸鍔犵彮
-        LocalDateTime today = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT);
-
         //鏍¢獙濡傛灉杩欎釜浜鸿繖涓娴嬮」鐩凡缁忔坊鍔犺繃浜�
         List<AuxiliaryOutputWorkingHours> count2s = auxiliaryOutputWorkingHoursMapper.selectList(Wrappers.<AuxiliaryOutputWorkingHours>lambdaQuery()
                 .eq(AuxiliaryOutputWorkingHours::getCheck, userId)
                 .eq(AuxiliaryOutputWorkingHours::getInsProductId, insProduct.getId()));
         if (CollectionUtils.isNotEmpty(count2s)) {
-            auxiliaryOutputWorkingHoursMapper.deleteBatchIds(count2s.stream().map(auxiliaryOutputWorkingHours -> auxiliaryOutputWorkingHours.getId()).collect(Collectors.toList()));
-        }
-        if (ObjectUtils.isNotEmpty(insProduct.getManHour()) && StringUtils.isNotBlank(insProduct.getLastValue())) {
-            AuxiliaryOutputWorkingHours auxiliaryOutputWorkingHours = new AuxiliaryOutputWorkingHours();
-            auxiliaryOutputWorkingHours.setInspectionItemClass(insProduct.getInspectionItemClass());//妫�娴嬮」鍒嗙被
-            auxiliaryOutputWorkingHours.setInspectionItem(insProduct.getInspectionItem());//妫�娴嬬埗椤�
-            auxiliaryOutputWorkingHours.setInspectionItemSubclass(insProduct.getInspectionItemSubclass());//妫�娴嬪瓙椤�
-            auxiliaryOutputWorkingHours.setSample(insSampleMapper.selectById(insProduct.getInsSampleId()).getSampleCode());//鏍峰搧缂栧彿
-            auxiliaryOutputWorkingHours.setOrderId(insOrder.getId());//璁㈠崟id
-            auxiliaryOutputWorkingHours.setOrderNo(insOrder.getEntrustCode());//闈炲姞鐝鎵樺崟鍙�
-            auxiliaryOutputWorkingHours.setWorkTime(insProduct.getManHour());//闈炲姞鐝伐鏃�
-            auxiliaryOutputWorkingHours.setAmount(1);//闈炲姞鐝暟閲�
-            auxiliaryOutputWorkingHours.setOutputWorkTime((ObjectUtils.isNotEmpty(auxiliaryOutputWorkingHours.getOvertimeWorkTime()) ? auxiliaryOutputWorkingHours.getOvertimeWorkTime() : BigDecimal.ZERO).add(ObjectUtils.isNotEmpty(auxiliaryOutputWorkingHours.getWorkTime()) ? auxiliaryOutputWorkingHours.getWorkTime() : BigDecimal.ZERO));//浜ч噺宸ユ椂
-            auxiliaryOutputWorkingHours.setManHourGroup(insProduct.getManHourGroup());//宸ユ椂鍒嗙粍
-            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
-            DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
-            auxiliaryOutputWorkingHours.setDateTime(LocalDateTime.now().toLocalDate().atStartOfDay().format(formatters));//鏃ユ湡
-            LocalDateTime localDateTime = LocalDateTime.now();
-            DateTime parse = DateUtil.parse(localDateTime.format(formatter));
-            auxiliaryOutputWorkingHours.setWeekDay(getWeek(localDateTime.format(formatters)));//鏄熸湡
-            auxiliaryOutputWorkingHours.setWeek(String.valueOf(DateUtil.weekOfYear(DateUtil.offsetDay(parse, 1))));//鍛ㄦ
-            auxiliaryOutputWorkingHours.setCheck(userId);//妫�娴嬩汉
-            auxiliaryOutputWorkingHours.setPrice(insProduct.getPrice());//鍗曚环
-            auxiliaryOutputWorkingHours.setSampleId(insProduct.getInsSampleId());//鏍峰搧id
-            auxiliaryOutputWorkingHours.setInsProductId(insProduct.getId());//妫�楠岄」id
+            for (AuxiliaryOutputWorkingHours auxiliaryOutputWorkingHours : count2s) {
+                auxiliaryOutputWorkingHours.setCheck(userId);//妫�娴嬩汉
+            }
+            auxiliaryOutputWorkingHoursService.updateBatchById(count2s);
+        } else {
+            if (ObjectUtils.isNotEmpty(insProduct.getManHour()) && StringUtils.isNotBlank(insProduct.getLastValue())) {
+                AuxiliaryOutputWorkingHours auxiliaryOutputWorkingHours = new AuxiliaryOutputWorkingHours();
+                auxiliaryOutputWorkingHours.setInspectionItemClass(insProduct.getInspectionItemClass());//妫�娴嬮」鍒嗙被
+                auxiliaryOutputWorkingHours.setInspectionItem(insProduct.getInspectionItem());//妫�娴嬬埗椤�
+                auxiliaryOutputWorkingHours.setInspectionItemSubclass(insProduct.getInspectionItemSubclass());//妫�娴嬪瓙椤�
+                auxiliaryOutputWorkingHours.setSample(insSampleMapper.selectById(insProduct.getInsSampleId()).getSampleCode());//鏍峰搧缂栧彿
+                auxiliaryOutputWorkingHours.setOrderId(insOrder.getId());//璁㈠崟id
+                auxiliaryOutputWorkingHours.setOrderNo(insOrder.getEntrustCode());//闈炲姞鐝鎵樺崟鍙�
+                auxiliaryOutputWorkingHours.setWorkTime(insProduct.getManHour());//闈炲姞鐝伐鏃�
+                auxiliaryOutputWorkingHours.setAmount(1);//闈炲姞鐝暟閲�
+                auxiliaryOutputWorkingHours.setOutputWorkTime((ObjectUtils.isNotEmpty(auxiliaryOutputWorkingHours.getOvertimeWorkTime()) ? auxiliaryOutputWorkingHours.getOvertimeWorkTime() : BigDecimal.ZERO).add(ObjectUtils.isNotEmpty(auxiliaryOutputWorkingHours.getWorkTime()) ? auxiliaryOutputWorkingHours.getWorkTime() : BigDecimal.ZERO));//浜ч噺宸ユ椂
+                auxiliaryOutputWorkingHours.setManHourGroup(insProduct.getManHourGroup());//宸ユ椂鍒嗙粍
+                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+                DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+                auxiliaryOutputWorkingHours.setDateTime(LocalDateTime.now().toLocalDate().atStartOfDay().format(formatters));//鏃ユ湡
+                LocalDateTime localDateTime = LocalDateTime.now();
+                DateTime parse = DateUtil.parse(localDateTime.format(formatter));
+                auxiliaryOutputWorkingHours.setWeekDay(getWeek(localDateTime.format(formatters)));//鏄熸湡
+                auxiliaryOutputWorkingHours.setWeek(String.valueOf(DateUtil.weekOfYear(DateUtil.offsetDay(parse, 1))));//鍛ㄦ
+                auxiliaryOutputWorkingHours.setCheck(userId);//妫�娴嬩汉
+                auxiliaryOutputWorkingHours.setPrice(insProduct.getPrice());//鍗曚环
+                auxiliaryOutputWorkingHours.setSampleId(insProduct.getInsSampleId());//鏍峰搧id
+                auxiliaryOutputWorkingHours.setInsProductId(insProduct.getId());//妫�楠岄」id
 
-            auxiliaryOutputWorkingHoursMapper.insert(auxiliaryOutputWorkingHours);
+                auxiliaryOutputWorkingHoursMapper.insert(auxiliaryOutputWorkingHours);
 
+            }
         }
     }
 
+
+    public static String getWeek(String dayStr) {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        try {
+            Date date = sdf.parse(dayStr);
+            Calendar calendar = Calendar.getInstance();
+            calendar.setTime(date);
+            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
+            int day = calendar.get(Calendar.DAY_OF_MONTH);
+            return getWeekDay(dayOfWeek);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    public static String getWeekDay(int dayOfWeek) {
+        switch (dayOfWeek) {
+            case Calendar.MONDAY:
+                return "鍛ㄤ竴";
+            case Calendar.TUESDAY:
+                return "鍛ㄤ簩";
+            case Calendar.WEDNESDAY:
+                return "鍛ㄤ笁";
+            case Calendar.THURSDAY:
+                return "鍛ㄥ洓";
+            case Calendar.FRIDAY:
+                return "鍛ㄤ簲";
+            case Calendar.SATURDAY:
+                return "鍛ㄥ叚";
+            case Calendar.SUNDAY:
+                return "鍛ㄦ棩";
+            default:
+                return "鏈煡";
+        }
+    }
 }

--
Gitblit v1.9.3