From 31ccc9cd47f96cea6e4e13b078187fd3201c4666 Mon Sep 17 00:00:00 2001
From: liding <756868258@qq.com>
Date: 星期五, 04 九月 2026 16:35:24 +0800
Subject: [PATCH] feat(report): 更新检测报告模板并优化报告生成功能 - 优化设备信息展示格式,支持多设备列表显示 - 统一检测报告和检验报告使用新版模板格式

---
 inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java |  991 ++++++++++++++++++++++++++++++++++++++++++++-------------
 1 files changed, 755 insertions(+), 236 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 3724d3d..2c9bf30 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;
@@ -36,6 +37,7 @@
 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.*;
@@ -43,15 +45,13 @@
 import com.ruoyi.inspect.pojo.*;
 import com.ruoyi.inspect.service.*;
 import com.ruoyi.inspect.util.HackLoopTableRenderPolicy;
+import com.ruoyi.inspect.util.PreserveReportPicturePlaceholderHandler;
 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.pojo.AuxiliaryOutputWorkingHoursTemporary;
 import com.ruoyi.performance.service.AuxiliaryOutputWorkingHoursService;
-import com.ruoyi.performance.service.AuxiliaryOutputWorkingHoursTemporaryService;
 import com.ruoyi.system.mapper.CustomMapper;
 import com.ruoyi.system.mapper.UserMapper;
 import com.ruoyi.system.service.ISysDictTypeService;
@@ -74,9 +74,7 @@
 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.atomic.AtomicBoolean;
@@ -90,6 +88,9 @@
  */
 @Service
 public class InsOrderPlanServiceImpl extends ServiceImpl<InsOrderMapper, InsOrder> implements InsOrderPlanService {
+
+    private static final int DETECTION_REPORT = 0;
+    private static final int INSPECTION_REPORT = 1;
 
     @Resource
     private InsSampleMapper insSampleMapper;
@@ -131,6 +132,8 @@
     @Resource
     private IfsInventoryQuantityMapper ifsInventoryQuantityMapper;
     @Resource
+    private IfsPartPropsRecordMapper ifsPartPropsRecordMapper;
+    @Resource
     private InsReportService insReportService;
     @Resource
     private InsUnqualifiedRetestProductMapper insUnqualifiedRetestProductMapper;
@@ -167,9 +170,7 @@
     public IPage<InsOrderPlanVO> selectInsOrderPlanList(Page page, InsOrderPlanDTO insOrderPlanDTO) {
         // todo: 浠呯湅鑷繁鎴栬�呭疄楠屽
         //鑾峰彇褰撳墠浜烘墍灞炲疄楠屽id
-
         String laboratory = null;
-
         String userName = null;
         Integer userId = null;
         if (ObjectUtil.isNotEmpty(insOrderPlanDTO.getUserId())) {
@@ -277,8 +278,14 @@
     }
 
     @Override
-    public List<String> checkSubmitPlan(Integer orderId, String laboratory) {
+    public Map<String,Object> checkSubmitPlan(Integer orderId, String laboratory, Integer reportType) {
+        Map<String, Object> map = new HashMap<>();
         List<String> collect = new ArrayList<>();
+        if (Objects.equals(DETECTION_REPORT, reportType)) {
+            map.put("errorMsg", collect);
+            map.put("unInsOrderCount", 0L);
+            return map;
+        }
         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<InsProduct> insProducts = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
@@ -303,7 +310,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
@@ -756,8 +775,15 @@
 
     @Override
     @Transactional(rollbackFor = Exception.class)
-    public int submitPlan(Integer orderId, String laboratory, Integer verifyUser, String entrustCode) {
-        InsOrder order = insOrderMapper.selectById(orderId);
+    public int submitPlan(Integer orderId, String laboratory, Integer verifyUser, String entrustCode, Boolean registerInsResults, Integer reportType) {
+        if (!Objects.equals(DETECTION_REPORT, reportType) && !Objects.equals(INSPECTION_REPORT, reportType)) {
+            throw new ErrorException("璇烽�夋嫨鎶ュ憡绫诲瀷");
+        }
+        InsOrder order = insOrderMapper.selectOne(Wrappers.<InsOrder>lambdaQuery()
+                .eq(InsOrder::getId, orderId)
+                .last("FOR UPDATE"));
+        boolean isInspectionReport = Objects.equals(INSPECTION_REPORT, reportType);
+        registerInsResults = isInspectionReport && Boolean.TRUE.equals(registerInsResults);
         // 1. 鍒ゆ柇鏄惁鏈夐噸澶嶇紪鍙�, 鏈夐噸澶嶇紪鍙峰仛鎻愰啋
         Long codeCount = insOrderMapper.selectCount(Wrappers.<InsOrder>lambdaQuery()
                 .ne(InsOrder::getState, -1)
@@ -783,13 +809,18 @@
                 .in(InsProduct::getInsSampleId, InsSampleIds)
                 .eq(InsProduct::getSonLaboratory, laboratory)
                 .eq(InsProduct::getState, 1)
-                .and(wrapper -> wrapper
-                        .isNull(InsProduct::getInsResult)
-                        .or()
-                        .eq(InsProduct::getInsResult, 2)
-                )
+                .and(wrapper -> {
+                    if (Objects.equals(reportType, DETECTION_REPORT)) {
+                        wrapper.isNull(InsProduct::getLastValue).or().eq(InsProduct::getLastValue, "");
+                    } else {
+                        wrapper.isNull(InsProduct::getInsResult).or().eq(InsProduct::getInsResult, 2);
+                    }
+                })
                 .ne(InsProduct::getIsBinding, 1));
-        insProducts.addAll(insProductMapper.selectFiberInsProduct(InsSampleIds, laboratory));
+        if (Objects.equals(reportType, INSPECTION_REPORT)) {
+            List<InsProduct> insProducts1 = insProductMapper.selectFiberInsProduct(InsSampleIds, laboratory);
+            insProducts.addAll(insProducts1);
+        }
         if (insProducts.size() > 0) {
             String str = "";
             int count = 0;
@@ -853,7 +884,7 @@
         });
 
         // 8.鎻愪氦鐢熸垚鎶ュ憡
-        this.generateReport(orderId);
+        this.generateReport(orderId, reportType);
 
         // 9.娣诲姞涓存椂pdf鐢熸垚鍦板潃
         InsReport report = insReportMapper.selectOne(Wrappers.<InsReport>lambdaQuery()
@@ -867,7 +898,7 @@
 
         // 11.鎴愬搧鎶芥牱娣诲姞鍚堟牸鐘舵��
         // 鍒ゆ柇鏄惁鏈夋娊鏍蜂俊鎭�
-        if (order.getQuarterItemId() != null) {
+        if (isInspectionReport && order.getQuarterItemId() != null) {
             // 鍒ゆ柇鏄惁鏈変笉鍚堟牸
             this.addProductSpotCheck(insSamples, order);
         }
@@ -922,11 +953,11 @@
         });
 
         // 14.ifs绉诲簱(鍘熸潗鏂欓渶瑕佽繘琛岀Щ搴撴搷浣�) --> 鏈�鍚庢墽琛�,鍥犱负澶辫触鏃犳硶鍥炴粴
-        if (ifsInventoryQuantity != null) {
+        if (ifsInventoryQuantity != null && isInspectionReport) {
             // 鐧昏妫�楠岀粨鏋�
             // 鍒ゆ柇鏄惁鏈変笉鍚堟牸, 鏈変笉鍚堟牸涓嶈兘绉诲簱
             // todo: ifs绉诲簱
-            insReportService.isRawMaterial(order);
+            insReportService.isRawMaterial(order,registerInsResults,false);
 
             // 15 鍒ゆ柇褰撳墠鏍峰搧鏄惁涓哄師鏉愭枡, 鍘熸潗鏂欓渶瑕佽繘琛屾暟鎹垎鏋�, 鍒ゆ柇涔嬪墠10鏉℃暟鎹悓涓�涓緵搴斿晢, 鍚屼竴涓楠岄」鐨勫亸宸槸鍚﹁秴杩�10%
             // 鏌ヨifs淇℃伅鑾峰彇鑾峰彇鍓�10涓緵搴斿晢涓�鏍风殑, 妫�楠岄」涓�鏍蜂俊鎭�
@@ -936,7 +967,7 @@
             });
 
 
-        } else {
+        } else if (isInspectionReport) {
             // 淇敼鎴愬搧鐘舵��
             // 鍒ゆ柇鏄惁鏈変笉鍚堟牸
             Long unqualifiedCount = insReportService.getUnqualifiedCount(order);
@@ -963,7 +994,7 @@
     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)) {
+            if ("1".equals(insProduct.getInspectionValueType()) && Objects.equals(insProduct.getInsResult(), 1)) {
                 List<InsProductDeviationWarningDetail> insProductAnalysisDtoList = insProductMapper.selectAnalysis(insProduct, ifsInventoryQuantity.getSupplierName());
 
                 if (CollectionUtils.isEmpty(insProductAnalysisDtoList)) {
@@ -1253,22 +1284,24 @@
      * 鐢熸垚鎶ュ憡
      * @param orderId
      */
-    private void generateReport(Integer orderId) {
+    private void generateReport(Integer orderId, Integer reportType) {
         /*鏍峰搧涓嬬殑椤圭洰鍙鏈変竴涓」鐩笉鍚堟牸鍒欐楠岀粨鏋滀负0,鍚﹀垯涓�1*/
         //杩欓噷鐨刬nsSamples鏄鍗曚笅鐨勬墍鏈夋牱鍝佸寘鎷�("/")
         List<InsSample> insSamples = insSampleMapper.selectList(Wrappers.<InsSample>lambdaQuery().eq(InsSample::getInsOrderId, orderId));
+        if (Objects.equals(reportType, INSPECTION_REPORT)) {
         for (InsSample insSample : insSamples) {
             List<InsProduct> insProducts = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
                     .eq(InsProduct::getInsSampleId, insSample.getId())
                     .eq(InsProduct::getState, 1)
                     .ne(InsProduct::getIsBinding, 1));
-            List<Integer> results = insProducts.stream().map(InsProduct::getInsResult).filter(str -> str != null).collect(Collectors.toList());
+            List<Integer> results = insProducts.stream().map(InsProduct::getInsResult).filter(Objects::nonNull).collect(Collectors.toList());
             if (results.contains(0)) {
                 insSample.setInsResult(0);
             } else {
                 insSample.setInsResult(1);
             }
             insSampleMapper.updateById(insSample);
+        }
         }
         InsOrder insOrder = insOrderMapper.selectById(orderId);
         // 鎶芥鍙樻垚濮旀墭妫�楠�
@@ -1279,10 +1312,10 @@
         // 鍒ゆ柇鏄ぇ鎶ュ憡杩樻槸灏忔姤鍛�  杩涘巶灏忔姤鍛�, 鍏朵粬閮芥槸澶ф姤鍛�
         if (insOrder.getOrderType().equals(InsOrderTypeConstants.ENTER_THE_FACTORY)) {
             // 鐢熸垚灏忔姤鍛�
-            addSmallReport(orderId, insOrder, insSamples);
+            addSmallReport(orderId, insOrder, insSamples, reportType);
         } else {
             //鐢熸垚澶ф姤鍛�
-            addBitReport(orderId, insOrder);
+            addBitReport(orderId, insOrder, reportType);
         }
 
     }
@@ -1624,16 +1657,117 @@
     /*****************************************************  灏忔姤鍛�    ***************************************************************************/
 
     /**
+     * 璁剧疆琛ㄦ牸鏍峰紡
+     * @param max 鏍囪瘑鏈�澶т釜鏁�
+     * @return
+     */
+    private TableStyle setTableStyle(int max, boolean showResult){
+        //璁剧疆鏍峰紡
+        TableStyle tableStyle = new TableStyle();
+        if (!showResult) {
+            switch (max) {
+                case 1: tableStyle.setColWidths(new int[]{650, 3000, 850, 2400, 3100}); break;
+                case 2: tableStyle.setColWidths(new int[]{650, 2800, 850, 2200, 1750, 1750}); break;
+                case 3: tableStyle.setColWidths(new int[]{650, 2600, 850, 1800, 1400, 1400, 1400}); break;
+                case 4: tableStyle.setColWidths(new int[]{650, 2400, 850, 1600, 1125, 1125, 1125, 1125}); break;
+                case 5: tableStyle.setColWidths(new int[]{650, 2200, 850, 1500, 960, 960, 960, 960, 960}); break;
+                default: break;
+            }
+        } else 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
      * @param insSamples
      */
-    private void addSmallReport(Integer orderId, InsOrder insOrder, List<InsSample> insSamples) {
+    private void addSmallReport(Integer orderId, InsOrder insOrder, List<InsSample> insSamples, Integer reportType) {
         InsReport insReport = new InsReport();
         AtomicReference<String> resultCh = new AtomicReference<>("");
+        boolean showResult = Objects.equals(reportType, INSPECTION_REPORT);
         insReport.setCode(insOrder.getEntrustCode());
         insReport.setInsOrderId(orderId);
+        insReport.setReportType(reportType);
         InsSample insSample = insSamples.get(0);
         // 濉厖鍩虹鏁版嵁
         EnterFactoryReport enterFactoryReport = new EnterFactoryReport();
@@ -1641,11 +1775,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());
 
         // 妫�娴嬩緷鎹�
@@ -1663,6 +1803,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()
@@ -1673,21 +1814,170 @@
 
         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 -> !showResult || f.getInsResult() != 3)
+                    .collect(Collectors.toList());
+            int maxCableTag = 5;//鍗曚釜琛ㄦ牸锛岀數缂嗛鑹叉爣璇嗘渶澶т釜鏁�
+            templateName = showResult ? "/static/small-wg-report-template.docx" : "/static/small-wg-detection-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>> totalItem = 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 = Math.max(cableTags.size(),1);
+            //澶勭悊鐢电紗閰嶇疆妫�娴嬮」
+            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());
+                }
+                cableTagItem.put(key,sampleProductExportDtos);
+            }
+            //澶勭悊闈炵數缂嗛厤缃娴嬮」
+            Map<String, List<SampleProductExportDto>> listMap = filterItems.stream()
+                    .filter(f -> StringUtils.isBlank(f.getCableTag()) && StringUtils.isNotBlank(f.getInspectionItem()))
+                    .collect(Collectors.groupingBy(s->s.getInspectionItem()+"&"));
+            //鍚堝苟妫�娴嬮」鍒楄〃
+            tempMap.putAll(cableTagItem);
+            tempMap.putAll(listMap);
+            sortSampleProduct(tempMap,totalItem);
+            int tagNum = Math.min(max,maxCableTag);
+            List<String> tagList = cableTags.isEmpty()?new ArrayList<>():cableTags.subList(0,tagNum);
+            handlerSampleItems(OrderType.WG.getValue(), totalItem, finalIndex, sampleList, tagNum, text, rows, rowRenderData, resultCh, tagList, true, showResult);
+
+            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(OrderType.WG.getValue(), cableTagEnclosureItem, finalIndex2, new ArrayList<>(), newCableTags.size(), newText, newRows, newRowRenderData, resultCh, newCableTags, true, showResult);
+                tableRenderData2.setRows(newRows);
+            tableRenderData2.setTableStyle(setTableStyle(newCableTags.size(), showResult));
+                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);
+            }
+
+            tableRenderData.setRows(rows);
+            tableRenderData.setTableStyle(setTableStyle(tagNum, showResult));
+            if (showResult && !resultCh.get().isEmpty()) {
+                resultCh.set("缁忔楠岋紝" + resultCh.get() + "鎵�妫�椤圭洰涓嶅悎鏍硷紝鍏朵綑鎵�妫�椤圭洰鍧囧悎鏍笺�傦紙鐩栫珷鏈夋晥锛�");
+            } else if (showResult) {
+                resultCh.set("鏈骇鍝佺鍚堢浉鍏虫爣鍑嗚姹傦紝缁忔楠屽悎鏍煎噯浜堝嚭鍘傦紙鐩栫珷鏈夋晥锛�");
+            }
+
+        }else{
+            templateName = showResult ? "/static/small-report-template.docx" : "/static/small-detection-template.docx";
+            // 杞垚Mpa杩涜鎺掑簭
+            Map<String, List<SampleProductExportDto>> sortedMap = sampleProductDto2s.stream()
+                    .filter(sampleProductDto2 -> StringUtils.isNotBlank(sampleProductDto2.getInspectionItem()))
+                    .collect(Collectors.groupingBy(SampleProductExportDto::getInspectionItem));
+//            // 鍒涘缓涓�涓� LinkedHashMap 鏉ヤ繚鎸佹彃鍏ラ『搴�
+            Map<String, List<SampleProductExportDto>> item = new LinkedHashMap<>();
+            sortSampleProduct(sortedMap,item);
+
+
+            AtomicInteger finalIndex = new AtomicInteger(1);
+            handlerSampleItems(OrderType.RAW.getValue(), item, finalIndex, sampleList, max, text, rows, rowRenderData, resultCh, null, true, showResult);
+            tableRenderData.setRows(rows);
+            tableRenderData.setTableStyle(setTableStyle(max, showResult));
+
+            if (showResult && !resultCh.get().equals("")) {
+                resultCh.set("缁忔楠岋紝" + resultCh.get() + "鎵�妫�椤圭洰涓嶅悎鏍硷紝鍏朵綑鎵�妫�椤圭洰鍧囧悎鏍笺��");
+            } else if (showResult) {
+                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("/", "") + (showResult ? "-J.docx" : "-C.docx");
+            Files.createDirectories(Paths.get(wordUrl));
+            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(String orderType, 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, boolean showResult) {
         item.forEach((s, sampleProductDtoInside) -> {
             // 娣诲姞妫�楠岄」
             SampleProductExportDto dto2 = new SampleProductExportDto();
@@ -1700,19 +1990,23 @@
                 // 澶勭悊闆嗗悎
                 Map<String, SampleProductExportDto> map = new LinkedHashMap<>();
                 for (SampleProductExportDto productDto2 : sampleProductDtoInside) {
-                    String productName = productDto2.getInspectionItemClass() + productDto2.getInspectionItem();
+                    String productName = productDto2.getInspectionItemClass() + productDto2.getInspectionItem() + productDto2.getCableTag();
                     if (map.containsKey(productName)) {
                         // 濡傛灉鍚嶇О宸茬粡瀛樺湪锛屾坊鍔� lastValue 鍊煎埌 lastValueList 鍒楄〃
-                        map.get(productName)
-                                .getLastValueList()
-                                .add(productDto2.getLastValue());
+                        if(CollectionUtil.isEmpty(map.get(productName).getLastValueList()) || StringUtils.equals(OrderType.RAW.getValue(),orderType)){
+                            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()) || StringUtils.equals(OrderType.RAW.getValue(),orderType)){
+                            productDto2.setLastValueList(new ArrayList<>()); // 妫�楠屽唴瀹�
+                            productDto2.getLastValueList().add(productDto2.getLastValue());
+                        }
                         productDto2.setInsResultList(new ArrayList<>()); // 缁撴灉
                         productDto2.getInsResultList().add(productDto2.getInsResult());
 
@@ -1741,19 +2035,23 @@
                 // 澶勭悊闆嗗悎
                 Map<String, SampleProductExportDto> map = new LinkedHashMap<>();
                 for (SampleProductExportDto productDto2 : sampleProductDtoInside) {
-                    String productName = productDto2.getInspectionItemClass() + productDto2.getInspectionItem() + productDto2.getInspectionItemSubclass();
+                    String productName = productDto2.getInspectionItemClass() + productDto2.getInspectionItem() + productDto2.getInspectionItemSubclass() + productDto2.getCableTag();
                     if (map.containsKey(productName)) {
                         // 濡傛灉鍚嶇О宸茬粡瀛樺湪锛屾坊鍔� lastValue 鍊煎埌 lastValueList 鍒楄〃
-                        map.get(productName)
-                                .getLastValueList()
-                                .add(productDto2.getLastValue());
+                        if(CollectionUtil.isEmpty(map.get(productName).getLastValueList()) || StringUtils.equals(OrderType.RAW.getValue(),orderType)){
+                            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()) || StringUtils.equals(OrderType.RAW.getValue(),orderType)){
+                            productDto2.setLastValueList(new ArrayList<>()); // 妫�楠屽唴瀹�
+                            productDto2.getLastValueList().add(productDto2.getLastValue());
+                        }
                         productDto2.setInsResultList(new ArrayList<>()); // 缁撴灉
                         productDto2.getInsResultList().add(productDto2.getInsResult());
 
@@ -1771,8 +2069,9 @@
         });
 
         // 娣诲姞灏忔姤鍛婅〃澶�
-        text = addSmallHead(text, max, rows);
-
+        if(hasAddHead){
+            text = addSmallHead(text, max, rows, cableTagList, showResult);
+        }
 
         // 涓棿妫�娴嬪�兼坊鍔�
         for (int i = 0; i < sampleList.size(); i++) {
@@ -1789,7 +2088,9 @@
 
             // 妫�楠岄」鐩�
             TextRenderData middleRenderData2 = new TextRenderData();
-            middleRenderData2.setText(sample.getInspectionName());
+            String[] split = sample.getInspectionName().split("&");
+            String itemName = split.length>0?split[0]:sample.getInspectionName();
+            middleRenderData2.setText(itemName+"鈭�"+itemName+i+"_"+finalIndex);
             Style middleStyle2 = new Style();
             middleStyle2.setFontFamily("瀹嬩綋");
             middleStyle2.setColor("000000");
@@ -1819,21 +2120,21 @@
             if (CollectionUtils.isNotEmpty(sample.getLastValueList())
                     && sample.getLastValueList().size() == max) {
                 // 鍒ゆ柇鏄惁鏄瑙�, 澶栬鍏ㄩ儴鍚堟牸鐨勮瘽闇�瑕佸悎骞�
-                if (sample.getInspectionItem().contains("澶栬")) {
+                if (showResult && sample.getInspectionItem().contains("澶栬")) {
                     // 鍒ゅ畾缁撴灉
                     boolean falg = false;
                     if (CollectionUtils.isNotEmpty(sample.getLastValueList())) {
                         // 鍒ゆ柇鏄惁鏈変竴涓敊璇�
-                        if (sample.getInsResultList().stream().anyMatch(s -> s.equals(2))) {
+                        if (sample.getInsResultList().stream().anyMatch(s -> Objects.equals(s, 2))) {
                             falg = true;
                         } else {
-                            boolean error = sample.getInsResultList().stream().anyMatch(s -> s.equals(0));
+                            boolean error = sample.getInsResultList().stream().anyMatch(s -> Objects.equals(s, 0));
                             if (!error) {
                                 falg = true;
                             }
                         }
                     } else {
-                        if (!sample.getInsResult().equals(2)) {
+                        if (!Objects.equals(sample.getInsResult(), 2)) {
                             falg = true;
                         }
                     }
@@ -1876,7 +2177,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");
@@ -1888,7 +2189,7 @@
 
             // 鍒ゅ畾缁撴灉
             String result = "";
-            if (sample.getInsResult() != null) {
+            if (showResult && sample.getInsResult() != null) {
                 switch (sample.getInsResult()) {
                     case 1:
                         result = "鈭�";
@@ -1901,20 +2202,20 @@
                         break;
                 }
             }
-            if (CollectionUtils.isNotEmpty(sample.getLastValueList())) {
+            if (showResult && CollectionUtils.isNotEmpty(sample.getLastValueList())) {
                 // 鍒ゆ柇鏄惁鏈変竴涓敊璇�
-                if (sample.getInsResultList().stream().anyMatch(s -> s.equals(3))) {
+                if (sample.getInsResultList().stream().anyMatch(s -> Objects.equals(s, 3))) {
                     result = "-";
                 } else {
-                    boolean error = sample.getInsResultList().stream().anyMatch(s -> s.equals(0));
+                    boolean error = sample.getInsResultList().stream().anyMatch(s -> Objects.equals(s, 0));
                     if (error) {
                         List<String> collect = new ArrayList<>();
                         int index = 1;
                         for (Integer count : sample.getInsResultList()) {
                             String type;
-                            if (count.equals(0)) {
+                            if (Objects.equals(count, 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("")) {
@@ -1936,6 +2237,7 @@
                 }
             }
 
+            if (showResult) {
             TextRenderData middleRenderData7 = new TextRenderData();
             middleRenderData7.setText(result);
             Style middleStyle7 = new Style();
@@ -1943,6 +2245,7 @@
             middleStyle7.setColor("000000");
             middleRenderData7.setStyle(middleStyle7);
             text.add(middleRenderData7);
+            }
 
             TextRenderData[] text2 = text.toArray(new TextRenderData[0]);
             rowRenderData = Rows.of(text2).center().rowAtleastHeight(1).create();
@@ -1954,95 +2257,16 @@
             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);
-
-        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);
-            inputStream.close();
-        } 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, boolean showResult) {
         RowRenderData rowRenderData;
 //        // 澶�
         TextRenderData headRenderData1 = new TextRenderData();
@@ -2079,13 +2303,14 @@
 
         for (int i = 0; i < max; i++) {
             TextRenderData headRenderData6 = new TextRenderData();
-            headRenderData6.setText("妫�楠岀粨鏋溾垜6");
+            headRenderData6.setText(showResult ? "妫�楠岀粨鏋溾垜6" : "妫�娴嬫暟鎹垜6");
             Style headStyle6 = new Style();
             headStyle6.setFontFamily("瀹嬩綋");
             headStyle6.setColor("000000");
             headRenderData6.setStyle(headStyle6);
             text.add(headRenderData6);
         }
+        if (showResult) {
         TextRenderData headRenderData7 = new TextRenderData();
         headRenderData7.setText("鍗曢」鍒ゆ柇");
         Style headStyle7 = new Style();
@@ -2093,6 +2318,7 @@
         headStyle7.setColor("000000");
         headRenderData7.setStyle(headStyle7);
         text.add(headRenderData7);
+        }
 
         TextRenderData[] text3 = text.toArray(new TextRenderData[0]);
         rowRenderData = Rows.of(text3).center().rowAtleastHeight(1).create();
@@ -2100,7 +2326,7 @@
         text = new ArrayList<>();
 
         // 绗簩琛�(鍙兘娌℃湁)
-        if (max > 1) {
+        if (max > 1 && CollectionUtil.isEmpty(cableTagList)) {
             TextRenderData tagRenderData1 = new TextRenderData();
             tagRenderData1.setText("");
             Style tagStyle1 = new Style();
@@ -2142,6 +2368,7 @@
                 tagRenderData6.setStyle(tagStyle6);
                 text.add(tagRenderData6);
             }
+            if (showResult) {
             TextRenderData tagRenderData7 = new TextRenderData();
             tagRenderData7.setText("");
             Style tagStyle7 = new Style();
@@ -2149,6 +2376,7 @@
             tagStyle7.setColor("000000");
             tagRenderData7.setStyle(tagStyle7);
             text.add(tagRenderData7);
+            }
 
             TextRenderData[] text4 = text.toArray(new TextRenderData[0]);
             rowRenderData = Rows.of(text4).center().rowAtleastHeight(1).create();
@@ -2157,7 +2385,64 @@
 
 
         }
+        //濡傛灉鏈夌數缂嗛鑹诧紝鐢熸垚棰滆壊鏍囪瘑琛�
+        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);
+            }
+            if (showResult) {
+            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;
     }
 
@@ -2169,12 +2454,14 @@
      * @param insOrder
      * @param
      */
-    private void addBitReport(Integer orderId, InsOrder insOrder) {
+    private void addBitReport(Integer orderId, InsOrder insOrder, Integer reportType) {
         //samples鏄笉鍖呮嫭甯︽湁"/"鐨勬牱鍝�
         List<SampleProductDto> samples = insSampleMapper.selectSampleProductListByOrderId(orderId);
         InsReport insReport = new InsReport();
         insReport.setCode(insOrder.getEntrustCode());
         insReport.setInsOrderId(orderId);
+        insReport.setReportType(reportType);
+        boolean showResult = Objects.equals(reportType, INSPECTION_REPORT);
         List<Map<String, Object>> tables = new ArrayList<>();
         Set<String> standardMethod = new HashSet<>();
         Set<String> deviceSet = new HashSet<>();
@@ -2185,7 +2472,7 @@
         List<String> resultChList = new ArrayList<>();
         List<String> resultEnList = new ArrayList<>();
         // 鍒ゆ柇鏄惁鏄彧鏈変竴涓牱鍝�
-        boolean isOneSample = samples.size() == 1 ? true : false;
+        boolean isOneSample = samples.size() == 1;
         /*鍩虹鎶ュ憡(鏍规嵁缁樺埗鐨勫師濮嬭褰曟ā鐗堝舰鎴�)*/
         samples.forEach(a -> {
             models.add(a.getModel());
@@ -2204,6 +2491,11 @@
                         }
                     }
                 }
+            }
+            // 鏂扮増妫�娴嬫姤鍛婄洿鎺ヤ娇鐢ㄥ浐瀹氬洓鍒楃粨鏋滆锛屼笉鍐嶆瀯閫犳棫鐗堝彲鍙樺垪 TableRenderData銆�
+            // 妫�楠屾姤鍛婁粛娌跨敤涓嬫柟鍘熸湁鐨勫ぇ琛ㄦ牸閫昏緫銆�
+            if (!showResult) {
+                return;
             }
             // 鏀舵牱鏃ユ湡
             List<RowRenderData> rows = new ArrayList<>();
@@ -2264,15 +2556,15 @@
             }
 
             // 琛ㄥご娣诲姞
-            addHead(a, text, rowRenderData, rows, max, cableTags);
+            addHead(a, text, rowRenderData, rows, max, cableTags, showResult);
             text = new ArrayList<>();
 
             // 娣诲姞妫�娴嬪��
-            productSize.set(addTestValue(a, text, rowRenderData, rows, max, resultChList, resultEnList, insSamples, cableTags, isOneSample));
+            productSize.set(addTestValue(a, text, rowRenderData, rows, max, resultChList, resultEnList, insSamples, cableTags, isOneSample, showResult));
             text = new ArrayList<>();
 
             // 缁撳熬娣诲姞
-            addEnding(text, rowRenderData, rows, max);
+            addEnding(text, rowRenderData, rows, max, showResult);
             text = new ArrayList<>();
 
             List<TableRenderData> tables1 = new ArrayList<>();
@@ -2303,26 +2595,27 @@
                     newTableRenderData.setRows(new ArrayList<>(firstTwoRows));
                     //璁剧疆鏍峰紡
                     TableStyle tableStyle = new TableStyle();
-                    for (int i = 1; i <= max; i++) {
-                        // 鏍规嵁鍑忓帇閭g粨鏋滀釜鏁颁慨鏀归暱搴�
-                        switch (i) {
-                            case 1:
-                                tableStyle.setColWidths(new int[]{650, 2000, 2000, 850, 2200, 2100, 1200});
-                                break;
-                            case 2:
-                                tableStyle.setColWidths(new int[]{650, 1400, 1400, 850, 2100, 1200, 1200, 1200});
-                                break;
-                            case 3:
-                                tableStyle.setColWidths(new int[]{650, 1400, 1400, 850, 1500, 1000, 1000, 1000, 1200});
-                                break;
-                            case 4:
-                                tableStyle.setColWidths(new int[]{650, 1200, 1200, 850, 1400, 850, 850, 850, 850, 1200});
-                                break;
-                            case 5:
-                                tableStyle.setColWidths(new int[]{650, 1100, 1100, 850, 1350, 750, 750, 750, 750, 750, 1200});
-                                break;
-                        }
-                    }
+//                    for (int i = 1; i <= max; i++) {
+//                    }
+                    // 鏍规嵁妫�楠岀粨鏋滀釜鏁颁慨鏀归暱搴�
+                    tableStyle.setColWidths(calcTableColWidths(max, showResult));
+//                    switch (max) {
+//                        case 1:
+//                            tableStyle.setColWidths(new int[]{650, 2000, 2000, 850, 2200, 2100, 1200});
+//                            break;
+//                        case 2:
+//                            tableStyle.setColWidths(new int[]{650, 1400, 1400, 850, 2100, 1200, 1200, 1200});
+//                            break;
+//                        case 3:
+//                            tableStyle.setColWidths(new int[]{650, 1400, 1400, 850, 1500, 1000, 1000, 1000, 1200});
+//                            break;
+//                        case 4:
+//                            tableStyle.setColWidths(new int[]{650, 1200, 1200, 850, 1400, 850, 850, 850, 850, 1200});
+//                            break;
+//                        case 5:
+//                            tableStyle.setColWidths(new int[]{650, 1100, 1100, 850, 1350, 750, 750, 750, 750, 750, 1200});
+//                            break;
+//                    }
                     tableStyle.setWidth("10000");
                     tableStyle.setAlign(TableRowAlign.CENTER);
                     BorderStyle borderStyle = new BorderStyle();
@@ -2345,42 +2638,43 @@
                 }
                 tableRenderData.getRows().add(row);
             }
-            if (!tableRenderData.getRows().isEmpty() && tableRenderData.getRows().size() != 3) {
+            TableStyle tableStyle = new TableStyle();
+            if (tableRenderData.getRows().size() != 3) {
                 //璁剧疆鏍峰紡
-                TableStyle tableStyle = new TableStyle();
-                for (int i = 1; i <= max; i++) {
-                    // 鏍规嵁鍑忓帇閭g粨鏋滀釜鏁颁慨鏀归暱搴�
-                    switch (i) {
-                        case 1:
-                            tableStyle.setColWidths(new int[]{650, 2000, 2000, 850, 2200, 2100, 1200});
-                            break;
-                        case 2:
-                            tableStyle.setColWidths(new int[]{650, 1400, 1400, 850, 2100, 1200, 1200, 1200});
-                            break;
-                        case 3:
-                            tableStyle.setColWidths(new int[]{650, 1400, 1400, 850, 1500, 1000, 1000, 1000, 1200});
-                            break;
-                        case 4:
-                            tableStyle.setColWidths(new int[]{650, 1200, 1200, 850, 1400, 850, 850, 850, 850, 1200});
-                            break;
-                        case 5:
-                            tableStyle.setColWidths(new int[]{650, 1100, 1100, 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.THICK);
-                borderStyle.setSize(14);
-                tableStyle.setLeftBorder(borderStyle);
-                tableStyle.setTopBorder(borderStyle);
-                tableStyle.setRightBorder(borderStyle);
-                tableStyle.setBottomBorder(borderStyle);
-                tableRenderData.setTableStyle(tableStyle);
-                tables1.add(tableRenderData);
+//                for (int i = 1; i <= max; i++) {
+//                }
+                // 鏍规嵁妫�楠岀粨鏋滀釜鏁颁慨鏀归暱搴�
+                tableStyle.setColWidths(calcTableColWidths(max, showResult));
+//                switch (max) {
+//                    case 1:
+//                        tableStyle.setColWidths(new int[]{650, 2000, 2000, 850, 2200, 2100, 1200});
+//                        break;
+//                    case 2:
+//                        tableStyle.setColWidths(new int[]{650, 1400, 1400, 850, 2100, 1200, 1200, 1200});
+//                        break;
+//                    case 3:
+//                        tableStyle.setColWidths(new int[]{650, 1400, 1400, 850, 1500, 1000, 1000, 1000, 1200});
+//                        break;
+//                    case 4:
+//                        tableStyle.setColWidths(new int[]{650, 1200, 1200, 850, 1400, 850, 850, 850, 850, 1200});
+//                        break;
+//                    case 5:
+//                        tableStyle.setColWidths(new int[]{650, 1100, 1100, 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.THICK);
+            borderStyle.setSize(14);
+            tableStyle.setLeftBorder(borderStyle);
+            tableStyle.setTopBorder(borderStyle);
+            tableStyle.setRightBorder(borderStyle);
+            tableStyle.setBottomBorder(borderStyle);
+            tableRenderData.setTableStyle(tableStyle);
+            tables1.add(tableRenderData);
             tables1.forEach(table -> {
                 Map<String, Object> tableMap = new HashMap<>();
                 tableMap.put("table", table);
@@ -2394,7 +2688,9 @@
         for (String s : standardMethod) {
             standardMethod2.append("銆�").append(s);
         }
-        standardMethod2.replace(0, 1, "");
+        if (standardMethod2.length() > 0) {
+            standardMethod2.deleteCharAt(0);
+        }
         tables.forEach(table -> {
             table.put("tableSize", tables.size() + 1);
         });
@@ -2438,7 +2734,7 @@
         Custom custom = customMapper.selectById(insOrder.getCompanyId());
 
         // 鏌ヨ鍒ゆ柇鏄惁鏈変笉鍒ゅ畾椤圭洰,鍜屽叏閮芥槸鍒ゅ畾椤�
-        int judgeType = insProductMapper.selectNoJudge(insOrder.getId());
+        int judgeType = showResult ? insProductMapper.selectNoJudge(insOrder.getId()) : 0;
         String resultCh = "";
         String resultEn = "";
         for (String reference : resultChList) {
@@ -2498,10 +2794,13 @@
         // 鎶芥牱鏃ユ湡
         // 鎴愬搧鏄娊鏍锋椂闂�
         LocalDateTime sendTime = insOrder.getSendTime();
-        if (insOrder.getTypeSource() != null && insOrder.getTypeSource().equals(1)) {
+        IfsInventoryQuantity reportInventory = null;
+        if (insOrder.getIfsInventoryId() != null) {
+            reportInventory = ifsInventoryQuantityMapper.selectById(insOrder.getIfsInventoryId());
+        }
+        if (insOrder.getTypeSource() != null && insOrder.getTypeSource().equals(1) && reportInventory != null) {
             // 鍘熸潗鏂欐敹鏍锋棩鏈熸槸鎶ユ鏃ユ湡
-            IfsInventoryQuantity ifsInventoryQuantity = ifsInventoryQuantityMapper.selectById(insOrder.getIfsInventoryId());
-            sendTime = ifsInventoryQuantity.getDeclareDate();
+            sendTime = reportInventory.getDeclareDate();
         }
 
         // 妫�楠屾椂闂�  鎶芥牱鏃堕棿-鎻愪氦鏃堕棿
@@ -2530,12 +2829,60 @@
         List<Map<String, String>> finalDeviceList = deviceList;
         String finalModelStr = modelStr;
 
-        InputStream inputStream = this.getClass().getResourceAsStream("/static/report-template.docx");
+        List<Map<String, String>> detectionResultRows = buildDetectionResultRows(samples);
+        String productName = defaultReportText(insOrder.getSampleView(), insOrder.getSample());
+        String customerName = defaultReportText(custom == null ? null : custom.getCompany(), insOrder.getCompany());
+        String detectionCategory = defaultReportText(finalOrderType, "濮旀墭妫�娴�");
+        String sampleCode = samples.stream()
+                .map(SampleProductDto::getSampleCode)
+                .filter(StringUtils::isNotBlank)
+                .distinct()
+                .collect(Collectors.joining("銆�"));
+        String productAndModel = productName;
+        if (StringUtils.isNotBlank(finalModelStr) && !Objects.equals(productName, finalModelStr)) {
+            productAndModel = productName + " " + finalModelStr;
+        }
+        String standardMethodText = "null".equals(standardMethod2.toString()) ? "" : standardMethod2.toString();
+        String productionDate = "/";
+        String batchNo = "/";
+        if (reportInventory != null) {
+            if (reportInventory.getProductDate() != null) {
+                productionDate = reportInventory.getProductDate().format(DateTimeFormatter.ofPattern("yyyy骞碝M鏈坉d鏃�"));
+            }
+            batchNo = defaultReportText(reportInventory.getUpdateBatchNo(), reportInventory.getLotBatchNo());
+        }
+        boolean containsOrganicChlorine = detectionResultRows.stream()
+                .map(row -> row.get("itemName"))
+                .filter(Objects::nonNull)
+                .anyMatch(name -> name.contains("鏈夋満姘�"));
+        String resultRemark = containsOrganicChlorine
+                ? "寰簱浠戞硶锛屾湁鏈烘隘鍚噺灏忎簬0.005%鏃讹紝浠ユ湭妫�鍑烘姤鍑恒��"
+                : defaultReportText(insOrder.getRemark(), "/");
+
+        // 妫�娴嬫姤鍛婂拰妫�楠屾姤鍛婄粺涓�浣跨敤鏂扮増鎶ュ憡妯℃澘
+        String templateName = "/static/detection-report-template-v2.docx";
+        InputStream inputStream = this.getClass().getResourceAsStream(templateName);
+        if (inputStream == null) {
+            throw new RuntimeException("鎵句笉鍒版姤鍛婃ā鏉�: " + templateName);
+        }
         Configure configure = Configure.builder()
                 .bind("deviceList", new HackLoopTableRenderPolicy())
+                .bind("r", new HackLoopTableRenderPolicy(true))
+                .setValidErrorHandler(new PreserveReportPicturePlaceholderHandler())
                 .useSpringEL(true)
                 .build();
 
+        String finalProductAndModel = productAndModel;
+        String finalProductName = productName;
+        String finalCustomerName = customerName;
+        String finalDetectionCategory = detectionCategory;
+        String finalSampleCode = defaultReportText(sampleCode, "/");
+        String finalStandardMethodText = defaultReportText(standardMethodText, "/");
+        String finalProductionDate = productionDate;
+        String finalBatchNo = batchNo;
+        String finalResultRemark = resultRemark;
+        String equipmentText = buildEquipmentText(finalDeviceList);
+        String issueDate = now.format(DateTimeFormatter.ofPattern("yyyy骞碝M鏈坉d鏃�"));
         XWPFTemplate template = XWPFTemplate.compile(inputStream, configure).render(
                 new HashMap<String, Object>() {{
                     put("order", insOrder);
@@ -2545,7 +2892,7 @@
                     put("sampleSize", insOrder.getTestQuantity());
                     put("tables", tables);
                     put("tableSize", tables.size() + 1);
-                    put("standardMethod", (standardMethod2.toString().equals("null") ? "" : standardMethod2));
+                    put("standardMethod", finalStandardMethodText);
                     put("deviceList", finalDeviceList);
                     put("twoCode", null);
                     put("models", finalModelStr);
@@ -2569,12 +2916,38 @@
                     put("resultCh", finalResultCh);
                     put("resultEn", finalResultEn);
                     put("sampleStatus", sampleStatus);
+                    // 鏂扮増妫�娴嬫姤鍛婃ā鏉匡紙鍙傜収銆婃湁鏈烘隘妫�娴嬫姤鍛娿�嬶級浣跨敤鐨勬墎骞冲瓧娈点��
+                    put("no", insReport.getCode());
+                    put("cover", finalProductAndModel);
+                    put("product", finalProductName);
+                    put("model", defaultReportText(finalModelStr, "/"));
+                    put("customer", finalCustomerName);
+                    put("category", finalDetectionCategory);
+                    put("date", issueDate);
+                    put("maker", defaultReportText(insOrder.getProduction(), "/"));
+                    put("env", finalEnvironment);
+                    put("qty", defaultReportText(insOrder.getTestQuantity(), "/"));
+                    put("receive", finalSendTime.format(DateTimeFormatter.ofPattern("yyyy骞碝M鏈坉d鏃�")));
+                    put("sampleNo", finalSampleCode);
+                    put("appearance", defaultReportText(sampleStatus, "/"));
+                    put("sender", defaultReportText(insOrder.getPrepareUser(), "/"));
+                    put("produced", finalProductionDate);
+                    put("batch", finalBatchNo);
+                    put("phone", defaultReportText(insOrder.getPhone(), "/"));
+                    put("testDate", insTime);
+                    put("entrustNo", defaultReportText(insOrder.getEntrustCode(), "/"));
+                    put("sampling", "/");
+                    put("standard", finalStandardMethodText);
+                    put("equipment", equipmentText);
+                    put("conclusion", "鏍峰搧鎸夊鎵樻柟瑕佹眰杩涜妫�娴嬶紝鏁版嵁瑙佹娴嬬粨鏋溿��");
+                    put("remark", "鏈姤鍛婃娴嬬粨鏋滀粎瀵瑰綋鏃ユ墍鎺ユ敹鏍峰搧璐熻矗銆�");
+                    put("r", detectionResultRows);
+                    put("resultNote", finalResultRemark);
                 }});
         try {
-            // 淇敼鎹㈣鍜屽悎骞堕棶棰�
-            updaeMerge(template.getXWPFDocument(), false);
-            String name = insReport.getCode().replace("/", "") + ".docx";
-            template.writeAndClose(Files.newOutputStream(Paths.get(wordUrl + "/" + name)));
+            String name = insReport.getCode().replace("/", "") + (showResult ? ".docx" : "-C.docx");
+            Files.createDirectories(Paths.get(wordUrl));
+            template.writeAndClose(Files.newOutputStream(Paths.get(wordUrl, name)));
             insReport.setUrl("/word/" + name);
             insReport.setWriteUserId(SecurityUtils.getUserId().intValue());//鎻愪氦浜�
             insReport.setWriteTime(LocalDateTime.now());//鎻愪氦鏃堕棿
@@ -2586,6 +2959,138 @@
         } catch (IOException e) {
             throw new RuntimeException(e);
         }
+    }
+
+    /**
+     * 鏂扮増妫�娴嬫姤鍛婄殑缁撴灉琛ㄥ浐瀹氫负鍥涘垪锛氬簭鍙枫�佹娴嬮」鐩�佸崟浣嶃�佹娴嬬粨鏋溿��
+     */
+    private static List<Map<String, String>> buildDetectionResultRows(List<SampleProductDto> samples) {
+        List<Map<String, String>> rows = new ArrayList<>();
+        if (CollectionUtils.isEmpty(samples)) {
+            return rows;
+        }
+
+        boolean multipleSamples = samples.size() > 1;
+        int sequence = 1;
+        for (SampleProductDto sample : samples) {
+            if (CollectionUtils.isEmpty(sample.getInsProduct())) {
+                continue;
+            }
+            for (InsProduct product : sample.getInsProduct()) {
+                // 缁戝畾椤圭洰浠呭弬涓庤绠楋紝涓嶅簲鍑虹幇鍦ㄦ姤鍛婁腑銆�
+                if (product == null || Objects.equals(product.getIsBinding(), 1)) {
+                    continue;
+                }
+
+                String itemName = defaultReportText(
+                        product.getInspectionItemSubclass(),
+                        defaultReportText(product.getInspectionItem(), product.getInspectionItemClass()));
+                if (multipleSamples && StringUtils.isNotBlank(sample.getSampleCode())) {
+                    itemName = sample.getSampleCode() + " - " + itemName;
+                }
+
+                Map<String, String> row = new LinkedHashMap<>();
+                row.put("seq", String.valueOf(sequence++));
+                row.put("itemName", itemName);
+                row.put("unit", defaultReportText(product.getUnit(), "/"));
+                row.put("result", defaultReportText(product.getLastValue(), "/"));
+                rows.add(row);
+            }
+        }
+        return rows;
+    }
+
+    private static String buildEquipmentText(List<Map<String, String>> deviceList) {
+        if (CollectionUtils.isEmpty(deviceList)) {
+            return "/";
+        }
+        Set<String> lines = new LinkedHashSet<>();
+        int sequence = 1;
+        for (Map<String, String> device : deviceList) {
+            String name = getMapText(device, "deviceName", "device_name");
+            String managementNumber = getMapText(device, "managementNumber", "management_number");
+            String line = sequence++ + ". " + defaultReportText(name, "/");
+            if (StringUtils.isNotBlank(managementNumber)) {
+                line += "锛�" + managementNumber;
+            }
+            lines.add(line);
+        }
+        return String.join("\n", lines);
+    }
+
+    private static String getMapText(Map<String, String> map, String... keys) {
+        if (map == null) {
+            return null;
+        }
+        for (String key : keys) {
+            String value = map.get(key);
+            if (StringUtils.isNotBlank(value)) {
+                return value;
+            }
+            for (Map.Entry<String, String> entry : map.entrySet()) {
+                if (entry.getKey() != null && entry.getKey().equalsIgnoreCase(key)
+                        && StringUtils.isNotBlank(entry.getValue())) {
+                    return entry.getValue();
+                }
+            }
+        }
+        return null;
+    }
+
+    private static String defaultReportText(String value, String fallback) {
+        if (StringUtils.isNotBlank(value)) {
+            return value;
+        }
+        return StringUtils.isNotBlank(fallback) ? fallback : "/";
+    }
+
+    /**
+     * 璁$畻琛ㄦ牸鍒楀搴�
+     * @param max 鏈�澶ф楠屼釜鏁�
+     * @return
+     */
+    private static int[] calcTableColWidths(int max, boolean showResult){
+        if (!showResult) {
+            switch (max) {
+                case 1: return new int[]{650, 2200, 2200, 850, 2300, 1800};
+                case 2: return new int[]{650, 1600, 1600, 850, 1900, 1700, 1700};
+                case 3: return new int[]{650, 1400, 1400, 850, 1600, 1375, 1375, 1375};
+                case 4: return new int[]{650, 1250, 1250, 850, 1450, 1140, 1140, 1140, 1140};
+                case 5: return new int[]{650, 1150, 1150, 850, 1300, 980, 980, 980, 980, 980};
+                default: return new int[0];
+            }
+        }
+        int[] colWidths = null;
+        switch (max) {
+            case 1:
+                colWidths = new int[]{650, 2000, 2000, 850, 2200, 2100, 1200};
+                break;
+            case 2:
+                colWidths = new int[]{650, 1400, 1400, 850, 2100, 1200, 1200, 1200};
+                break;
+            case 3:
+                colWidths = new int[]{650, 1400, 1400, 850, 1500, 1000, 1000, 1000, 1200};
+                break;
+            case 4:
+                colWidths = new int[]{650, 1200, 1200, 850, 1400, 850, 850, 850, 850, 1200};
+                break;
+            case 5:
+                colWidths = new int[]{650, 1100, 1100, 850, 1350, 750, 750, 750, 750, 750, 1200};
+                break;
+        }
+        if(ObjectUtils.isNull(colWidths)){
+            List<Integer> defaultColWidths = new ArrayList<>(Arrays.asList(650, 1100, 1100, 850, 1350));
+            int totalWidth = 3000;//鎬诲搴�
+            int byOneWidth = totalWidth/max;//姣忎竴涓殑瀹藉害
+            int realWidth = 0;//瀹為檯瀹藉害
+            for (int i = 0; i < max; i++) {
+                realWidth+=byOneWidth;
+                defaultColWidths.add(byOneWidth);
+            }
+            defaultColWidths.add(1200+(totalWidth-realWidth));
+            return defaultColWidths.stream().mapToInt(Integer::intValue).toArray();
+        }
+        return colWidths;
     }
 
     /**
@@ -2603,9 +3108,9 @@
         // 鑾峰彇妫�娴嬪唴瀹瑰垽鏂槸鍚﹁秴鍑�
         if (StringUtils.isNotBlank(dataText) && dataText.contains("@")) {
             double number = 1;
-            double chinaLength = 0;
-            double englishLength = 0;
-            double valueLength = 0;
+            double chinaLength = 14;
+            double englishLength = 28;
+            double valueLength = 6;
             // 鏍规嵁绾胯姱涓暟鍒ゆ柇璺濈
             switch (max) {
                 case 1:
@@ -2828,7 +3333,7 @@
      * @param max
      * @param cableTags 绾胯姱棰滆壊
      */
-    private static void addHead(SampleProductDto sample, List<TextRenderData> text, RowRenderData rowRenderData, List<RowRenderData> rows, int max, List<String> cableTags) {
+    private static void addHead(SampleProductDto sample, List<TextRenderData> text, RowRenderData rowRenderData, List<RowRenderData> rows, int max, List<String> cableTags, boolean showResult) {
         // 绗竴琛�
         TextRenderData firstRenderData1 = new TextRenderData();
         firstRenderData1.setText("鏍峰搧缂栧彿@Sample No.鈭�1");
@@ -2905,6 +3410,11 @@
             }
 
         }
+        // 妫�娴嬫姤鍛婁笉灞曠ず鈥滅粨璁衡�濆垪锛岄琛屼篃瑕佸悓姝ュ噺灏戜竴涓崟鍏冩牸锛�
+        // 鍚﹀垯棣栬涓� max + 6 鍒椼�佸叾浣欒涓� max + 5 鍒楋紝poi-tl 鏃犳硶娓叉煋琛ㄦ牸銆�
+        if (!showResult && !text.isEmpty()) {
+            text.remove(text.size() - 1);
+        }
         TextRenderData[] text2 = text.toArray(new TextRenderData[0]);
         rowRenderData = Rows.of(text2).center().rowAtleastHeight(1).create();
         rows.add(rowRenderData);
@@ -2953,13 +3463,14 @@
 
         for (int i = 0; i < max; i++) {
             TextRenderData headRenderData6 = new TextRenderData();
-            headRenderData6.setText("妫�楠岀粨鏋淍Test result鈭�6");
+            headRenderData6.setText(showResult ? "妫�楠岀粨鏋淍Test result鈭�6" : "妫�娴嬫暟鎹瓳Test data鈭�6");
             Style headStyle6 = new Style();
             headStyle6.setFontFamily("瀹嬩綋");
             headStyle6.setColor("000000");
             headRenderData6.setStyle(headStyle6);
             text.add(headRenderData6);
         }
+        if (showResult) {
         TextRenderData headRenderData7 = new TextRenderData();
         headRenderData7.setText("缁撹@Conclusion");
         Style headStyle7 = new Style();
@@ -2967,6 +3478,7 @@
         headStyle7.setColor("000000");
         headRenderData7.setStyle(headStyle7);
         text.add(headRenderData7);
+        }
 
         TextRenderData[] text3 = text.toArray(new TextRenderData[0]);
         rowRenderData = Rows.of(text3).center().rowAtleastHeight(1).create();
@@ -3024,6 +3536,7 @@
                 cableRenderData6.setStyle(cableStyle6);
                 text.add(cableRenderData6);
             }
+            if (showResult) {
             TextRenderData cableRenderData7 = new TextRenderData();
             cableRenderData7.setText("-");
             Style cableStyle7 = new Style();
@@ -3031,6 +3544,7 @@
             cableStyle7.setColor("000000");
             cableRenderData7.setStyle(cableStyle7);
             text.add(cableRenderData7);
+            }
 
             TextRenderData[] text4 = text.toArray(new TextRenderData[0]);
             rowRenderData = Rows.of(text4).center().rowAtleastHeight(1).create();
@@ -3063,7 +3577,7 @@
                              List<String> resultChList,
                              List<String> resultEhList,
                              InsSample insSamples, List<String> cableTags,
-                             boolean isOneSample) {
+                             boolean isOneSample, boolean showResult) {
         // 妫�楠岄」鎬绘暟
         AtomicInteger productSize = new AtomicInteger(1);
         // 涓嶅悎鏍间俊鎭�
@@ -3471,7 +3985,6 @@
         // 妫�楠岄」鍒嗙被      妫�楠岄」  妫�楠屽瓙椤�
         Map<String, LinkedHashMap<String, List<String>>> errorClassItemMapCn = new LinkedHashMap<>();
         Map<String, LinkedHashMap<String, List<String>>> errorClassItemMapEn = new LinkedHashMap<>();
-
         // 涓棿妫�娴嬪�兼坊鍔�
         for (int i = 0; i < sampleList.size(); i++) {
             SampleProductExportDto sample = sampleList.get(i);
@@ -3552,7 +4065,9 @@
 
             // 鍒ゆ柇鏄惁鏈夌數缂嗘爣璇唌ap
             if (CollectionUtils.isNotEmpty(sample.getCableTagValueMap())) {
-                sample.setLastValueList(new ArrayList<>(sample.getCableTagValueMap().values()));
+                TreeMap<String, String> cableTagValues = new TreeMap<>(Comparator.comparingInt(cableTags::indexOf));
+                cableTagValues.putAll(sample.getCableTagValueMap());
+                sample.setLastValueList(new ArrayList<>(cableTagValues.values()));
             }
             if (CollectionUtils.isNotEmpty(sample.getCableTagResultMap())) {
                 sample.setInsResultList(new ArrayList<>(sample.getCableTagResultMap().values()));
@@ -3586,6 +4101,7 @@
                 }
             }
             // 鍒ゅ畾缁撴灉
+            if (showResult) {
             String result = "";
             if (sample.getInsResult() != null) {
                 switch (sample.getInsResult()) {
@@ -3602,16 +4118,16 @@
             }
             if (CollectionUtils.isNotEmpty(sample.getLastValueList())) {
                 // 鍒ゆ柇鏄惁鏈変竴涓敊璇�
-                if (sample.getInsResultList().stream().anyMatch(s -> s.equals(3))) {
+                if (sample.getInsResultList().stream().anyMatch(s -> Objects.equals(s, 3))) {
                     result = "-";
                 } else {
-                    boolean error = sample.getInsResultList().stream().anyMatch(s -> s.equals(0));
+                    boolean error = sample.getInsResultList().stream().anyMatch(s -> Objects.equals(s, 0));
                     if (error) {
                         List<String> collect = new ArrayList<>();
                         int index = 0;
                         for (Integer count : sample.getInsResultList()) {
                             String type;
-                            if (count.equals(0)) {
+                            if (Objects.equals(count, 0)) {
                                 String itemCh = "";
                                 String itemEn = "";
                                 // 娣诲姞涓嶅悎鏍兼弿杩�
@@ -3645,6 +4161,7 @@
                 }
             }
 
+            if (showResult) {
             TextRenderData headRenderData7 = new TextRenderData();
             headRenderData7.setText(result);
             Style headStyle7 = new Style();
@@ -3652,6 +4169,8 @@
             headStyle7.setColor("000000");
             headRenderData7.setStyle(headStyle7);
             text.add(headRenderData7);
+            }
+            }
 
             TextRenderData[] text2 = text.toArray(new TextRenderData[0]);
             rowRenderData = Rows.of(text2).center().rowAtleastHeight(1).create();
@@ -3812,7 +4331,7 @@
                 sampleProductDto2.setLastValue(sampleProductDto2.getLastValue().trim());
             }
 
-            if (sampleProductDto2.getInsResult().equals(0)) {
+            if (Objects.equals(sampleProductDto2.getInsResult(), 0)) {
                 // 鏌ヨ涓嶅悎鏍煎娴�
                 Long count = insUnqualifiedRetestProductMapper.selectCount(Wrappers.<InsUnqualifiedRetestProduct>lambdaQuery()
                         .eq(InsUnqualifiedRetestProduct::getInsProductId, sampleProductDto2.getInsProductId())
@@ -3876,7 +4395,7 @@
      * @param rowRenderData
      * @param rows
      */
-    private static void addEnding(List<TextRenderData> text, RowRenderData rowRenderData, List<RowRenderData> rows, int max) {
+    private static void addEnding(List<TextRenderData> text, RowRenderData rowRenderData, List<RowRenderData> rows, int max, boolean showResult) {
         for (int i = 0; i < 2; i++) {
             TextRenderData endingRenderData = new TextRenderData();
             endingRenderData.setText("澶囨敞鈭�1999");
@@ -3887,9 +4406,9 @@
             text.add(endingRenderData);
         }
 
-        for (int i = 0; i < 5 + max - 1; i++) {
+        for (int i = 0; i < (showResult ? 5 : 4) + max - 1; i++) {
             TextRenderData endingRenderData = new TextRenderData();
-            endingRenderData.setText("鈥溾垰鈥濊〃绀洪」鐩悎鏍�,鈥溍椻�濊〃绀洪」鐩笉鍚堟牸,鈥�-鈥濊〃绀轰笉瑕佸垽瀹氾紝鈥�/鈥濊〃绀烘病鏈夋爣鍑嗚姹傘�侤鈥溾垰鈥� indicates test ltem is qualified,鈥溍椻�� indicates test ltem is unqualified,鈥�-鈥� indicates test ltem judgment is not required,鈥�/鈥� indicates test ltem is no test requirement.鈭�2000");
+            endingRenderData.setText(showResult ? "鈥溾垰鈥濊〃绀洪」鐩悎鏍�,鈥溍椻�濊〃绀洪」鐩笉鍚堟牸,鈥�-鈥濊〃绀轰笉瑕佸垽瀹氾紝鈥�/鈥濊〃绀烘病鏈夋爣鍑嗚姹傘�侤鈥溾垰鈥� indicates test ltem is qualified,鈥溍椻�� indicates test ltem is unqualified,鈥�-鈥� indicates test ltem judgment is not required,鈥�/鈥� indicates test ltem is no test requirement.鈭�2000" : "");
             Style endingStyle = new Style();
             endingStyle.setFontFamily("瀹嬩綋");
             endingStyle.setColor("000000");

--
Gitblit v1.9.3