package com.inspect.resultmain.controller;

import cn.hutool.core.date.DateUtil;
import com.inspect.analysis.domain.ResultAnalysis;
import com.inspect.analysis.service.IResultAnalysisService;
import com.inspect.base.core.sftp.SftpClient;
import com.inspect.base.core.sftp.SftpUploadEntity;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.poi.ExcelUtil;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.core.web.page.TableDataInfo;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.img.domain.InspectionReportImg;
import com.inspect.img.service.IInspectionReportImgService;
import com.inspect.insreport.domain.InspectionReport;
import com.inspect.insreport.service.IInspectionReportService;
import com.inspect.insreportdata.domain.InspectionReportData;
import com.inspect.insreportdata.service.IInspectionReportDataService;
import com.inspect.message.MessageUtils;
import com.inspect.partrolresult.domain.PatrolResult;
import com.inspect.partrolresult.service.IPatrolResultService;
import com.inspect.partrolresult.util.PrintUtil;
import com.inspect.partrolresultAux.service.IPatrolResultAuxService;
import com.inspect.resultmain.domain.PatrolTaskResultMain;
import com.inspect.resultmain.service.IPatrolTaskResultMainService;
import com.inspect.task.service.IPatrolTaskService;
import com.inspect.taskinfo.service.IPatrolTaskInfoService;
import com.inspect.taskstatus.service.IPatrolTaskStatusService;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.function.IOConsumer;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.Units;
import org.apache.poi.xssf.streaming.SXSSFDrawing;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@RefreshScope
@RequestMapping({"/resultmain"})
public class PatrolTaskResultMainController extends BaseController {

    @Value("${sftp.basePath}")
    private String basePath;

    @Value("${sftp.stationCode}")
    private String stationCode;

    @Value("${inspect.task.report.all:0}")
    private String exportReportFlag;

    private final IPatrolTaskResultMainService patrolTaskResultMainService;
    private final IPatrolResultService patrolResultService;
    private final IInspectionReportDataService inspectionReportDataService;
    private final IInspectionReportImgService inspectionReportImgService;
    private final IPatrolTaskInfoService patrolTaskInfoService;
    private final IResultAnalysisService resultAnalysisService;
    private final IInspectionReportService inspectionReportService;
    private final IPatrolTaskService patrolTaskService;
    private final IPatrolTaskStatusService patrolTaskStatusService;
    private final SftpClient sftpClient;
    private final IPatrolResultAuxService iPatrolResultAuxService;

    private static final ExecutorService executor = Executors.newFixedThreadPool(10);

    @Autowired
    private MessageUtils MessageUtils;

    public PatrolTaskResultMainController(IPatrolTaskInfoService patrolTaskInfoService, IPatrolTaskResultMainService patrolTaskResultMainService, IPatrolResultService patrolResultService, IInspectionReportDataService inspectionReportDataService, IInspectionReportImgService inspectionReportImgService, IResultAnalysisService resultAnalysisService, IInspectionReportService inspectionReportService, IPatrolTaskService patrolTaskService, IPatrolTaskStatusService patrolTaskStatusService, SftpClient sftpClient, IPatrolResultAuxService iPatrolResultAuxService) {
        this.patrolTaskInfoService = patrolTaskInfoService;
        this.patrolTaskResultMainService = patrolTaskResultMainService;
        this.patrolResultService = patrolResultService;
        this.inspectionReportDataService = inspectionReportDataService;
        this.inspectionReportImgService = inspectionReportImgService;
        this.resultAnalysisService = resultAnalysisService;
        this.inspectionReportService = inspectionReportService;
        this.patrolTaskService = patrolTaskService;
        this.patrolTaskStatusService = patrolTaskStatusService;
        this.sftpClient = sftpClient;
        this.iPatrolResultAuxService = iPatrolResultAuxService;
    }

    @GetMapping({"/list"})
    public TableDataInfo list(PatrolTaskResultMain patrolTaskResultMain) {
        this.startPage();
        List<PatrolTaskResultMain> list = this.patrolTaskResultMainService.selectPatrolTaskResultMain(patrolTaskResultMain);
        for (PatrolTaskResultMain taskResultMain : list) {
            String devType = taskResultMain.getDevType();
            if (StringUtils.isNotEmpty(devType)) {
                String[] devTypes = devType.split(",");
                List<String> devTypeList = Arrays.stream(devTypes).distinct().collect(Collectors.toList());
                taskResultMain.setDevType(String.join(",", devTypeList));
            }
        }
        return this.getDataTable(list);
    }

    @Log(
            title = "任务主",
            businessType = BizType.EXPORT
    )
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, PatrolTaskResultMain patrolTaskResultMain) {
        List<PatrolTaskResultMain> list = this.patrolTaskResultMainService.selectPatrolTaskResultMainList(patrolTaskResultMain);
        ExcelUtil<PatrolTaskResultMain> util = new ExcelUtil<>(PatrolTaskResultMain.class);
        util.exportExcel(response, list, "任务主数据");
    }

    @GetMapping({"/{lineId}"})
    public AjaxResult getInfo(@PathVariable("lineId") Long lineId) {
        return AjaxResult.success(this.patrolTaskResultMainService.selectPatrolTaskResultMainByLineId(lineId));
    }

    @Log(
            title = "任务主",
            businessType = BizType.INSERT
    )
    @PostMapping
    public AjaxResult add(@RequestBody PatrolTaskResultMain patrolTaskResultMain) {
        return this.toAjax(this.patrolTaskResultMainService.insertPatrolTaskResultMain(patrolTaskResultMain));
    }

    @Log(
            title = "任务主",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult edit(@RequestBody PatrolTaskResultMain patrolTaskResultMain) {
        return this.toAjax(this.patrolTaskResultMainService.updatePatrolTaskResultMain(patrolTaskResultMain));
    }

    @Log(
            title = "任务主",
            businessType = BizType.DELETE
    )
    @PostMapping({"/remove/{lineIds}"})
    public AjaxResult remove(@PathVariable Long[] lineIds) {
        return this.toAjax(this.patrolTaskResultMainService.deletePatrolTaskResultMainByLineIds(lineIds));
    }

    @GetMapping({"/updateInfo"})
    public AjaxResult updateInfo(
            @RequestParam("lineId") Long lineId,
            @RequestParam("chechkPerson") String checkPerson,
            @RequestParam("taskResult") String taskResult) {
        PatrolTaskResultMain resultMain = new PatrolTaskResultMain();
        resultMain.setLineId(lineId);
        resultMain.setCheckPerson(checkPerson);
        resultMain.setTaskResult(taskResult);
        String mainId = String.valueOf(lineId);
        long startTime = System.currentTimeMillis();
        logger.info("[ARCHIVE] Starting, Id: {}", mainId);
        List<Long> lineIds = patrolTaskResultMainService.selectLineIds(lineId);
        if (lineIds.size() == 0) {
            lineIds.add(lineId);
        }
        logger.info("---归档--lineIds size: {}，lineIds：{}", lineIds.size(), lineIds);
//        int analyseNum, collectNum;
//        AtomicInteger modifyNum = new AtomicInteger(0);
//        List<PatrolResult> resultList = patrolResultService.selectPatrolResultList(new PatrolResult(mainId));
        List<PatrolResult> resultList = patrolResultService.selectPatrolResultListByMainIds(lineIds);
        if (resultList.isEmpty()) {
            logger.error("[归档]失败, 数据采集中...");
            return AjaxResult.error("数据采集中请稍后....");
        }
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        int csQxNum = 0, aiQxNum = 0;
        List<String> taskPatrolledIds = resultList.stream().map(PatrolResult::getTaskPatrolledId).distinct().collect(Collectors.toList());
        for (String taskPatrolledId : taskPatrolledIds) {
            resultAnalysis.setTaskPatrolledId(taskPatrolledId);
            ResultAnalysis ras = patrolResultService.selectTaskAbnormalData(resultAnalysis);
            csQxNum += ras.getCsQxNum();
            aiQxNum += ras.getAiQxNum();
        }

        if ("0".equals(exportReportFlag) && 0 == csQxNum && 0 == aiQxNum) {
            logger.error("[归档]没有缺陷数据, 无需归档!");
            return AjaxResult.error("没有缺陷数据, 无需归档!");
        }
//        List<PatrolResultAux> patrolResultAuxList = iPatrolResultAuxService.selectPatrolResultAuxListByMainId(new PatrolResultAux(mainId));
//        List<PatrolResultAux> patrolResultAuxList = iPatrolResultAuxService.selectPatrolResultAuxListByMainIds(lineIds);
//        for (PatrolResultAux aux : patrolResultAuxList) {
//            resultList.forEach((item) -> {
//                if (aux.getResultId().equals(String.valueOf(item.getLineId()))) {
//                    item.setValue(aux.getValue());
//                    if (!"1".equals(item.getDataType())) {
//                        modifyNum.addAndGet(1);
//                    }
//                }
//            });
//        }

//        startTime = PrintUtil.useTime("INQUIRY MEND DATA", startTime);
//        collectNum = resultList.size();
//        analyseNum = resultAnalysisService.selectResultAnalysisByMainId(lineId);
//        analyseNum = resultAnalysisService.selectResultAnalysisByMainIds(lineIds);
//        startTime = PrintUtil.useTime("INQUIRY ANALYZE DATA", startTime);
//        logger.info("[ARCHIVE] Id: {}, collectNum: {}, analyseNum: {}, modifyNum:{}", mainId, collectNum, analyseNum, modifyNum.get());

        // 使用CompletableFuture异步执行saveReport
        int finalAiQxNum = aiQxNum;
        int finalCsQxNum = csQxNum;
        CompletableFuture<List<Long>> saveReportFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("[ARCHIVE] Start saving reports");
            return patrolResultService.saveReport(resultMain, lineIds, lineId, resultList, finalAiQxNum, finalCsQxNum);
        }, executor).exceptionally(ex -> {
            logger.error("Report saving failed", ex);
            return Collections.emptyList();
        });
        PrintUtil.useTime("saveReport", startTime);
        // 当saveReport完成后，再异步处理所有导出任务
        CompletableFuture<Void> reportsToExportFuture = saveReportFuture.thenAcceptAsync(reportIds -> {
            logger.info("-----------[ARCHIVE] Saved export reportIds: {}", reportIds);
            if (reportIds.isEmpty()) {
                logger.warn("No reports to export");
                return;
            }
            // 为每个reportId创建异步导出任务
            CompletableFuture<?>[] exportFutures = reportIds.stream()
                    .map(reportId -> CompletableFuture.runAsync(() -> {
                        logger.info("[EXPORT] Start export for reportId: {}", reportId);
                        exportExcelWordAndZip(String.valueOf(reportId));
                    }, executor))
                    .toArray(CompletableFuture[]::new);

        }, executor).exceptionally(ex -> {
            logger.error("Error occurred during saveReport: ", ex);
            return null;
        });
        PrintUtil.useTime("exportExcelWordAndZip", startTime);
//        logger.info("-----------[ARCHIVE] EndTime: {}, reportIds: {}", DateUtil.now(), reportIds);
//        CompletableFuture.allOf(reportsToExportFuture).join();
        return toAjax(1);

    }

    @PostMapping({"/updateInfo_shaoxing"})
    public AjaxResult updateInfo_shaoxing(
            @RequestBody PatrolTaskResultMain resultMain) {
        long startTime = System.currentTimeMillis();
        long finalStartTime = startTime;
        CompletableFuture<List<Long>> saveReportFuture = CompletableFuture.supplyAsync(() -> {
            List<String> taskPatrolledIds = resultMain.getTaskPatrolledIds();
            logger.info("-----------patrolTaskResultMains taskPatrolledIds: {}", taskPatrolledIds);
            List<PatrolTaskResultMain> patrolTaskResultMains = patrolTaskResultMainService.selectPatrolTaskResultMainByTaskPatrolledIds(taskPatrolledIds);
            logger.info("-----------patrolTaskResultMains: {}", patrolTaskResultMains);
            if (patrolTaskResultMains.size() == 0) {
                logger.error("[归档]失败, 数据采集中...");
//                return AjaxResult.error("数据采集中请稍后....");
            }
            List<Long> lineIds = patrolTaskResultMains.stream().map(PatrolTaskResultMain::getLineId).collect(Collectors.toList());
            List<Long> longs = patrolTaskResultMainService.selectLineIdsByList(lineIds);
            if (longs != null && longs.size() > 0) {
                lineIds.addAll(longs);
            }
            lineIds = lineIds.stream().distinct().collect(Collectors.toList());
            List<PatrolResult> resultList = patrolResultService.selectPatrolResultListByMainIds(lineIds);
            if (resultList.isEmpty()) {
                logger.error("[归档]失败, 数据采集中...");
//                return AjaxResult.error("数据采集中请稍后....");
            }
            List<Long> finalLineIds = lineIds;
            PrintUtil.useTime("查询统计数据", finalStartTime);
            logger.info("[ARCHIVE] Start saving reports");
            return patrolResultService.saveReportShaoxing(resultMain, finalLineIds, resultList);
        }, executor).exceptionally(ex -> {
            logger.error("Report saving failed", ex);
            return Collections.emptyList();
        });
        startTime = PrintUtil.useTime("保存报告数据", startTime);
        // 当saveReport完成后，再异步处理所有导出任务
        saveReportFuture.thenAcceptAsync(reportIds -> {
            logger.info("-----------[ARCHIVE] Saved export reportIds: {}", reportIds);
            if (reportIds.isEmpty()) {
                logger.warn("No reports to export");
                return;
            }
            // 为每个reportId创建异步导出任务
            CompletableFuture<?>[] exportFutures = reportIds.stream()
                    .map(reportId -> CompletableFuture.runAsync(() -> {
                        logger.info("[EXPORT] Start export for reportId: {}", reportId);
//                        exportExcelWordAndZipLingzhou(String.valueOf(reportId));
                        exportExcelWordAndZipShaoxing(String.valueOf(reportId));
                    }, executor))
                    .toArray(CompletableFuture[]::new);

        }, executor).exceptionally(ex -> {
            logger.error("Error occurred during saveReport: ", ex);
            return null;
        });
        PrintUtil.useTime("导出报告数据", startTime);
        return toAjax(1);

    }


    @PostMapping({"/updateInfo"})
    public AjaxResult updateInfo_lingzhou(
            @RequestBody PatrolTaskResultMain resultMain) {
        long startTime = System.currentTimeMillis();
        List<Long> lineIds = resultMain.getLineIds();
        Long lineId = resultMain.getLineIds().get(0);
        resultMain.setLineId(lineId);
        List<Long> longs = patrolTaskResultMainService.selectLineIdsByList(lineIds);
        if (longs != null && longs.size() > 0) {
            lineIds.addAll(longs);
        }
        lineIds = lineIds.stream().distinct().collect(Collectors.toList());
        PrintUtil.useTime("收集需归档的lineIds", startTime);
        logger.info("---归档--lineIds size: {}，lineIds：{}", lineIds.size(), lineIds);
        List<PatrolResult> resultList = patrolResultService.selectPatrolResultListByMainIds(lineIds);
        if (resultList.isEmpty()) {
            logger.error("[归档]失败, 数据采集中...");
            return AjaxResult.error("数据采集中请稍后....");
        }
        startTime = System.currentTimeMillis();
        List<Long> finalLineIds = lineIds;
        CompletableFuture<List<Long>> saveReportFuture = CompletableFuture.supplyAsync(() -> {
            logger.info("[ARCHIVE] Start saving reports");
            return patrolResultService.saveReportLingzhou_v2(resultMain, finalLineIds, lineId, resultList);
        }, executor).exceptionally(ex -> {
            logger.error("Report saving failed", ex);
            return Collections.emptyList();
        });
        PrintUtil.useTime("保存报告数据", startTime);
        startTime = System.currentTimeMillis();
        // 当saveReport完成后，再异步处理所有导出任务
        saveReportFuture.thenAcceptAsync(reportIds -> {
            logger.info("-----------[ARCHIVE] Saved export reportIds: {}", reportIds);
            if (reportIds.isEmpty()) {
                logger.warn("No reports to export");
                return;
            }
            // 为每个reportId创建异步导出任务
            CompletableFuture<?>[] exportFutures = reportIds.stream()
                    .map(reportId -> CompletableFuture.runAsync(() -> {
                        logger.info("[EXPORT] Start export for reportId: {}", reportId);
                        exportExcelWordAndZipLingzhou(String.valueOf(reportId));
                    }, executor))
                    .toArray(CompletableFuture[]::new);

        }, executor).exceptionally(ex -> {
            logger.error("Error occurred during saveReport: ", ex);
            return null;
        });
        PrintUtil.useTime("导出报告数据", startTime);
        return toAjax(1);

    }


    @GetMapping({"/updateInfo_v2"})
    public AjaxResult updateInfoV2(PatrolTaskResultMain resultMain) {
        String mainId = String.valueOf(resultMain.getLineId());
        long startTime = System.currentTimeMillis();
        logger.info("[归档]开始处理ID: {}", mainId);
        AtomicInteger modifyNum = new AtomicInteger(0);
        List<PatrolResult> resultList = patrolResultService.selectPatrolResultList(new PatrolResult(mainId));
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        resultAnalysis.setTaskPatrolledId(resultList.get(0).getTaskPatrolledId());
        ResultAnalysis ras = patrolResultService.selectTaskAbnormalData(resultAnalysis);
        if (0 == ras.getCsQxNum() && 0 == ras.getAiQxNum()) {
            logger.error("[归档]没有缺陷数据, 无需归档!");
            return AjaxResult.error("没有缺陷数据, 无需归档!");
        } else if (resultList.isEmpty()) {
            logger.error("[归档]失败, 数据采集中...");
            return AjaxResult.error("数据采集中请稍后....");
        } else {
            int collectNum = resultList.size();
            int analyseNum = resultAnalysisService.selectResultAnalysisByMainId(resultMain.getLineId());
            startTime = PrintUtil.useTime("查询分析数据", startTime);
            logger.info("[归档]执行ID: {}, 采集条数: {}, 分析条数: {}, 修正条数: {} ", mainId, collectNum, analyseNum, modifyNum.get());
            List reportIds = patrolResultService.saveReportV2(resultMain, resultList);
            PrintUtil.useTime("归档结束", startTime);
            (new Thread(() -> {
                long beginTime = (new Date()).getTime();
                logger.info("[导出报告] 开始时间: {}", DateUtil.now());

                for (int i = 0; i < reportIds.size(); ++i) {
                    exportExcelWordAndZip(String.valueOf(reportIds.get(i)));
                }

                PrintUtil.useTime("导出报告结束", beginTime);
            })).start();
            return toAjax(1);
        }
    }

    @Log(
            title = "导出报告",
            businessType = BizType.EXPORT
    )
    @PostMapping({"/reportExport"})
    public ResponseEntity reportExport(HttpServletResponse response, PatrolTaskResultMain patrolTaskResultMain) throws Exception {
        logger.info("开始导出报告,patrolTaskResultMain:{}", patrolTaskResultMain.toString());
        List<String> taskPatrolledIds = patrolTaskResultMain.getTaskPatrolledIds();
        List<PatrolTaskResultMain> patrolTaskResultMains = patrolTaskResultMainService.selectPatrolTaskResultMainByTaskPatrolledIds(taskPatrolledIds);
        logger.info("-----------patrolTaskResultMains: {}", patrolTaskResultMains);
        if (patrolTaskResultMains.size() == 0) {
            logger.error("[归档]失败, 数据采集中...");
            return ResponseEntity.ok("数据采集中请稍后....");
        }
        List<Long> lineIds = patrolTaskResultMains.stream().map(PatrolTaskResultMain::getLineId).collect(Collectors.toList());
        List<Long> longs = patrolTaskResultMainService.selectLineIdsByList(lineIds);
        if (longs != null && longs.size() > 0) {
            lineIds.addAll(longs);
        }
        lineIds = lineIds.stream().distinct().collect(Collectors.toList());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"InspectionReport_" + System.currentTimeMillis() + ".xlsx\"");
        InspectionReport inspectionReport = patrolResultService.getInspectionReport(lineIds, patrolTaskResultMain);
        List<InspectionReportData> inspectionReportDataList = inspectionReport.getReportDatalist();
        List<String> images = new ArrayList<>();
        for (InspectionReportData reportData : inspectionReportDataList) {
            List<InspectionReportImg> reportImgList = reportData.getReportImgList();

            for (InspectionReportImg reportImg : reportImgList) {
                if (StringUtils.isNotEmpty(reportImg.getImgSrc()) && reportImg.getImgType().equals("0")) {
                    String originalImgSrc = reportImg.getImgSrc();
                    images.add(originalImgSrc);
                }
            }
        }

        // 将图片下载到临时文件，避免大量图片字节数据全部驻留内存
        Map<String, Path> tempFileMap = new LinkedHashMap<>();
        List<Path> tempFiles = new ArrayList<>();
        for (String imgSrc : images) {
            try {
                Path tempFile = downloadImageToTemp(imgSrc);
                if (tempFile != null) {
                    tempFileMap.put(imgSrc, tempFile);
                    tempFiles.add(tempFile);
                }
            } catch (Exception e) {
                logger.warn("报告归档下载图片失败: {}", imgSrc, e);
            }
        }

        try (SXSSFWorkbook sxssfWorkbook = getSXSSFWorkbookShaoxing(inspectionReport, tempFileMap);
             ServletOutputStream outputStream = response.getOutputStream()) {
            sxssfWorkbook.write(outputStream);
        }

        for (Path tempFile : tempFiles) {
            try {
                Files.deleteIfExists(tempFile);
            } catch (IOException e) {
                logger.warn("删除临时文件失败: {}", tempFile, e);
            }
        }

        return ResponseEntity.ok("报告导出成功！");
    }

    public String ToStationIn(String areaId) {
        String areaName = "";
        Map<String, Object> map = this.patrolResultService.selectAreaInfo(areaId);
        if (map != null) {
            String mapType = String.valueOf(map.get("area_type"));
            if (StringUtils.isNotEmpty(mapType) && mapType.equals("station_in")) {
                areaName = String.valueOf(map.get("area_name"));
            } else {
                String parentId = String.valueOf(map.get("ancestors"));
                String[] parentArr = parentId.split(StringUtils.COMMA);

                for (String s : parentArr) {
                    Map<String, Object> maps = this.patrolResultService.selectAreaInfo(s);
                    if (maps != null) {
                        String mapTypes = String.valueOf(maps.get("area_type"));
                        if (StringUtils.isNotEmpty(mapTypes) && mapTypes.equals("station_in")) {
                            areaName = String.valueOf(maps.get("area_name"));
                        }
                    }
                }

                if (StringUtils.isEmpty(areaName)) {
                    List<Map<String, Object>> areaMap = this.patrolResultService.selectAreaInfoByParentId(areaId);
                    if (areaMap != null) {
                        System.out.println(areaMap.size());
                        if (!areaMap.isEmpty()) {
                            for (Map<String, Object> stringObjectMap : areaMap) {
                                if (stringObjectMap != null) {
                                    String mapTypes = String.valueOf(stringObjectMap.get("area_type"));
                                    if (StringUtils.isNotEmpty(mapTypes) && mapTypes.equals("station_in")) {
                                        areaName = String.valueOf(stringObjectMap.get("area_name"));
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return areaName;
    }


    private XWPFDocument getXWPFDocument(InspectionReport report, Map<String, byte[]> images) {
        XWPFDocument doc = new XWPFDocument();

        // 标题
        addTitle(doc, MessageUtils.get("巡视报告"));

        // 基本信息表格
        XWPFTable baseInfoTable = doc.createTable(7, 4);
        baseInfoTable.setWidth("100%");

        // 设置表格样式
        setTableStyle(baseInfoTable);

        // 填充基础信息
        fillBaseInfo(baseInfoTable, report);


        // 点位汇总
//        List<String> statusList = Arrays.asList(MessageUtils.get("异常"), MessageUtils.get("待人工确认"), MessageUtils.get("正常"));
        List<String> statusList = new ArrayList<>();
        statusList.add(MessageUtils.get("缺陷"));
        if ("1".equals(exportReportFlag)) {
            statusList.add(MessageUtils.get("正常"));
            statusList.add(MessageUtils.get("异常"));
        }
        for (String status : statusList) {
            addStatusSection(doc, report, status, images);
        }

        return doc;
    }

    private XWPFDocument getXWPFDocumentLingzhou(InspectionReport report, Map<String, Path> tempFileMap) {
        XWPFDocument doc = new XWPFDocument();

        // 标题
        addTitle(doc, MessageUtils.get("巡视报告"));

        // 基本信息表格
        XWPFTable baseInfoTable = doc.createTable(7, 4);
        baseInfoTable.setWidth("100%");

        // 设置表格样式
        setTableStyle(baseInfoTable);

        // 填充基础信息
        fillBaseInfoLingzhou(baseInfoTable, report);


        // 点位汇总
        List<String> statusList = Arrays.asList(MessageUtils.get("缺陷"), MessageUtils.get("异常"), MessageUtils.get("正常"));
//        List<String> statusList = Collections.singletonList(MessageUtils.get("缺陷"));
        for (String status : statusList) {
            addStatusSectionLingzhou(doc, report, status, tempFileMap);
        }
//        addQXStatusSection(doc, report, MessageUtils.get("缺陷"), images);
//        addNormalStatusSection(doc, report, MessageUtils.get("正常"), images);
        return doc;
    }

    private void addTitle(XWPFDocument doc, String title) {
        XWPFParagraph titlePara = doc.createParagraph();
        titlePara.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titlePara.createRun();
        titleRun.setText(title);
        titleRun.setFontFamily("宋体");
        titleRun.setFontSize(20);
        titleRun.setBold(true);
        addEmptyParagraph(doc); // 空行
    }

    // 样式设置方法
    private void setTableStyle(XWPFTable table) {
        table.setCellMargins(100, 100, 100, 100); // 设置单元格边距
        for (XWPFTableRow row : table.getRows()) {
            for (XWPFTableCell cell : row.getTableCells()) {
                setCellStyle(cell);
            }
        }
    }

    private void fillBaseInfo(XWPFTable table, InspectionReport report) {

        fillRow(table, 0, MessageUtils.get("变电站"), report.getStationName(), MessageUtils.get("电压等级"), report.getVoltLevel());
        fillRow(table, 1, MessageUtils.get("巡视计划创建日期"), formatDate(report.getInspectionDate()),
                MessageUtils.get("变电站类别"), report.getStationType());
        fillRow(table, 2, MessageUtils.get("巡视任务"), report.getInspectionTaskName(),
                MessageUtils.get("环境信息"), report.getEnvInfo());
        fillRow(table, 3, MessageUtils.get("审核人"), report.getCheckPerson(),
                MessageUtils.get("审核时间"), formatDateTime(report.getCheckTime()));
        fillRow(table, 4, MessageUtils.get("巡视开始时间"), formatDateTime(report.getInspectionStartTime()),
                MessageUtils.get("巡视结束时间"), formatDateTime(report.getInspectionEndTime()));
        fillRowWithMerge(table, 5, MessageUtils.get("巡视统计"), report.getPatrolStatistics(), 3);

        // 新增：巡视结论（合并右侧3列）
        fillRowWithMerge(table, 6, MessageUtils.get("巡视结论"), report.getDescription(), 3);
    }

    private void fillBaseInfoLingzhou(XWPFTable table, InspectionReport report) {

        fillRow(table, 0, MessageUtils.get("变电站"), report.getStationName(), MessageUtils.get("电压等级"), report.getVoltLevel());
        fillRow(table, 1, MessageUtils.get("巡视计划创建日期"), formatDate(report.getInspectionDate()),
                MessageUtils.get("变电站类别"), report.getStationType());
        fillRow(table, 2, MessageUtils.get("巡视任务"), report.getInspectionTaskName(),
                MessageUtils.get("环境信息"), report.getEnvInfo());
        fillRow(table, 3, MessageUtils.get("审核人"), report.getCheckPerson(),
                MessageUtils.get("审核时间"), formatDateTime(report.getCheckTime()));
        fillRow(table, 4, MessageUtils.get("巡视开始时间"), formatDateTime(report.getInspectionStartTime()),
                MessageUtils.get("巡视结束时间"), formatDateTime(report.getInspectionEndTime()));
        fillRowWithMerge(table, 5, MessageUtils.get("巡视统计"), report.getPatrolStatistics(), 3);

        // 新增：巡视结论（合并右侧3列）
        fillRowWithMerge(table, 6, MessageUtils.get("巡视结论"), report.getDescription(), 3);
    }

    private void fillRow(XWPFTable table, int rowNum, String... values) {
        XWPFTableRow row = table.getRow(rowNum);
        for (int i = 0; i < values.length; i++) {
            XWPFTableCell cell = row.getCell(i);
            CTP ctP = cell.getCTTc().sizeOfPArray() == 0 ? cell.getCTTc().addNewP() : cell.getCTTc().getPArray(0);
            XWPFParagraph par = cell.getParagraph(ctP);
            par.createRun().setText(values[i]);
            // 左侧标题列（索引0,2）设置特殊样式
            if (i % 2 == 0) {
                setTitleCellStyle(cell);
            } else {
                setValueCellStyle(cell);
            }
        }
    }

    // 标题单元格样式（宋体小五加粗）
    private void setTitleCellStyle(XWPFTableCell cell) {
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
        for (XWPFParagraph para : cell.getParagraphs()) {
            para.setAlignment(ParagraphAlignment.CENTER);
            for (XWPFRun run : para.getRuns()) {
                run.setFontFamily("宋体");
                run.setFontSize(9);
                run.setBold(true);
                run.setColor("000000");
            }
        }

        // 单元格背景色（浅灰色）
        CTTcPr tcPr = cell.getCTTc().addNewTcPr();
        CTShd shading = tcPr.addNewShd();
        shading.setFill("D3D3D3");
        shading.setVal(STShd.Enum.forString("clear"));
    }

    // 值单元格样式
    private void setValueCellStyle(XWPFTableCell cell) {
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
        for (XWPFParagraph para : cell.getParagraphs()) {
            para.setAlignment(ParagraphAlignment.CENTER);
            for (XWPFRun run : para.getRuns()) {
                run.setFontFamily("宋体");
                run.setFontSize(9);
                run.setColor("000000");
            }
        }
    }

    /**
     * 填充带合并的表格行
     *
     * @param table     表格对象
     * @param rowNum    行号
     * @param title     左侧标题
     * @param content   右侧内容
     * @param mergeCols 需要合并的列数
     */
    private void fillRowWithMerge(XWPFTable table, int rowNum, String title, String content, int mergeCols) {
        XWPFTableRow row = table.getRow(rowNum);

        // 设置左侧标题单元格
        XWPFTableCell titleCell = row.getCell(0);
        CTP ctPTitle = titleCell.getCTTc().sizeOfPArray() == 0 ? titleCell.getCTTc().addNewP() : titleCell.getCTTc().getPArray(0);
        XWPFParagraph parTitle = titleCell.getParagraph(ctPTitle);
        parTitle.createRun().setText(title);
        setTitleCellStyle(titleCell);

        // 设置右侧合并内容单元格
        XWPFTableCell contentCell = row.getCell(1);
        CTP ctPContent = contentCell.getCTTc().sizeOfPArray() == 0 ? contentCell.getCTTc().addNewP() : contentCell.getCTTc().getPArray(0);
        XWPFParagraph parContent = contentCell.getParagraph(ctPContent);
        parContent.createRun().setText(content);
        // 合并右侧单元格
        for (int i = 1; i <= mergeCols; i++) {
            if (i > 1) {
                row.getCell(i).removeParagraph(0);
                mergeCellsHorizontal(table, rowNum, 1, i);
            }
            setMergedContentStyle(row.getCell(i)); // 内容样式
        }
    }

    // 合并单元格工具方法（横向）
    private void mergeCellsHorizontal(XWPFTable table, int row, int startCol, int endCol) {
        for (int i = startCol; i <= endCol; i++) {
            CTTcPr tcPr = table.getRow(row).getCell(i).getCTTc().getTcPr();
            if (tcPr == null) tcPr = table.getRow(row).getCell(i).getCTTc().addNewTcPr();
            if (i == startCol) {
                tcPr.addNewHMerge().setVal(STMerge.RESTART);
            } else {
                tcPr.addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }


    /**
     * 合并内容单元格样式
     */
    private void setMergedContentStyle(XWPFTableCell cell) {
        for (XWPFParagraph para : cell.getParagraphs()) {
            para.setAlignment(ParagraphAlignment.LEFT);
            para.setSpacingAfter(0);
            para.setIndentationFirstLine(400); // 首行缩进

            for (XWPFRun run : para.getRuns()) {
                run.setFontFamily("宋体");
                run.setFontSize(9);
                run.setColor("000000");
            }
        }

        // 自动换行设置
        CTTcPr tcPr = cell.getCTTc().addNewTcPr();
        tcPr.addNewNoWrap().setVal(STOnOff.FALSE);
    }


    private void addStatusSection(XWPFDocument doc, InspectionReport report,
                                  String status, Map<String, byte[]> images) {
//        addSectionHeader(doc, status + MessageUtils.get("点位汇总"));
        addSectionHeader(doc, status + MessageUtils.get("汇总"));

        XWPFTable table = doc.createTable(1, 9);
        table.setWidth("100%");


        // 创建表头
        String[] headers = {MessageUtils.get("编号"), MessageUtils.get("区域"), MessageUtils.get("设备"), MessageUtils.get("点位"), MessageUtils.get("数据来源"),
                MessageUtils.get("采集时间"), MessageUtils.get("巡视结果"), MessageUtils.get("算法名称"), MessageUtils.get("巡视图像")};
        XWPFTableRow headerRow = table.getRow(0);
        for (int i = 0; i < headers.length; i++) {
            XWPFTableCell cell = headerRow.getCell(i);
            CTP ctP = cell.getCTTc().sizeOfPArray() == 0 ? cell.getCTTc().addNewP() : cell.getCTTc().getPArray(0);
            XWPFParagraph par = cell.getParagraph(ctP);
            par.createRun().setText(headers[i]);
        }
        setTableHeaderStyle(table);
        // 填充数据
        List<InspectionReportData> dataList = report.getReportDatalist();
        if (dataList != null && dataList.size() > 0) {
            dataList = dataList.stream().filter(data -> status.equals(data.getPointStatus())).collect(Collectors.toList());
            for (InspectionReportData data : dataList) {
                XWPFTableRow row = table.createRow();
                fillDataRow(row, data, images);
            }
        }
        addEmptyParagraph(doc);
    }

    private void addStatusSectionLingzhou(XWPFDocument doc, InspectionReport report,
                                          String status, Map<String, Path> tempFileMap) {
//        addSectionHeader(doc, status + MessageUtils.get("点位汇总"));
        addSectionHeader(doc, status + MessageUtils.get("汇总"));

        XWPFTable table = doc.createTable(1, 10);
        table.setWidth("100%");


        // 创建表头
        String[] headers = {MessageUtils.get("编号"), MessageUtils.get("区域"), MessageUtils.get("设备"), MessageUtils.get("部件"), MessageUtils.get("点位"), MessageUtils.get("数据来源")
                , MessageUtils.get("识别时间"), MessageUtils.get("巡视结果"), MessageUtils.get("算法名称"), MessageUtils.get("巡视图像")};
        XWPFTableRow headerRow = table.getRow(0);
        for (int i = 0; i < headers.length; i++) {
            XWPFTableCell cell = headerRow.getCell(i);
            CTP ctP = cell.getCTTc().sizeOfPArray() == 0 ? cell.getCTTc().addNewP() : cell.getCTTc().getPArray(0);
            XWPFParagraph par = cell.getParagraph(ctP);
            par.createRun().setText(headers[i]);
        }
        setTableHeaderStyle(table);
        // 填充数据
        List<InspectionReportData> dataList = report.getReportDatalist();
        if (dataList != null && dataList.size() > 0) {
            // 填充数据
            dataList = dataList.stream()
                    .filter(d -> status.equals(d.getPointStatus()))
                    .collect(Collectors.toList());

            for (InspectionReportData data : dataList) {
                XWPFTableRow row = table.createRow();
                fillDataRowLingzhou(row, data, tempFileMap);
            }
        }
        addEmptyParagraph(doc);
    }

    private void addQXStatusSection(XWPFDocument doc, InspectionReport report,
                                    String status, Map<String, byte[]> images) {
        addSectionHeader(doc, status + MessageUtils.get("点位汇总"));
//        addSectionHeader(doc, status + MessageUtils.get("汇总"));

        XWPFTable table = doc.createTable(1, 10);
        table.setWidth("100%");


        // 创建表头
        String[] headers = {MessageUtils.get("编号"), MessageUtils.get("区域"), MessageUtils.get("设备"), MessageUtils.get("部件"), MessageUtils.get("点位"), MessageUtils.get("数据来源")
                , MessageUtils.get("识别时间"), MessageUtils.get("巡视结果"), MessageUtils.get("算法名称"), MessageUtils.get("巡视图像")};
        XWPFTableRow headerRow = table.getRow(0);
        for (int i = 0; i < headers.length; i++) {
            XWPFTableCell cell = headerRow.getCell(i);
            CTP ctP = cell.getCTTc().sizeOfPArray() == 0 ? cell.getCTTc().addNewP() : cell.getCTTc().getPArray(0);
            XWPFParagraph par = cell.getParagraph(ctP);
            par.createRun().setText(headers[i]);
        }
        setTableHeaderStyle(table);
        // 填充数据
        List<InspectionReportData> dataList = report.getReportDatalist();
        if (dataList != null && dataList.size() > 0) {
            dataList = dataList.stream().filter(data -> status.equals(data.getPointStatus())).collect(Collectors.toList());
            // 填充数据行（除去表头第一行
            for (InspectionReportData data : dataList) {
                XWPFTableRow row = table.createRow();
                fillQXDataRow(row, data, images);
            }
        }
        addEmptyParagraph(doc);
    }

    private void addNormalStatusSection(XWPFDocument doc, InspectionReport report,
                                        String status, Map<String, byte[]> images) {
        addSectionHeader(doc, status + MessageUtils.get("点位汇总"));
//        addSectionHeader(doc, status + MessageUtils.get("汇总"));

        XWPFTable table = doc.createTable(1, 11);
        table.setWidth("100%");


        // 创建表头
        String[] headers = {MessageUtils.get("编号"), MessageUtils.get("区域"), MessageUtils.get("设备"), MessageUtils.get("部件"), MessageUtils.get("点位"), MessageUtils.get("数据来源"),
                MessageUtils.get("告警等级"), MessageUtils.get("识别时间"), MessageUtils.get("巡视结果"), MessageUtils.get("算法名称"), MessageUtils.get("巡视图像")};
        XWPFTableRow headerRow = table.getRow(0);
        for (int i = 0; i < headers.length; i++) {
            XWPFTableCell cell = headerRow.getCell(i);
            CTP ctP = cell.getCTTc().sizeOfPArray() == 0 ? cell.getCTTc().addNewP() : cell.getCTTc().getPArray(0);
            XWPFParagraph par = cell.getParagraph(ctP);
            par.createRun().setText(headers[i]);
        }
        setTableHeaderStyle(table);
        // 填充数据
        List<InspectionReportData> dataList = report.getReportDatalist();
        if (dataList != null && dataList.size() > 0) {
            dataList = dataList.stream().filter(data -> status.equals(data.getPointStatus())).collect(Collectors.toList());
            // 填充数据行（除去表头第一行
            for (InspectionReportData data : dataList) {
                XWPFTableRow row = table.createRow();
                fillNormalDataRow(row, data, images);
            }
        }
        addEmptyParagraph(doc);
    }

    private void addSectionHeader(XWPFDocument doc, String text) {
        XWPFParagraph para = doc.createParagraph();
        para.setSpacingBefore(200); // 段前间距
        XWPFRun run = para.createRun();
        run.setText(text);
        run.setFontSize(14);
        run.setBold(true);
    }

    private void setTableHeaderStyle(XWPFTable table) {
        if (table == null || table.getRows().isEmpty()) return;

        // 获取表头行（第一行）
        XWPFTableRow headerRow = table.getRow(0);

        // 设置表格整体边框
        CTTblPr tblPr = table.getCTTbl().getTblPr();
        if (tblPr == null) {
            tblPr = table.getCTTbl().addNewTblPr();
        }

        // 表格边框设置
        CTTblBorders borders = tblPr.addNewTblBorders();
        borders.addNewBottom().setVal(STBorder.SINGLE);
        borders.addNewLeft().setVal(STBorder.SINGLE);
        borders.addNewRight().setVal(STBorder.SINGLE);
        borders.addNewTop().setVal(STBorder.SINGLE);
        borders.addNewInsideH().setVal(STBorder.SINGLE);
        borders.addNewInsideV().setVal(STBorder.SINGLE);

        // 设置表头单元格样式
        for (XWPFTableCell cell : headerRow.getTableCells()) {
            CTTcPr tcPr = cell.getCTTc().addNewTcPr();
            cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
            // 单元格边距设置
            tcPr.addNewTcMar();
            CTTcMar tcMar = tcPr.getTcMar();
            tcMar.addNewLeft().setW(BigInteger.valueOf(100));
            tcMar.addNewRight().setW(BigInteger.valueOf(100));
            tcMar.addNewTop().setW(BigInteger.valueOf(50));
            tcMar.addNewBottom().setW(BigInteger.valueOf(50));

            // 背景色填充（浅灰色）
            CTShd shading = tcPr.addNewShd();
            shading.setFill("D3D3D3");
            shading.setVal(STShd.Enum.forString("clear"));

            // 设置文本样式为宋体小五号加粗
            for (XWPFParagraph para : cell.getParagraphs()) {
                para.setAlignment(ParagraphAlignment.CENTER);
                for (XWPFRun run : para.getRuns()) {
                    run.setBold(true);
                    run.setFontSize(9);
                    run.setFontFamily("宋体");
                    run.setColor("000000");
                }
            }
        }
    }


    private void fillDataRow(XWPFTableRow row, InspectionReportData data,
                             Map<String, byte[]> images) {
        String[] values = {
                String.valueOf(data.getCode()),
                data.getArea(),
                data.getEqName(),
                data.getPointName(),
                data.getDataSources(),
                formatDateTime(data.getAcquisitionTime()),
                data.getInspectionResults(),
                data.getAlgName(),
                "" // 图片占位
        };

        for (int i = 0; i < values.length; i++) {
            XWPFTableCell cell = row.getTableCells().get(i);
            CTP ctP = cell.getCTTc().sizeOfPArray() == 0 ? cell.getCTTc().addNewP() : cell.getCTTc().getPArray(0);
            XWPFParagraph par = cell.getParagraph(ctP);
            par.createRun().setText(values[i]);
            setCellStyle(cell);
        }

        // 插入图片
        if (data.getReportImgList() != null) {
            data.getReportImgList().stream()
                    .filter(img -> "0".equals(img.getImgType()))
                    .forEach(img -> insertImageToCell(row.getCell(8),
                            images.get(img.getImgSrc())));
        }
    }

    private void fillDataRowLingzhou(XWPFTableRow row, InspectionReportData data,
                                     Map<String, Path> tempFileMap) {
        String[] values = {
                String.valueOf(data.getCode()),
                data.getArea(),
                data.getEqName(),
                data.getParts(),
                data.getPointName(),
                data.getDataSources(),
                formatDateTime(data.getAcquisitionTime()),
                data.getInspectionResults(),
                data.getAlgName(),
                "" // 图片占位
        };

        for (int i = 0; i < values.length; i++) {
            XWPFTableCell cell = row.getTableCells().get(i);
            CTP ctP = cell.getCTTc().sizeOfPArray() == 0 ? cell.getCTTc().addNewP() : cell.getCTTc().getPArray(0);
            XWPFParagraph par = cell.getParagraph(ctP);
            par.createRun().setText(values[i]);
            setCellStyle(cell);
        }

        // 插入图片
        if (data.getReportImgList() != null) {
            data.getReportImgList().stream()
                    .filter(img -> "0".equals(img.getImgType()))
                    .forEach(img -> {
                        try {
                            insertImageToCell(row.getCell(9),
                                    Files.readAllBytes(tempFileMap.get(img.getImgSrc())));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    });
        }
    }

    private void fillQXDataRow(XWPFTableRow row, InspectionReportData data,
                               Map<String, byte[]> images) {
        String[] values = {
                String.valueOf(data.getCode()),
                data.getArea(),
                data.getEqName(),
                data.getParts(),
                data.getPointName(),
                data.getDataSources(),
                "", // 告警等级
                formatDateTime(data.getAcquisitionTime()),
                data.getInspectionResults(),
                data.getAlgName(),
                "" // 图片占位
        };

        for (int i = 0; i < values.length; i++) {
            XWPFTableCell cell = row.getTableCells().get(i);
            CTP ctP = cell.getCTTc().sizeOfPArray() == 0 ? cell.getCTTc().addNewP() : cell.getCTTc().getPArray(0);
            XWPFParagraph par = cell.getParagraph(ctP);
            par.createRun().setText(values[i]);
            setCellStyle(cell);
        }

        // 插入图片
        if (data.getReportImgList() != null) {
            data.getReportImgList().stream()
                    .filter(img -> "0".equals(img.getImgType()))
                    .forEach(img -> insertImageToCell(row.getCell(10),
                            images.get(img.getImgSrc())));
        }
    }

    private void fillNormalDataRow(XWPFTableRow row, InspectionReportData data,
                                   Map<String, byte[]> images) {
        String[] values = {
                String.valueOf(data.getCode()),
                data.getArea(),
                data.getEqName(),
                data.getParts(),
                data.getPointName(),
                data.getDataSources(),
                formatDateTime(data.getAcquisitionTime()),
                data.getInspectionResults(),
                data.getAlgName(),
                "" // 图片占位
        };

        for (int i = 0; i < values.length; i++) {
            XWPFTableCell cell = row.getTableCells().get(i);
            CTP ctP = cell.getCTTc().sizeOfPArray() == 0 ? cell.getCTTc().addNewP() : cell.getCTTc().getPArray(0);
            XWPFParagraph par = cell.getParagraph(ctP);
            par.createRun().setText(values[i]);
            setCellStyle(cell);
        }

        // 插入图片
        if (data.getReportImgList() != null) {
            data.getReportImgList().stream()
                    .filter(img -> "0".equals(img.getImgType()))
                    .forEach(img -> insertImageToCell(row.getCell(9),
                            images.get(img.getImgSrc())));
        }
    }

    private void insertImageToCell(XWPFTableCell cell, byte[] imageData) {
        if (imageData == null) return;

        try (ByteArrayInputStream bis = new ByteArrayInputStream(imageData)) {
            CTP ctP = cell.getCTTc().sizeOfPArray() == 0 ? cell.getCTTc().addNewP() : cell.getCTTc().getPArray(0);
            XWPFParagraph par = cell.getParagraph(ctP);
            XWPFRun run = par.createRun();
            run.addPicture(bis, XWPFDocument.PICTURE_TYPE_JPEG,
                    "image.jpg", Units.toEMU(100), Units.toEMU(100));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void setCellStyle(XWPFTableCell cell) {
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);

        XWPFParagraph para = cell.getParagraphs().get(0);
        para.setAlignment(ParagraphAlignment.CENTER);
        para.setSpacingAfter(0);
        para.setSpacingBefore(0);
        XWPFRun run = para.getRuns().isEmpty() ? para.createRun() : para.getRuns().get(0);
        run.setFontSize(9);
        run.setFontFamily("宋体");

    }

    private void addEmptyParagraph(XWPFDocument doc) {
        doc.createParagraph().createRun().addBreak();
    }

    private String formatDate(Date date) {
        return date != null ? DateUtils.format(DateUtils.yyyyMMdd2, date) : "";
    }

    private String formatDateTime(Date date) {
        return date != null ? DateUtils.format(DateUtils.yyyyMMddHHmmss2, date) : "";
    }


    public void exportToExcel(String lineId) {
        List<String> images = new ArrayList<>();
        InspectionReport inspectionReport =
                inspectionReportService.selectInspectionReportByLineId(Long.valueOf(lineId));
        InspectionReportData inspectionReportData = new InspectionReportData();
        inspectionReportData.setReportId(String.valueOf(inspectionReport.getLineId()));
        List<InspectionReportData> inspectionReportDataList =
                inspectionReportDataService.selectInspectionReportDataList(inspectionReportData);
        if (!inspectionReportDataList.isEmpty()) {
            inspectionReport.setReportDatalist(inspectionReportDataList);
        }

        for (InspectionReportData reportData : inspectionReportDataList) {
            InspectionReportImg inspectionReportImg = new InspectionReportImg();
            inspectionReportImg.setReportInfoId(reportData.getLineId());
            List<InspectionReportImg> reportImgList =
                    inspectionReportImgService.selectInspectionReportImgList(inspectionReportImg);
            reportData.setReportImgList(reportImgList);
            for (InspectionReportImg reportImg : reportImgList) {
                if (StringUtils.isNotEmpty(reportImg.getImgSrc()) && reportImg.getImgType().equals("0")) {
                    images.add(reportImg.getImgSrc());
                }
            }
        }

        Map<String, byte[]> streamHashMap = new HashMap<>();
        for (String algorithmBaseImagePath : images) {
            try {
                sftpClient.downLoad(algorithmBaseImagePath, (inputStream) -> {
                    byte[] bytes = streamHashMap.get(algorithmBaseImagePath);
                    byte[] byInputStream = getStringByInputStream(inputStream);
                    if (bytes == null) {
                        streamHashMap.put(algorithmBaseImagePath, byInputStream);
                    }

                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        HSSFWorkbook hssfWorkbook = getHSSFWorkbook(inspectionReport, streamHashMap);
        logger.info("[ARCHIVE] hssfWorkbook: {}", hssfWorkbook);
        try {
            String algorithmBaseImagePath = basePath + stationCode + "/Model/";
            SftpUploadEntity sftpUploadEntity = new SftpUploadEntity();
            sftpUploadEntity.setFilePath(algorithmBaseImagePath);
            Date startTime = inspectionReport.getInspectionStartTime() == null ?
                    new Date() :
                    inspectionReport.getInspectionStartTime();
            String date = DateUtils.format(DateUtils.yyyyMMddHHmmss2, startTime);
            sftpUploadEntity.setFileName(inspectionReport.getInspectionTaskName() + "_" + date + "_" + System.currentTimeMillis());
            sftpUploadEntity.setSuffix(".xls");
            String filePath = sftpClient.upload(sftpUploadEntity, (outputStream) -> {
                logger.info("[ARCHIVE] outputStream: {}", outputStream);
                hssfWorkbook.write(outputStream);
            });
            logger.info("[ARCHIVE] result filePath: {}", filePath);
            inspectionReport.setFilePath(filePath);
            inspectionReportService.updateInspectionReport(inspectionReport);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void exportExcelWordAndZip(String lineId) {
        List<String> images = new ArrayList<>();
        Map<String, String> imgSrcToFileNameMap = new HashMap<>();
        InspectionReport inspectionReport =
                inspectionReportService.selectInspectionReportByLineId(Long.valueOf(lineId));
        InspectionReportData inspectionReportData = new InspectionReportData();
        inspectionReportData.setReportId(String.valueOf(inspectionReport.getLineId()));
        List<InspectionReportData> inspectionReportDataList =
                inspectionReportDataService.selectInspectionReportDataList(inspectionReportData);
        if (!inspectionReportDataList.isEmpty()) {
            inspectionReport.setReportDatalist(inspectionReportDataList);
        } else {
            logger.info("--exportExcelWordAndZip------report lineId:{},filter:{} no report data!", lineId, inspectionReport.getFilter());
            return;
        }

        for (InspectionReportData reportData : inspectionReportDataList) {
            InspectionReportImg inspectionReportImg = new InspectionReportImg();
            inspectionReportImg.setReportInfoId(reportData.getLineId());
            List<InspectionReportImg> reportImgList =
                    inspectionReportImgService.selectInspectionReportImgList(inspectionReportImg);
            reportData.setReportImgList(reportImgList);

            int imgIndex = 1; // 每个报告数据项下的图片索引
            for (InspectionReportImg reportImg : reportImgList) {
                if (StringUtils.isNotEmpty(reportImg.getImgSrc()) && reportImg.getImgType().equals("0")) {
                    String originalImgSrc = reportImg.getImgSrc();
                    images.add(originalImgSrc);
                    String pointName = reportData.getPointName();
                    pointName = (pointName != null) ? pointName : "unnamed";
//                    PatrolResult patrolResult = patrolResultService.selectPatrolResultByDeviceName(pointName);
                    // 提取文件扩展名
                    String extension = "";
                    int dotIndex = originalImgSrc.lastIndexOf('.');
                    if (dotIndex > 0) {
                        extension = originalImgSrc.substring(dotIndex);
                    }

                    // 生成唯一文件名（包含 lineId 防止重复）
                    String uniqueFileName = String.format("%s_%s_%s_%d%s",
                            originalImgSrc.split("_")[2],
                            pointName,
                            reportData.getLineId(),
                            imgIndex,
                            extension);

                    imgSrcToFileNameMap.put(originalImgSrc, uniqueFileName);
                    imgIndex++;
                }
            }
        }

        Map<String, byte[]> streamHashMap = new HashMap<>();
        for (String algorithmBaseImagePath : images) {
            try {
                sftpClient.downLoad(algorithmBaseImagePath, (inputStream) -> {
                    byte[] bytes = streamHashMap.get(algorithmBaseImagePath);
                    byte[] byInputStream = getStringByInputStream(inputStream);
                    if (bytes == null) {
                        streamHashMap.put(algorithmBaseImagePath, byInputStream);
                    }

                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        images.parallelStream().forEach(imagePath -> {
//            byte[] shm = streamHashMap.get(imagePath);
//            byte[] bytes = downloadAndCompressImage(imagePath);
//            if (shm == null) {
//                streamHashMap.put(imagePath, bytes);
//            }
//        });


        SXSSFWorkbook sxssfWorkbook = getSXSSFWorkbook(inspectionReport, streamHashMap);
        XWPFDocument wordDocument = getXWPFDocument(inspectionReport, streamHashMap);
        logger.info("[ARCHIVE] hssfWorkbook: {}", sxssfWorkbook);
        try {
            String basePath = this.basePath + stationCode + "/Model/";
            Date startTime = inspectionReport.getInspectionStartTime() != null ?
                    inspectionReport.getInspectionStartTime() : new Date();
            String timestamp = DateUtils.format(DateUtils.yyyyMMddHHmmss2, startTime) + "_" + System.currentTimeMillis();
            String namePrefix = "";
            if ("1".equals(inspectionReport.getFilter())) {
                namePrefix = MessageUtils.get("初筛") + "_";
            } else if ("0".equals(inspectionReport.getFilter())) {
                namePrefix = MessageUtils.get("大模型") + "_";
            }
            String reportName = namePrefix + inspectionReport.getInspectionTaskName() + "_" + timestamp;
            // 上传媒体包
            CompletableFuture<Void> zipUploadFuture = CompletableFuture.runAsync(() -> {
                uploadFile(basePath, reportName, ".zip", outputStream -> {
                    try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
                        for (Map.Entry<String, byte[]> entry : streamHashMap.entrySet()) {
                            String imagePath = entry.getKey();
                            String pointFileName = imgSrcToFileNameMap.getOrDefault(imagePath, "unnamed");
                            byte[] imageData = entry.getValue();
//                            String fileName = new File(imagePath).getName();
                            ZipEntry zipEntry = new ZipEntry(pointFileName);
                            zipOut.putNextEntry(zipEntry);
                            zipOut.write(imageData);
                            zipOut.closeEntry();
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("生成ZIP文件失败", e);
                    }
                });
            }, executor);
            // 上传Excel
            CompletableFuture<Void> excelUploadFuture = CompletableFuture.runAsync(() -> {
                uploadFile(basePath, reportName, ".xls", sxssfWorkbook::write);
            }, executor);
            // 上传Word
            CompletableFuture<Void> wordUploadFuture = CompletableFuture.runAsync(() -> {
                uploadFile(basePath, reportName, ".docx", wordDocument::write);
            }, executor);
            CompletableFuture.allOf(zipUploadFuture, excelUploadFuture, wordUploadFuture).whenComplete((v, t) -> {
                inspectionReport.setFilePath(basePath + reportName + ".xls");
                inspectionReportService.updateInspectionReport(inspectionReport);
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void exportExcelWordAndZipLingzhou(String lineId) {
        List<String> images = new ArrayList<>();
        Map<String, String> imgSrcToFileNameMap = new HashMap<>();
        InspectionReport inspectionReport =
                inspectionReportService.selectInspectionReportByLineId(Long.valueOf(lineId));
        InspectionReportData inspectionReportData = new InspectionReportData();
        inspectionReportData.setReportId(String.valueOf(inspectionReport.getLineId()));
        List<InspectionReportData> inspectionReportDataList =
                inspectionReportDataService.selectInspectionReportDataList(inspectionReportData);
        if (!inspectionReportDataList.isEmpty()) {
            inspectionReport.setReportDatalist(inspectionReportDataList);
        } else {
            logger.info("--exportExcelWordAndZip------report lineId:{},filter:{} no report data!", lineId, inspectionReport.getFilter());
            return;
        }

        for (InspectionReportData reportData : inspectionReportDataList) {
            InspectionReportImg inspectionReportImg = new InspectionReportImg();
            inspectionReportImg.setReportInfoId(reportData.getLineId());
            List<InspectionReportImg> reportImgList =
                    inspectionReportImgService.selectInspectionReportImgList(inspectionReportImg);
            reportData.setReportImgList(reportImgList);

            int imgIndex = 1; // 每个报告数据项下的图片索引
            for (InspectionReportImg reportImg : reportImgList) {
                if (StringUtils.isNotEmpty(reportImg.getImgSrc()) && reportImg.getImgType().equals("0")) {
                    // /2/2026/06/21/1670/CCD/1670_20260621140000_2023923_02160558348953680127.jpg
                    String originalImgSrc = reportImg.getImgSrc();
                    images.add(originalImgSrc);
                    String pointName = reportData.getPointName();
                    pointName = (pointName != null) ? pointName : "unnamed";
                    // 提取文件扩展名
                    String extension = "";
                    int dotIndex = originalImgSrc.lastIndexOf('.');
                    if (dotIndex > 0) {
                        extension = originalImgSrc.substring(dotIndex);
                    }

                    // 生成唯一文件名（包含 lineId 防止重复）
                    // 2023923_极Ⅱ低Y/Y-A相换流变油面温度1_3212_100097_1.jpg
                    String uniqueFileName = String.format("%s_%s_%s_%d%s",
                            originalImgSrc.split("_")[2],
                            pointName.replaceAll("[\\\\/:*?\"<>|]", "")
                                    .replaceAll("\\s+", ""),  // 空格,
                            reportData.getLineId(),
                            imgIndex,
                            extension);

                    imgSrcToFileNameMap.put(originalImgSrc, uniqueFileName);
                    imgIndex++;
                }
            }
        }

        // 将图片下载到临时文件，避免大量图片字节数据全部驻留内存
        Map<String, Path> tempFileMap = new LinkedHashMap<>();
        List<Path> tempFiles = new ArrayList<>();
        for (String imgSrc : images) {
            try {
                Path tempFile = downloadImageToTemp(imgSrc);
                if (tempFile != null) {
                    tempFileMap.put(imgSrc, tempFile);
                    tempFiles.add(tempFile);
                }
            } catch (Exception e) {
                logger.warn("报告归档下载图片失败: {}", imgSrc, e);
            }
        }

        // 懒加载适配：按需从临时文件读取图片字节，读取后调用方使用完毕即被GC回收
        Map<String, byte[]> streamHashMap = new AbstractMap<String, byte[]>() {
            @Override
            public byte[] get(Object key) {
                Path path = tempFileMap.get(key);
                if (path == null) return null;
                try {
                    return Files.readAllBytes(path);
                } catch (IOException e) {
                    logger.warn("读取临时图片文件失败: {}", path, e);
                    return null;
                }
            }

            @Override
            public boolean containsKey(Object key) {
                return tempFileMap.containsKey(key);
            }

            @Override
            public Set<Entry<String, byte[]>> entrySet() {
                throw new UnsupportedOperationException();
            }

            @Override
            public int size() {
                return tempFileMap.size();
            }
        };
        logMemoryUsage("AFTER_IMAGE_DOWNLOAD");

        SXSSFWorkbook sxssfWorkbook = null;
        XWPFDocument wordDocument = null;

        try {
            sxssfWorkbook = getSXSSFWorkbookLingzhou(inspectionReport, streamHashMap);
            wordDocument = getXWPFDocumentLingzhou(inspectionReport, tempFileMap);
            String basePath = this.basePath + stationCode + "/Model/";
            Date startTime = inspectionReport.getInspectionStartTime() != null ?
                    inspectionReport.getInspectionStartTime() : new Date();
            String timestamp = DateUtils.format(DateUtils.yyyyMMddHHmmss2, startTime) + "_" + System.currentTimeMillis();
            String namePrefix = "";
            if ("1".equals(inspectionReport.getFilter())) {
                namePrefix = MessageUtils.get("初筛") + "_";
            } else if ("0".equals(inspectionReport.getFilter())) {
                namePrefix = MessageUtils.get("大模型") + "_";
            }
            String reportName = namePrefix + timestamp;
            // 上传媒体包（直接从临时文件流式写入ZIP，不加载到内存）
            CompletableFuture<Void> zipUploadFuture = CompletableFuture.runAsync(() -> {
                uploadFile(basePath, reportName, ".zip", outputStream -> {
                    try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
                        for (Map.Entry<String, Path> entry : tempFileMap.entrySet()) {
                            String imagePath = entry.getKey();
                            String pointFileName = imgSrcToFileNameMap.getOrDefault(imagePath, "unnamed");
                            Path tempFile = entry.getValue();
                            ZipEntry zipEntry = new ZipEntry(pointFileName);
                            zipOut.putNextEntry(zipEntry);
                            Files.copy(tempFile, zipOut);
                            zipOut.closeEntry();
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("生成ZIP文件失败", e);
                    }
                });
            }, executor);
            logMemoryUsage("AFTER_ZIP_UPLOAD");

            // 上传Excel
            SXSSFWorkbook finalSxssfWorkbook = sxssfWorkbook;
            CompletableFuture<Void> excelUploadFuture = CompletableFuture.runAsync(() -> {
                uploadFile(basePath, reportName, ".xls", finalSxssfWorkbook::write);
            }, executor);

            // 上传Word
            XWPFDocument finalWordDocument = wordDocument;
            CompletableFuture<Void> wordUploadFuture = CompletableFuture.runAsync(() -> {
                uploadFile(basePath, reportName, ".docx", finalWordDocument::write);
            }, executor);
            logMemoryUsage("AFTER_WORD_UPLOAD");

            CompletableFuture.allOf(zipUploadFuture, excelUploadFuture, wordUploadFuture).whenComplete((v, t) -> {
                try {
                    inspectionReport.setFilePath(basePath + reportName + ".xls");
                    inspectionReportService.updateInspectionReport(inspectionReport);
                } finally {
                    // 清理资源
                    closeResources(finalSxssfWorkbook, finalWordDocument, tempFiles);
                }
            });
        } catch (Exception e) {
            // 清理资源
            closeResources(sxssfWorkbook, wordDocument, tempFiles);
            e.printStackTrace();
        }
    }

    public void exportExcelWordAndZipShaoxing(String lineId) {
        logMemoryUsage("START exportExcelWordAndZipShaoxing");
        List<String> images = new ArrayList<>();
        Map<String, String> imgSrcToFileNameMap = new HashMap<>();
        InspectionReport inspectionReport =
                inspectionReportService.selectInspectionReportByLineId(Long.valueOf(lineId));
        InspectionReportData inspectionReportData = new InspectionReportData();
        inspectionReportData.setReportId(String.valueOf(inspectionReport.getLineId()));
        List<InspectionReportData> inspectionReportDataList =
                inspectionReportDataService.selectInspectionReportDataList(inspectionReportData);
        if (!inspectionReportDataList.isEmpty()) {
            inspectionReport.setReportDatalist(inspectionReportDataList);
        } else {
            logger.info("--exportExcelWordAndZip------report lineId:{},filter:{} no report data!", lineId, inspectionReport.getFilter());
            return;
        }

        for (InspectionReportData reportData : inspectionReportDataList) {
            InspectionReportImg inspectionReportImg = new InspectionReportImg();
            inspectionReportImg.setReportInfoId(reportData.getLineId());
            List<InspectionReportImg> reportImgList =
                    inspectionReportImgService.selectInspectionReportImgList(inspectionReportImg);
            reportData.setReportImgList(reportImgList);

            int imgIndex = 1; // 每个报告数据项下的图片索引
            for (InspectionReportImg reportImg : reportImgList) {
                if (StringUtils.isNotEmpty(reportImg.getImgSrc()) && reportImg.getImgType().equals("0")) {
                    // /2/2026/06/21/1670/CCD/1670_20260621140000_2023923_02160558348953680127.jpg
                    String originalImgSrc = reportImg.getImgSrc();
                    images.add(originalImgSrc);
                    String pointName = reportData.getPointName();
                    pointName = (pointName != null) ? pointName : "unnamed";
                    // 提取文件扩展名
                    String extension = "";
                    int dotIndex = originalImgSrc.lastIndexOf('.');
                    if (dotIndex > 0) {
                        extension = originalImgSrc.substring(dotIndex);
                    }

                    // 生成唯一文件名（包含 lineId 防止重复）
                    // 2023923_极Ⅱ低Y/Y-A相换流变油面温度1_3212_100097_1.jpg
                    String uniqueFileName = String.format("%s_%s_%s_%d%s",
                            originalImgSrc.split("_")[2],
                            pointName.replaceAll("[\\\\/:*?\"<>|]", "")
                                    .replaceAll("\\s+", ""),  // 空格,
                            reportData.getLineId(),
                            imgIndex,
                            extension);

                    imgSrcToFileNameMap.put(originalImgSrc, uniqueFileName);
                    imgIndex++;
                }
            }
        }

        // 将图片下载到临时文件，避免大量图片字节数据全部驻留内存
        Map<String, Path> tempFileMap = new LinkedHashMap<>();
        List<Path> tempFiles = new ArrayList<>();
        for (String imgSrc : images) {
            try {
                Path tempFile = downloadImageToTemp(imgSrc);
                if (tempFile != null) {
                    tempFileMap.put(imgSrc, tempFile);
                    tempFiles.add(tempFile);
                }
            } catch (Exception e) {
                logger.warn("报告归档下载图片失败: {}", imgSrc, e);
            }
        }

        logMemoryUsage("AFTER_IMAGE_DOWNLOAD");

        SXSSFWorkbook sxssfWorkbook = null;
        XWPFDocument wordDocument = null;
        logger.info("[ARCHIVE] hssfWorkbook: {}", sxssfWorkbook);

        try {
            sxssfWorkbook = getSXSSFWorkbookShaoxing(inspectionReport, tempFileMap);
            logMemoryUsage("AFTER_EXCEL_CREATE");

            wordDocument = getXWPFDocumentLingzhou(inspectionReport, tempFileMap);
            logMemoryUsage("AFTER_WORD_CREATE");

            String basePath = this.basePath + stationCode + "/Model/";
            Date startTime = inspectionReport.getInspectionStartTime() != null ?
                    inspectionReport.getInspectionStartTime() : new Date();
            String timestamp = DateUtils.format(DateUtils.yyyyMMddHHmmss2, startTime) + "_" + System.currentTimeMillis();
            String namePrefix = "";
            if ("1".equals(inspectionReport.getFilter())) {
                namePrefix = MessageUtils.get("初筛") + "_";
            } else if ("0".equals(inspectionReport.getFilter())) {
                namePrefix = MessageUtils.get("大模型") + "_";
            }

            String reportName = inspectionReport.getInspectionTaskName() + "_" + timestamp;

            // 上传媒体包（直接从临时文件流式写入ZIP，不加载到内存）
            CompletableFuture<Void> zipUploadFuture = CompletableFuture.runAsync(() -> {
                uploadFile(basePath, reportName, ".zip", outputStream -> {
                    try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
                        for (Map.Entry<String, Path> entry : tempFileMap.entrySet()) {
                            String imagePath = entry.getKey();
                            String pointFileName = imgSrcToFileNameMap.getOrDefault(imagePath, "unnamed");
                            Path tempFile = entry.getValue();
                            ZipEntry zipEntry = new ZipEntry(pointFileName);
                            zipOut.putNextEntry(zipEntry);
                            Files.copy(tempFile, zipOut);
                            zipOut.closeEntry();
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("生成ZIP文件失败", e);
                    }
                });
            }, executor);
            logMemoryUsage("AFTER_ZIP_UPLOAD");

            // 上传Excel
            SXSSFWorkbook finalSxssfWorkbook = sxssfWorkbook;
            CompletableFuture<Void> excelUploadFuture = CompletableFuture.runAsync(() -> {
                uploadFile(basePath, reportName, ".xls", finalSxssfWorkbook::write);
            }, executor);
            logMemoryUsage("AFTER_EXCEL_UPLOAD");

            // 上传Word
            XWPFDocument finalWordDocument = wordDocument;
            CompletableFuture<Void> wordUploadFuture = CompletableFuture.runAsync(() -> {
                uploadFile(basePath, reportName, ".docx", finalWordDocument::write);
            }, executor);
            logMemoryUsage("AFTER_WORD_UPLOAD");

            CompletableFuture.allOf(zipUploadFuture, excelUploadFuture, wordUploadFuture).whenComplete((v, t) -> {
                try {
                    inspectionReport.setFilePath(basePath + reportName + ".xls");
                    inspectionReportService.updateInspectionReport(inspectionReport);
                } finally {
                    closeResources(finalSxssfWorkbook, finalWordDocument, tempFiles);
                }
            });

        } catch (Exception e) {
            logger.error("生成巡视文件异常：{}", e);
            closeResources(sxssfWorkbook, wordDocument, tempFiles);
        }
        logMemoryUsage("END exportExcelWordAndZipShaoxing");
    }




    private void closeResources(SXSSFWorkbook sxssfWorkbook, XWPFDocument wordDocument, List<Path> tempFiles) {
        // 清理资源
        // 关闭 Excel
        if (sxssfWorkbook != null) {
            try {
                sxssfWorkbook.close();
                logger.info("SXSSFWorkbook 已关闭");
            } catch (IOException e) {
                logger.error("关闭SXSSFWorkbook失败", e);
            }
        }
        if (wordDocument != null) {
            try {
                wordDocument.close();
                logger.info("XWPFDocument 已关闭");
            } catch (IOException e) {
                logger.error("关闭XWPFDocument失败", e);
            }
        }

        for (Path tempFile : tempFiles) {
            try {
                Files.deleteIfExists(tempFile);
            } catch (IOException e) {
                logger.warn("删除临时文件失败: {}", tempFile, e);
            }
        }
    }

    /**
     * 下载图片并保存到临时文件，避免内存中持有大量图片字节数据
     */
    private Path downloadImageToTemp(String imagePath) {
        try {
            Path tempFile = Files.createTempFile("inspect_img_", ".jpg");
            sftpClient.downLoad(imagePath, inputStream -> {
                Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
            });
            return tempFile;
        } catch (Exception e) {
            logger.warn("图片下载到临时文件失败: {}", imagePath, e);
            return null;
        }
    }

    private void logMemoryUsage(String stage) {
        Runtime runtime = Runtime.getRuntime();
        long maxMemory = runtime.maxMemory() / (1024 * 1024);
        long totalMemory = runtime.totalMemory() / (1024 * 1024);
        long freeMemory = runtime.freeMemory() / (1024 * 1024);
        long usedMemory = totalMemory - freeMemory;

        logger.info("[MEMORY] Stage: {}, Max: {}MB, Total: {}MB, Used: {}MB, Free: {}MB",
                stage, maxMemory, totalMemory, usedMemory, freeMemory);
    }

    private byte[] downloadAndCompressImage(String imagePath) {
        try {
            // 直接下载并压缩图片
            logger.info("-----开始下载并压缩图片: {}", imagePath);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            sftpClient.downLoad(imagePath, inputStream -> {
                // 压缩图片
                Thumbnails.of(inputStream)
                        .size(300, 300) // 限制最大尺寸
                        .outputQuality(0.5) // 50%质量
                        .outputFormat("JPEG")
                        .toOutputStream(output);
            });
            return output.toByteArray();
        } catch (Exception e) {
            logger.warn("图片下载压缩失败: {}", imagePath, e);
            return null;
        }
    }

    /**
     * 上传文件到SFTP服务器
     *
     * @param basePath 文件上传的基础路径
     * @param fileName 文件名
     * @param suffix   文件后缀
     * @param writer   文件写入器，用于将文件内容写入到输出流中
     * @throws Exception 如果上传过程中发生异常，则抛出异常
     */
    private void uploadFile(String basePath, String fileName, String suffix, IOConsumer<OutputStream> writer) {
        SftpUploadEntity sftpUploadEntity = new SftpUploadEntity();
        sftpUploadEntity.setFilePath(basePath);
        sftpUploadEntity.setFileName(fileName);
        sftpUploadEntity.setSuffix(suffix);

        try {
            String filePath = sftpClient.upload(sftpUploadEntity, outputStream -> {
                writer.accept(outputStream);
                outputStream.flush();
            });
            logger.info("文件上传成功: {}", filePath);
        } catch (Exception e) {
            logger.error("文件上传失败", e);
        }
    }

    public HSSFWorkbook getHSSFWorkbook(InspectionReport inspectionReport, Map<String, byte[]> inputStreamMap) {
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        HSSFSheet hssfSheet = hssfWorkbook.createSheet(String.valueOf(System.currentTimeMillis()));
        hssfSheet.setDefaultColumnWidth(20);
        HSSFCellStyle colStyle = createCellStyle(hssfWorkbook, (short) 15, true, true);
        HSSFCellStyle colStyle2 = createCellStylenoborder(hssfWorkbook, (short) 15, true, true);
        HSSFCellStyle colRight = getColRight(hssfWorkbook, (short) 10, true, false);
        CellRangeAddress callRangeAddress01 = new CellRangeAddress(0, 0, 0, 14);
        CellRangeAddress callRangeAddress02 = new CellRangeAddress(1, 1, 0, 3);
        CellRangeAddress callRangeAddress03 = new CellRangeAddress(1, 1, 4, 7);
        CellRangeAddress callRangeAddress04 = new CellRangeAddress(1, 1, 8, 11);
        CellRangeAddress callRangeAddress05 = new CellRangeAddress(1, 1, 12, 14);
        CellRangeAddress callRangeAddress21 = new CellRangeAddress(2, 2, 0, 3);
        CellRangeAddress callRangeAddress22 = new CellRangeAddress(2, 2, 4, 7);
        CellRangeAddress callRangeAddress23 = new CellRangeAddress(2, 2, 8, 11);
        CellRangeAddress callRangeAddress24 = new CellRangeAddress(2, 2, 12, 14);
        CellRangeAddress callRangeAddress31 = new CellRangeAddress(3, 3, 0, 3);
        CellRangeAddress callRangeAddress32 = new CellRangeAddress(3, 3, 4, 7);
        CellRangeAddress callRangeAddress33 = new CellRangeAddress(3, 3, 8, 11);
        CellRangeAddress callRangeAddress34 = new CellRangeAddress(3, 3, 12, 14);
        CellRangeAddress callRangeAddress41 = new CellRangeAddress(4, 4, 0, 3);
        CellRangeAddress callRangeAddress42 = new CellRangeAddress(4, 4, 4, 7);
        CellRangeAddress callRangeAddress43 = new CellRangeAddress(4, 4, 8, 11);
        CellRangeAddress callRangeAddress44 = new CellRangeAddress(4, 4, 12, 14);
        CellRangeAddress callRangeAddress51 = new CellRangeAddress(5, 5, 0, 3);
        CellRangeAddress callRangeAddress52 = new CellRangeAddress(5, 5, 4, 7);
        CellRangeAddress callRangeAddress53 = new CellRangeAddress(5, 5, 8, 11);
        CellRangeAddress callRangeAddress54 = new CellRangeAddress(5, 5, 12, 14);
        CellRangeAddress callRangeAddress61 = new CellRangeAddress(6, 7, 0, 3);
        CellRangeAddress callRangeAddress62 = new CellRangeAddress(6, 7, 4, 14);
        CellRangeAddress callRangeAddress71 = new CellRangeAddress(8, 8, 0, 3);
        CellRangeAddress callRangeAddress72 = new CellRangeAddress(8, 8, 4, 14);
        hssfSheet.addMergedRegion(callRangeAddress01);
        hssfSheet.addMergedRegion(callRangeAddress02);
        hssfSheet.addMergedRegion(callRangeAddress03);
        hssfSheet.addMergedRegion(callRangeAddress04);
        hssfSheet.addMergedRegion(callRangeAddress05);
        hssfSheet.addMergedRegion(callRangeAddress21);
        hssfSheet.addMergedRegion(callRangeAddress22);
        hssfSheet.addMergedRegion(callRangeAddress23);
        hssfSheet.addMergedRegion(callRangeAddress24);
        hssfSheet.addMergedRegion(callRangeAddress31);
        hssfSheet.addMergedRegion(callRangeAddress32);
        hssfSheet.addMergedRegion(callRangeAddress33);
        hssfSheet.addMergedRegion(callRangeAddress34);
        hssfSheet.addMergedRegion(callRangeAddress41);
        hssfSheet.addMergedRegion(callRangeAddress42);
        hssfSheet.addMergedRegion(callRangeAddress43);
        hssfSheet.addMergedRegion(callRangeAddress44);
        hssfSheet.addMergedRegion(callRangeAddress51);
        hssfSheet.addMergedRegion(callRangeAddress52);
        hssfSheet.addMergedRegion(callRangeAddress53);
        hssfSheet.addMergedRegion(callRangeAddress54);
        hssfSheet.addMergedRegion(callRangeAddress61);
        hssfSheet.addMergedRegion(callRangeAddress62);
        hssfSheet.addMergedRegion(callRangeAddress71);
        hssfSheet.addMergedRegion(callRangeAddress72);
        HSSFRow hssRow = hssfSheet.createRow(0);
        hssRow.setHeight((short) 600);
        HSSFCell cell0 = hssRow.createCell(0);
        cell0.setCellValue(MessageUtils.get("巡视报告"));
        HSSFCellStyle hssfCellStyle = hssfWorkbook.createCellStyle();
        hssfCellStyle.setAlignment(HorizontalAlignment.CENTER);
        hssfCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        HSSFFont font = hssfWorkbook.createFont();
        font.setFontHeightInPoints((short) 20);
        font.setFontHeight((short) 500);
        font.setBold(true);
        hssfCellStyle.setFont(font);
        cell0.setCellStyle(hssfCellStyle);
        HSSFRow row1 = hssfSheet.createRow(1);
        HSSFCell cell11 = row1.createCell(0);
        cell11.setCellValue(MessageUtils.get("变电站"));
        cell11.setCellStyle(colStyle2);
        HSSFCell cell12 = row1.createCell(4);
        cell12.setCellValue(inspectionReport.getStationName());
        cell12.setCellStyle(colStyle2);
        HSSFCell cell13 = row1.createCell(8);
        cell13.setCellValue(MessageUtils.get("电压等级"));
        cell13.setCellStyle(colStyle2);
        HSSFCell cell14 = row1.createCell(12);
        cell14.setCellValue(inspectionReport.getVoltLevel());
        cell14.setCellStyle(colStyle2);
        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = row1.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        HSSFRow hssfRow2 = hssfSheet.createRow(2);
        HSSFCell cell21 = hssfRow2.createCell(0);
        cell21.setCellValue(MessageUtils.get("巡视计划创建日期"));
        cell21.setCellStyle(colStyle2);
        HSSFCell cell22 = hssfRow2.createCell(4);
        if (inspectionReport.getInspectionDate() != null) {
            cell22.setCellValue(DateUtils.format(DateUtils.yyyyMMdd2, inspectionReport.getInspectionDate()));
        }

        cell22.setCellStyle(colStyle2);
        HSSFCell cell23 = hssfRow2.createCell(8);
        cell23.setCellValue(MessageUtils.get("变电站类别"));
        cell23.setCellStyle(colStyle2);
        HSSFCell cell24 = hssfRow2.createCell(12);
        cell24.setCellValue(inspectionReport.getStationType());
        cell24.setCellStyle(colStyle2);

        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = hssfRow2.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        HSSFRow hssfRow3 = hssfSheet.createRow(3);
        HSSFCell cell31 = hssfRow3.createCell(0);
        cell31.setCellValue(MessageUtils.get("巡视任务"));
        cell31.setCellStyle(colStyle2);
        HSSFCell cell32 = hssfRow3.createCell(4);
        cell32.setCellValue(inspectionReport.getInspectionTaskName());
        cell32.setCellStyle(colStyle2);
        HSSFCell cell33 = hssfRow3.createCell(8);
        cell33.setCellValue(MessageUtils.get("环境信息"));
        cell33.setCellStyle(colStyle2);
        HSSFCell cell34 = hssfRow3.createCell(12);
        cell34.setCellValue(inspectionReport.getEnvInfo());
        cell34.setCellStyle(colStyle2);
        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = hssfRow3.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        HSSFRow hssfRow4 = hssfSheet.createRow(4);
        HSSFCell cell41 = hssfRow4.createCell(0);
        cell41.setCellValue(MessageUtils.get("审核人"));
        cell41.setCellStyle(colStyle2);
        HSSFCell cell42 = hssfRow4.createCell(4);
        cell42.setCellValue(inspectionReport.getCheckPerson());
        cell42.setCellStyle(colStyle2);
        HSSFCell cell43 = hssfRow4.createCell(8);
        cell43.setCellValue(MessageUtils.get("审核时间"));
        cell43.setCellStyle(colStyle2);
        HSSFCell cell44 = hssfRow4.createCell(12);
        cell44.setCellValue(DateUtils.format(DateUtils.yyyyMMddHHmmss2, inspectionReport.getCheckTime()));
        cell44.setCellStyle(colStyle2);

        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = hssfRow4.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        HSSFRow hssfRow5 = hssfSheet.createRow(5);
        HSSFCell cell51 = hssfRow5.createCell(0);
        cell51.setCellValue(MessageUtils.get("巡视开始时间"));
        cell51.setCellStyle(colStyle2);
        HSSFCell cell52 = hssfRow5.createCell(4);
        if (inspectionReport.getInspectionStartTime() != null) {
            cell52.setCellValue(DateUtils.format(DateUtils.yyyyMMddHHmmss2, inspectionReport.getInspectionStartTime()));
        }

        cell52.setCellStyle(colStyle2);
        HSSFCell cell53 = hssfRow5.createCell(8);
        cell53.setCellValue(MessageUtils.get("巡视结束时间"));
        cell53.setCellStyle(colStyle2);
        HSSFCell cell54 = hssfRow5.createCell(12);
        if (inspectionReport.getInspectionEndTime() != null) {
            cell54.setCellValue(DateUtils.format(DateUtils.yyyyMMddHHmmss2, inspectionReport.getInspectionEndTime()));
        }

        cell54.setCellStyle(colStyle2);

        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = hssfRow5.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        HSSFRow hssfRow6 = hssfSheet.createRow(6);
        hssfRow6.setHeight((short) 1000);
        HSSFCell cell61 = hssfRow6.createCell(0);
        cell61.setCellValue(MessageUtils.get("巡视统计"));
        cell61.setCellStyle(colStyle2);
        HSSFCell cell62 = hssfRow6.createCell(4);
        cell62.setCellValue(inspectionReport.getPatrolStatistics());
        cell62.setCellStyle(colStyle2);

        int i;
        for (i = 0; i < 15; ++i) {
            if (i != 0 && i != 4) {
                cell14 = hssfRow6.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        hssfRow6 = hssfSheet.createRow(7);

        for (i = 0; i < 15; ++i) {
            cell14 = hssfRow6.createCell(i);
            cell14.setCellStyle(colStyle2);
        }

        HSSFRow hssfRow7 = hssfSheet.createRow(8);
        hssfRow7.setHeight((short) 1000);
        HSSFCell cell71 = hssfRow7.createCell(0);
        cell71.setCellValue(MessageUtils.get("巡视结论"));
        cell71.setCellStyle(colStyle2);
        HSSFCell cell72 = hssfRow7.createCell(4);
        cell72.setCellValue(inspectionReport.getDescription());
        cell72.setCellStyle(colStyle2);

        for (int j = 0; j < 15; ++j) {
            if (j != 0 && j != 4) {
                cell14 = hssfRow7.createCell(j);
                cell14.setCellStyle(colStyle2);
            }
        }

//        InspectionReportData inspectionReportData = new InspectionReportData();
//        List<InspectionReportData> list = new ArrayList<>();
//        inspectionReportData.setPointStatus(MessageUtils.get("异常"));
//        list.add(inspectionReportData);
//        InspectionReportData inspection = new InspectionReportData();
//        inspection.setPointStatus(MessageUtils.get("待人工确认"));
//        list.add(inspection);
//        InspectionReportData reportData = new InspectionReportData();
//        reportData.setPointStatus(MessageUtils.get("正常"));
//        list.add(reportData);
        InspectionReportData inspectionReportData = new InspectionReportData();
        List<InspectionReportData> list = new ArrayList<>();
        inspectionReportData.setPointStatus(MessageUtils.get("缺陷"));
        list.add(inspectionReportData);
        int total = 0;
        HSSFPatriarch patriarch = hssfSheet.createDrawingPatriarch();

        label190:
        for (Iterator<InspectionReportData> iterator = list.iterator(); iterator.hasNext(); total += 2) {
            InspectionReportData arr = iterator.next();
            CellRangeAddress cellRangeAddress = new CellRangeAddress(9 + total, 9 + total, 0, 14);
            hssfSheet.addMergedRegion(cellRangeAddress);
            HSSFRow rowa1 = hssfSheet.createRow(9 + total);
            HSSFCell cella1 = rowa1.createCell(0);
            cella1.setCellValue(arr.getPointStatus() + MessageUtils.get("汇总"));
            HSSFCellStyle hssfCellStyle1 = hssfWorkbook.createCellStyle();
            hssfCellStyle1.setAlignment(HorizontalAlignment.CENTER);
            hssfCellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);
            HSSFFont hssfWorkbookFont = hssfWorkbook.createFont();
            hssfWorkbookFont.setFontHeightInPoints((short) 20);//qinyl
            hssfCellStyle1.setFont(hssfWorkbookFont);
            cella1.setCellStyle(hssfCellStyle1);

            //qinyl
            for (int j = 0; j < 15; ++j) {
                if (j != 0) {
                    cell14 = rowa1.createCell(j);
                    cell14.setCellStyle(colStyle2);
                }
            }

            CellRangeAddress callRangeAddress2 = new CellRangeAddress(10 + total, 10 + total, 12, 14);
            hssfSheet.addMergedRegion(callRangeAddress2);
            rowa1 = hssfSheet.createRow(10 + total);
            hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total, 2, 4));
            hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total, 5, 6));
            hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total, 9, 10));
            cella1 = rowa1.createCell(0);
            cella1.setCellValue(MessageUtils.get("编号"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(1);
            cella1.setCellValue(MessageUtils.get("区域"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(2);
            cella1.setCellValue(MessageUtils.get("设备"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(3);
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(4);
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(5);
            cella1.setCellValue(MessageUtils.get("点位"));
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(6);
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(7);
            cella1.setCellValue(MessageUtils.get("数据来源"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(8);
            cella1.setCellValue(MessageUtils.get("采集时间"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(9);
            cella1.setCellValue(MessageUtils.get("巡视结果"));
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(10);
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(11);
            cella1.setCellValue(MessageUtils.get("算法类型"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(12);
            cella1.setCellValue(MessageUtils.get("巡视图像"));
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(13);
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(14);
            cella1.setCellStyle(colStyle);
            InspectionReportData reportData1 = new InspectionReportData();
            reportData1.setReportId(inspectionReport.getLineId() + "");
            reportData1.setPointStatus(arr.getPointStatus());
            List objectArrayList = new ArrayList<>();
            if (inspectionReport.getReportDatalist() != null && !inspectionReport.getReportDatalist().isEmpty()) {
                objectArrayList = inspectionReport.getReportDatalist();
                logger.info("[HSSF] STATISTICS RECORD Number: {}, Origin Number: {}", objectArrayList.size(), inspectionReport.getReportDatalist().size());
            }

            Iterator iterator1 = objectArrayList.iterator();
            while (true) {
                while (true) {
                    if (!iterator1.hasNext()) {
                        continue label190;
                    }

                    InspectionReportData brr = (InspectionReportData) iterator1.next();
                    ++total;
                    InspectionReportImg inspectionReportImg = new InspectionReportImg();
                    inspectionReportImg.setReportInfoId(brr.getLineId());
                    List<InspectionReportImg> imgList = new ArrayList<>();
                    if (brr.getReportImgList() != null && !brr.getReportImgList().isEmpty()) {
                        imgList = brr.getReportImgList();
                    }

                    CellRangeAddress cellRangeAddress1 = new CellRangeAddress(10 + total, 10 + total, 12, 14);
                    hssfSheet.addMergedRegion(cellRangeAddress1);
                    HSSFRow rowb1 = hssfSheet.createRow(10 + total);
                    if (!imgList.isEmpty()) {
                        rowb1.setHeight((short) 1000);
                    }

                    cella1 = rowb1.createCell(0);
                    cella1.setCellValue((double) brr.getCode());
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(1);
                    cella1.setCellValue(brr.getArea());
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(2);
                    cella1.setCellValue(brr.getEqName());
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(3);
                    cella1.setCellValue(brr.getEqName());
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(4);
                    cella1.setCellValue(brr.getParts());
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(5);
                    cella1.setCellValue(brr.getPointName());
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(6);
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(7);
                    cella1.setCellValue(brr.getDataSources());
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(8);
                    if (brr.getAcquisitionTime() != null) {
                        cella1.setCellValue(DateUtils.format(DateUtils.yyyyMMddHHmmss2, brr.getAcquisitionTime()));
                    }

                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(9);
                    cella1.setCellValue(brr.getInspectionResults());
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(10);
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(11);
                    cella1.setCellValue(brr.getAlgName());
                    cella1.setCellStyle(colStyle2);
                    String str = "";
                    cella1 = rowb1.createCell(12);
                    cella1.setCellValue(str);
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(13);
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(14);
                    cella1.setCellStyle(colStyle);
                    if (!imgList.isEmpty()) {
                        hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 0, 0));
                        hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 1, 1));
                        hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 2, 4));
                        hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 5, 6));
                        hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 7, 7));
                        hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 8, 8));
                        hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 9, 10));
                        hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 11, 11));

                        for (InspectionReportImg o : imgList) {
                            ++total;
                            CellRangeAddress cellRangeAddress2 = new CellRangeAddress(10 + total, 10 + total, 12, 14);
                            hssfSheet.addMergedRegion(cellRangeAddress2);
                            rowb1 = hssfSheet.createRow(10 + total);
                            rowb1.setHeight((short) 1000);
                            cella1 = rowb1.createCell(0);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(1);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(2);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(3);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(4);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(5);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(6);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(7);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(8);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(9);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(10);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(11);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(12);
                            if (o.getImgType().equals("0")) {
                                try {
                                    insertImage(hssfWorkbook, patriarch, images(o.getImg(), inputStreamMap), 10 + total, 0, 2);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                String sheetName = o.getImgSrc();
                                cella1.setCellFormula("HYPERLINK(\"" + sheetName + "\")");
                                cella1.setCellStyle(colRight);
                            }

                            cella1 = rowb1.createCell(13);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(14);
                            cella1.setCellStyle(colStyle);
                        }
                    } else {
                        hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total, 2, 4));
                        hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total, 5, 6));
                        hssfSheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total, 9, 10));
                    }
                }
            }
        }

        return hssfWorkbook;
    }

    public SXSSFWorkbook getSXSSFWorkbook(InspectionReport inspectionReport, Map<String, byte[]> inputStreamMap) {
        // 使用SXSSFWorkbook并设置行访问窗口大小（1000行）
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SXSSFSheet sheet = wb.createSheet(System.currentTimeMillis() + "");
        CellStyle colStyle = createCellStyle((SXSSFWorkbook) wb, (short) 15, true, true);
        CellStyle colStyle2 = createCellStylenoborder((SXSSFWorkbook) wb, (short) 15, true, true);
        CellStyle colright = getColRight((SXSSFWorkbook) wb, (short) 10, true, false);
        CellRangeAddress callRangeAddress01 = new CellRangeAddress(0, 0, 0, 14);
        CellRangeAddress callRangeAddress02 = new CellRangeAddress(1, 1, 0, 3);
        CellRangeAddress callRangeAddress03 = new CellRangeAddress(1, 1, 4, 7);
        CellRangeAddress callRangeAddress04 = new CellRangeAddress(1, 1, 8, 11);
        CellRangeAddress callRangeAddress05 = new CellRangeAddress(1, 1, 12, 14);
        CellRangeAddress callRangeAddress21 = new CellRangeAddress(2, 2, 0, 3);
        CellRangeAddress callRangeAddress22 = new CellRangeAddress(2, 2, 4, 7);
        CellRangeAddress callRangeAddress23 = new CellRangeAddress(2, 2, 8, 11);
        CellRangeAddress callRangeAddress24 = new CellRangeAddress(2, 2, 12, 14);
        CellRangeAddress callRangeAddress31 = new CellRangeAddress(3, 3, 0, 3);
        CellRangeAddress callRangeAddress32 = new CellRangeAddress(3, 3, 4, 7);
        CellRangeAddress callRangeAddress33 = new CellRangeAddress(3, 3, 8, 11);
        CellRangeAddress callRangeAddress34 = new CellRangeAddress(3, 3, 12, 14);
        CellRangeAddress callRangeAddress41 = new CellRangeAddress(4, 4, 0, 3);
        CellRangeAddress callRangeAddress42 = new CellRangeAddress(4, 4, 4, 7);
        CellRangeAddress callRangeAddress43 = new CellRangeAddress(4, 4, 8, 11);
        CellRangeAddress callRangeAddress44 = new CellRangeAddress(4, 4, 12, 14);
        CellRangeAddress callRangeAddress51 = new CellRangeAddress(5, 5, 0, 3);
        CellRangeAddress callRangeAddress52 = new CellRangeAddress(5, 5, 4, 7);
        CellRangeAddress callRangeAddress53 = new CellRangeAddress(5, 5, 8, 11);
        CellRangeAddress callRangeAddress54 = new CellRangeAddress(5, 5, 12, 14);
        CellRangeAddress callRangeAddress61 = new CellRangeAddress(6, 7, 0, 3);
        CellRangeAddress callRangeAddress62 = new CellRangeAddress(6, 7, 4, 14);
        CellRangeAddress callRangeAddress71 = new CellRangeAddress(8, 8, 0, 3);
        CellRangeAddress callRangeAddress72 = new CellRangeAddress(8, 8, 4, 14);
        sheet.addMergedRegion(callRangeAddress01);
        sheet.addMergedRegion(callRangeAddress02);
        sheet.addMergedRegion(callRangeAddress03);
        sheet.addMergedRegion(callRangeAddress04);
        sheet.addMergedRegion(callRangeAddress05);
        sheet.addMergedRegion(callRangeAddress21);
        sheet.addMergedRegion(callRangeAddress22);
        sheet.addMergedRegion(callRangeAddress23);
        sheet.addMergedRegion(callRangeAddress24);
        sheet.addMergedRegion(callRangeAddress31);
        sheet.addMergedRegion(callRangeAddress32);
        sheet.addMergedRegion(callRangeAddress33);
        sheet.addMergedRegion(callRangeAddress34);
        sheet.addMergedRegion(callRangeAddress41);
        sheet.addMergedRegion(callRangeAddress42);
        sheet.addMergedRegion(callRangeAddress43);
        sheet.addMergedRegion(callRangeAddress44);
        sheet.addMergedRegion(callRangeAddress51);
        sheet.addMergedRegion(callRangeAddress52);
        sheet.addMergedRegion(callRangeAddress53);
        sheet.addMergedRegion(callRangeAddress54);
        sheet.addMergedRegion(callRangeAddress61);
        sheet.addMergedRegion(callRangeAddress62);
        sheet.addMergedRegion(callRangeAddress71);
        sheet.addMergedRegion(callRangeAddress72);
        Row row0 = sheet.createRow(0);
        row0.setHeight((short) 600);
        Cell cell0 = row0.createCell(0);
        cell0.setCellValue(MessageUtils.get("巡视报告"));
        CellStyle stylea = wb.createCellStyle();
        stylea.setAlignment(HorizontalAlignment.CENTER);
        stylea.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font = wb.createFont();
        font.setFontHeightInPoints((short) 20);
        font.setFontHeight((short) 500);
        font.setBold(true);
        stylea.setFont(font);
        cell0.setCellStyle(stylea);
        Row row1 = sheet.createRow(1);
        Cell cell11 = row1.createCell(0);
        cell11.setCellValue(MessageUtils.get("变电站"));
        cell11.setCellStyle(colStyle2);
        Cell cell12 = row1.createCell(4);
        cell12.setCellValue(inspectionReport.getStationName());
        cell12.setCellStyle(colStyle2);
        Cell cell13 = row1.createCell(8);
        cell13.setCellValue(MessageUtils.get("电压等级"));
        cell13.setCellStyle(colStyle2);
        Cell cell14 = row1.createCell(12);
        cell14.setCellValue(inspectionReport.getVoltLevel());
        cell14.setCellStyle(colStyle2);

        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = row1.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        Row row2 = sheet.createRow(2);
        Cell cell21 = row2.createCell(0);
        cell21.setCellValue(MessageUtils.get("巡视计划创建日期"));
        cell21.setCellStyle(colStyle2);
        Cell cell22 = row2.createCell(4);
        if (inspectionReport.getInspectionDate() != null) {
            cell22.setCellValue(sdf.format(inspectionReport.getInspectionDate()));
        }

        cell22.setCellStyle(colStyle2);
        Cell cell23 = row2.createCell(8);
        cell23.setCellValue(MessageUtils.get("变电站类别"));
        cell23.setCellStyle(colStyle2);
        Cell cell24 = row2.createCell(12);
        cell24.setCellValue(inspectionReport.getStationType());
        cell24.setCellStyle(colStyle2);

        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = row2.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        Row row3 = sheet.createRow(3);
        Cell cell31 = row3.createCell(0);
        cell31.setCellValue(MessageUtils.get("巡视任务"));
        cell31.setCellStyle(colStyle2);
        Cell cell32 = row3.createCell(4);
        cell32.setCellValue(inspectionReport.getInspectionTaskName());
        cell32.setCellStyle(colStyle2);
        Cell cell33 = row3.createCell(8);
        cell33.setCellValue(MessageUtils.get("环境信息"));
        cell33.setCellStyle(colStyle2);
        Cell cell34 = row3.createCell(12);
        cell34.setCellValue(inspectionReport.getEnvInfo());
        cell34.setCellStyle(colStyle2);

        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = row3.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        Row row4 = sheet.createRow(4);
        Cell cell41 = row4.createCell(0);
        cell41.setCellValue(MessageUtils.get("审核人"));
        cell41.setCellStyle(colStyle2);
        Cell cell42 = row4.createCell(4);
        cell42.setCellValue(inspectionReport.getCheckPerson());
        cell42.setCellStyle(colStyle2);
        Cell cell43 = row4.createCell(8);
        cell43.setCellValue(MessageUtils.get("审核时间"));
        cell43.setCellStyle(colStyle2);
        Cell cell44 = row4.createCell(12);
        cell44.setCellValue(DateUtil.formatDateTime(inspectionReport.getCheckTime()));
        cell44.setCellStyle(colStyle2);

        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = row4.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        Row row5 = sheet.createRow(5);
        Cell cell51 = row5.createCell(0);
        cell51.setCellValue(MessageUtils.get("巡视开始时间"));
        cell51.setCellStyle(colStyle2);
        Cell cell52 = row5.createCell(4);
        if (inspectionReport.getInspectionStartTime() != null) {
            cell52.setCellValue(DateUtil.formatDateTime(inspectionReport.getInspectionStartTime()));
        }

        cell52.setCellStyle(colStyle2);
        Cell cell53 = row5.createCell(8);
        cell53.setCellValue(MessageUtils.get("巡视结束时间"));
        cell53.setCellStyle(colStyle2);
        Cell cell54 = row5.createCell(12);
        if (inspectionReport.getInspectionEndTime() != null) {
            cell54.setCellValue(DateUtil.formatDateTime(inspectionReport.getInspectionEndTime()));
        }

        cell54.setCellStyle(colStyle2);

        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = row5.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        Row row6 = sheet.createRow(6);
        row6.setHeight((short) 1000);
        Cell cell61 = row6.createCell(0);
        cell61.setCellValue(MessageUtils.get("巡视统计"));
        cell61.setCellStyle(colStyle2);
        Cell cell62 = row6.createCell(4);
        cell62.setCellValue(inspectionReport.getPatrolStatistics());
        cell62.setCellStyle(colStyle2);

        int i;
        for (i = 0; i < 15; ++i) {
            if (i != 0 && i != 4) {
                cell14 = row6.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        row6 = sheet.createRow(7);

        for (i = 0; i < 15; ++i) {
            cell14 = row6.createCell(i);
            cell14.setCellStyle(colStyle2);
        }

        Row row7 = sheet.createRow(8);
        row7.setHeight((short) 1000);
        Cell cell71 = row7.createCell(0);
        cell71.setCellValue(MessageUtils.get("巡视结论"));
        cell71.setCellStyle(colStyle2);
        Cell cell72 = row7.createCell(4);
        cell72.setCellValue(inspectionReport.getDescription());
        cell72.setCellStyle(colStyle2);

        //qinyl
        for (int j = 0; j < 15; ++j) {
            if (j != 0 && j != 4) {
                cell14 = row7.createCell(j);
                cell14.setCellStyle(colStyle2);
            }
        }


        List<InspectionReportData> list = new ArrayList();
        InspectionReportData inspectionReportQxData = new InspectionReportData();
        inspectionReportQxData.setPointStatus(MessageUtils.get("缺陷"));
        list.add(inspectionReportQxData);
        if ("1".equals(exportReportFlag)) {
            InspectionReportData inspectionReportZcData = new InspectionReportData();
            inspectionReportZcData.setPointStatus(MessageUtils.get("正常"));
            list.add(inspectionReportZcData);
            InspectionReportData inspectionReportYcData = new InspectionReportData();
            inspectionReportYcData.setPointStatus(MessageUtils.get("异常"));
            list.add(inspectionReportYcData);
        }
        int total = 0;

        label186:
        for (Iterator var74 = list.iterator(); var74.hasNext(); total += 2) {
            InspectionReportData arr = (InspectionReportData) var74.next();
            SXSSFDrawing patriarch = sheet.createDrawingPatriarch();
            CellRangeAddress callRangeAddressa1 = new CellRangeAddress(9 + total, 9 + total, 0, 14);
            sheet.addMergedRegion(callRangeAddressa1);
            Row rowa1 = sheet.createRow(9 + total);
            Cell cella1 = rowa1.createCell(0);
            cella1.setCellValue(arr.getPointStatus() + MessageUtils.get("点位汇总"));
            CellStyle styleab = wb.createCellStyle();
            styleab.setAlignment(HorizontalAlignment.CENTER);
            styleab.setVerticalAlignment(VerticalAlignment.CENTER);
            Font fonta = wb.createFont();
            fonta.setFontHeightInPoints((short) 20);
            styleab.setFont(fonta);
            cella1.setCellStyle(styleab);

            //qinyl
            for (int j = 0; j < 15; ++j) {
                if (j != 0) {
                    cell14 = rowa1.createCell(j);
                    cell14.setCellStyle(colStyle2);
                }
            }

            CellRangeAddress callRangeAddressa12 = new CellRangeAddress(10 + total, 10 + total, 12, 14);
            sheet.addMergedRegion(callRangeAddressa12);
            rowa1 = sheet.createRow(10 + total);
            sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total, 2, 4));
            sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total, 5, 6));
            sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total, 9, 10));
            cella1 = rowa1.createCell(0);
            cella1.setCellValue(MessageUtils.get("编号"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(1);
            cella1.setCellValue(MessageUtils.get("区域"));
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(2);
            cella1.setCellValue(MessageUtils.get("设备"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(3);
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(4);
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(5);
            cella1.setCellValue(MessageUtils.get("点位"));
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(6);
            cella1.setCellStyle(colStyle);

            cella1 = rowa1.createCell(7);
            cella1.setCellValue(MessageUtils.get("数据来源"));
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(8);
            cella1.setCellValue(MessageUtils.get("采集时间"));
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(9);
            cella1.setCellValue(MessageUtils.get("巡视结果"));
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(10);
            cella1.setCellStyle(colStyle);

            cella1 = rowa1.createCell(11);
            cella1.setCellValue(MessageUtils.get("算法类型"));
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(12);
            cella1.setCellValue(MessageUtils.get("巡视图像"));
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(13);
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(14);
            cella1.setCellStyle(colStyle);

            InspectionReportData insa = new InspectionReportData();
            insa.setReportId(inspectionReport.getLineId() + "");
            insa.setPointStatus(arr.getPointStatus());
            List<InspectionReportData> listarr = new ArrayList();
            if (inspectionReport.getReportDatalist() != null && inspectionReport.getReportDatalist().size() > 0) {
                listarr = (List) inspectionReport.getReportDatalist().stream().filter((a) -> {
                    return arr.getPointStatus().equals(a.getPointStatus());
                }).collect(Collectors.toList());
            }

            Iterator var85 = ((List) listarr).iterator();

            while (true) {
                while (true) {
                    if (!var85.hasNext()) {
                        continue label186;
                    }

                    InspectionReportData brr = (InspectionReportData) var85.next();
                    ++total;
                    InspectionReportImg inspectionReportImg = new InspectionReportImg();
                    inspectionReportImg.setReportInfoId(brr.getLineId() + "");
                    List<InspectionReportImg> imgList = new ArrayList();
                    if (brr.getReportImgList() != null && brr.getReportImgList().size() > 0) {
                        imgList = brr.getReportImgList();
                    }

                    CellRangeAddress callRangeAddressa4 = new CellRangeAddress(10 + total, 10 + total, 12, 14);
                    sheet.addMergedRegion(callRangeAddressa4);
                    Row rowb1 = sheet.createRow(10 + total);
                    if (((List) imgList).size() > 0) {
                        rowb1.setHeight((short) 1000);
                    }

                    cella1 = rowb1.createCell(0);
                    cella1.setCellValue((double) brr.getCode().longValue());
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(1);
                    cella1.setCellValue(brr.getArea());
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(2);
                    cella1.setCellValue(brr.getEqName());
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(3);
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(4);
//                    cella1.setCellValue(brr.getParts());
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(5);
                    cella1.setCellValue(brr.getPointName());
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(6);
                    cella1.setCellStyle(colStyle);

                    cella1 = rowb1.createCell(7);
                    cella1.setCellValue(brr.getDataSources());
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(8);
                    if (brr.getAcquisitionTime() != null) {
                        cella1.setCellValue(DateUtil.formatDateTime(brr.getAcquisitionTime()));
                    }
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(9);
                    cella1.setCellValue(brr.getInspectionResults());
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(10);
                    cella1.setCellStyle(colStyle);

                    cella1 = rowb1.createCell(11);
                    cella1.setCellValue(brr.getAlgName());
                    cella1.setCellStyle(colStyle2);

                    String str = "";
                    cella1 = rowb1.createCell(12);
                    cella1.setCellValue(str);
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(13);
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(14);
                    cella1.setCellStyle(colStyle);
                    if (((List) imgList).size() > 0) {
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + ((List) imgList).size(), 0, 0));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + ((List) imgList).size(), 1, 1));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + ((List) imgList).size(), 2, 4));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + ((List) imgList).size(), 5, 6));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + ((List) imgList).size(), 7, 7));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + ((List) imgList).size(), 8, 8));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + ((List) imgList).size(), 9, 10));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + ((List) imgList).size(), 11, 11));
                        new ArrayList();
                        Iterator var93 = ((List) imgList).iterator();

                        while (var93.hasNext()) {
                            InspectionReportImg crr = (InspectionReportImg) var93.next();
                            ++total;
                            CellRangeAddress callRangeAddressb4 = new CellRangeAddress(10 + total, 10 + total, 12, 14);
                            sheet.addMergedRegion(callRangeAddressb4);
                            rowb1 = sheet.createRow(10 + total);
                            rowb1.setHeight((short) 1000);
                            cella1 = rowb1.createCell(0);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(1);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(2);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(3);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(4);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(5);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(6);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(7);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(8);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(9);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(10);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(11);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(12);
                            if (crr.getImgType().equals("0")) {
                                try {
                                    insertImage(wb, patriarch, this.images(crr.getImg(), inputStreamMap), 10 + total, 0, 2);
                                } catch (Exception var97) {
                                    var97.printStackTrace();
                                }
                            } else {
                                String sheetName = crr.getImgSrc();
                                cella1.setCellFormula("HYPERLINK(\"" + sheetName + "\")");
                                cella1.setCellStyle(colright);
                            }

                            cella1 = rowb1.createCell(13);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(14);
                            cella1.setCellStyle(colStyle);
                        }
                    } else {
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total, 2, 4));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total, 5, 6));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total, 9, 10));
                    }
                }
            }
        }

        return wb;
    }

    public SXSSFWorkbook getSXSSFWorkbookLingzhou(InspectionReport inspectionReport, Map<String, byte[]> inputStreamMap) {
        // 使用SXSSFWorkbook并设置行访问窗口大小（1000行）
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SXSSFSheet sheet = wb.createSheet(System.currentTimeMillis() + "");
        CellStyle colStyle = createCellStyle(wb, (short) 15, true, true);
        CellStyle colStyle2 = createCellStylenoborder(wb, (short) 15, true, true);
        CellStyle colright = getColRight(wb, (short) 10, true, false);

        CellRangeAddress callRangeAddress01 = new CellRangeAddress(0, 0, 0, 17);
        sheet.addMergedRegion(callRangeAddress01);
        for (int i = 1; i < 6; ++i) {
            CellRangeAddress callRangeAddress02 = new CellRangeAddress(i, i, 0, 2);
            CellRangeAddress callRangeAddress03 = new CellRangeAddress(i, i, 3, 17);
            sheet.addMergedRegion(callRangeAddress02);
            sheet.addMergedRegion(callRangeAddress03);
        }

        Row row0 = sheet.createRow(0);
        row0.setHeight((short) 600);
        Cell cell0 = row0.createCell(0);
        cell0.setCellValue(MessageUtils.get("巡视报告"));
        CellStyle stylea = wb.createCellStyle();
        stylea.setAlignment(HorizontalAlignment.CENTER);
        stylea.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font = wb.createFont();
        font.setFontHeightInPoints((short) 20);
        font.setFontHeight((short) 500);
        font.setBold(true);
        stylea.setFont(font);
        cell0.setCellStyle(stylea);

        Row row1 = sheet.createRow(1);
        row1.setHeight((short) 1000);
        Cell cell11 = row1.createCell(0);
        cell11.setCellValue(MessageUtils.get("任务名称"));
        cell11.setCellStyle(colStyle2);
        Cell cell12 = row1.createCell(3);
        cell12.setCellValue(inspectionReport.getInspectionTaskName());
        cell12.setCellStyle(colStyle2);

        for (int i = 0; i < 18; ++i) {
            if (i != 0 && i != 3) {
                cell12 = row1.createCell(i);
                cell12.setCellStyle(colStyle2);
            }
        }

        Row row2 = sheet.createRow(2);
        row2.setHeight((short) 1000);
        Cell cell61 = row2.createCell(0);
        cell61.setCellValue(MessageUtils.get("任务时间"));
        cell61.setCellStyle(colStyle2);
        Cell cell62 = row2.createCell(3);
        cell62.setCellValue("任务开始时间：" + formatDateTime(inspectionReport.getInspectionStartTime()) + "，任务结束时间：" + formatDateTime(inspectionReport.getInspectionEndTime()));
        cell62.setCellStyle(colStyle2);

        for (int i = 0; i < 18; ++i) {
            if (i != 0 && i != 3) {
                cell12 = row2.createCell(i);
                cell12.setCellStyle(colStyle2);
            }
        }

        Row row3 = sheet.createRow(3);
        row3.setHeight((short) 1000);
        Cell cell31 = row3.createCell(0);
        cell31.setCellValue(MessageUtils.get("任务状态"));
        cell31.setCellStyle(colStyle2);
        Cell cell32 = row3.createCell(3);
        cell32.setCellValue("已完成");
        cell32.setCellStyle(colStyle2);

        for (int i = 0; i < 18; ++i) {
            if (i != 0 && i != 3) {
                cell12 = row3.createCell(i);
                cell12.setCellStyle(colStyle2);
            }
        }

        Row row4 = sheet.createRow(4);
        row4.setHeight((short) 1000);
        Cell cell41 = row4.createCell(0);
        cell41.setCellValue(MessageUtils.get("巡检点"));
        cell41.setCellStyle(colStyle2);
        Cell cell42 = row4.createCell(3);
        cell42.setCellValue(inspectionReport.getPatrolStatistics());
        cell42.setCellStyle(colStyle2);

        for (int i = 0; i < 18; ++i) {
            if (i != 0 && i != 3) {
                cell12 = row4.createCell(i);
                cell12.setCellStyle(colStyle2);
            }
        }

        Row row5 = sheet.createRow(5);
        row5.setHeight((short) 1000);
        Cell cell51 = row5.createCell(0);
        cell51.setCellValue(MessageUtils.get("环境信息"));
        cell51.setCellStyle(colStyle2);
        Cell cell52 = row5.createCell(3);
        cell52.setCellValue(inspectionReport.getEnvInfo());
        cell52.setCellStyle(colStyle2);

        for (int i = 0; i < 18; ++i) {
            if (i != 0 && i != 3) {
                cell12 = row5.createCell(i);
                cell12.setCellStyle(colStyle2);
            }
        }


//        Row row1 = sheet.createRow(1);
//        Cell cell11 = row1.createCell(0);
//        cell11.setCellValue(MessageUtils.get("变电站"));
//        cell11.setCellStyle(colStyle2);
//        Cell cell12 = row1.createCell(5);
//        cell12.setCellValue(inspectionReport.getStationName());
//        cell12.setCellStyle(colStyle2);
//        Cell cell13 = row1.createCell(10);
//        cell13.setCellValue(MessageUtils.get("电压等级"));
//        cell13.setCellStyle(colStyle2);
//        Cell cell14 = row1.createCell(15);
//        cell14.setCellValue(inspectionReport.getVoltLevel());
//        cell14.setCellStyle(colStyle2);
//
//        for (int i = 0; i < 18; ++i) {
//            if (i != 0 && i != 5 && i != 10 && i != 15) {
//                cell14 = row1.createCell(i);
//                cell14.setCellStyle(colStyle2);
//            }
//        }
//
//        Row row2 = sheet.createRow(2);
//        Cell cell21 = row2.createCell(0);
//        cell21.setCellValue(MessageUtils.get("巡视计划创建日期"));
//        cell21.setCellStyle(colStyle2);
//        Cell cell22 = row2.createCell(5);
//        if (inspectionReport.getInspectionDate() != null) {
//            cell22.setCellValue(sdf.format(inspectionReport.getInspectionDate()));
//        }
//
//        cell22.setCellStyle(colStyle2);
//        Cell cell23 = row2.createCell(10);
//        cell23.setCellValue(MessageUtils.get("变电站类别"));
//        cell23.setCellStyle(colStyle2);
//        Cell cell24 = row2.createCell(15);
//        cell24.setCellValue(inspectionReport.getStationType());
//        cell24.setCellStyle(colStyle2);
//
//        for (int i = 0; i < 18; ++i) {
//            if (i != 0 && i != 5 && i != 10 && i != 15) {
//                cell14 = row2.createCell(i);
//                cell14.setCellStyle(colStyle2);
//            }
//        }
//
//        Row row3 = sheet.createRow(3);
//        Cell cell31 = row3.createCell(0);
//        cell31.setCellValue(MessageUtils.get("巡视任务"));
//        cell31.setCellStyle(colStyle2);
//        Cell cell32 = row3.createCell(5);
//        cell32.setCellValue(inspectionReport.getInspectionTaskName());
//        cell32.setCellStyle(colStyle2);
//        Cell cell33 = row3.createCell(10);
//        cell33.setCellValue(MessageUtils.get("环境信息"));
//        cell33.setCellStyle(colStyle2);
//        Cell cell34 = row3.createCell(15);
//        cell34.setCellValue(inspectionReport.getEnvInfo());
//        cell34.setCellStyle(colStyle2);
//
//        for (int i = 0; i < 18; ++i) {
//            if (i != 0 && i != 5 && i != 10 && i != 15) {
//                cell14 = row3.createCell(i);
//                cell14.setCellStyle(colStyle2);
//            }
//        }
//
//        Row row4 = sheet.createRow(4);
//        Cell cell41 = row4.createCell(0);
//        cell41.setCellValue(MessageUtils.get("审核人"));
//        cell41.setCellStyle(colStyle2);
//        Cell cell42 = row4.createCell(5);
//        cell42.setCellValue(inspectionReport.getCheckPerson());
//        cell42.setCellStyle(colStyle2);
//        Cell cell43 = row4.createCell(10);
//        cell43.setCellValue(MessageUtils.get("审核时间"));
//        cell43.setCellStyle(colStyle2);
//        Cell cell44 = row4.createCell(15);
//        cell44.setCellValue(DateUtil.formatDateTime(inspectionReport.getCheckTime()));
//        cell44.setCellStyle(colStyle2);
//
//        for (int i = 0; i < 18; ++i) {
//            if (i != 0 && i != 5 && i != 10 && i != 15) {
//                cell14 = row4.createCell(i);
//                cell14.setCellStyle(colStyle2);
//            }
//        }
//
//        Row row5 = sheet.createRow(5);
//        Cell cell51 = row5.createCell(0);
//        cell51.setCellValue(MessageUtils.get("巡视开始时间"));
//        cell51.setCellStyle(colStyle2);
//        Cell cell52 = row5.createCell(5);
//        if (inspectionReport.getInspectionStartTime() != null) {
//            cell52.setCellValue(DateUtil.formatDateTime(inspectionReport.getInspectionStartTime()));
//        }
//
//        cell52.setCellStyle(colStyle2);
//        Cell cell53 = row5.createCell(10);
//        cell53.setCellValue(MessageUtils.get("巡视结束时间"));
//        cell53.setCellStyle(colStyle2);
//        Cell cell54 = row5.createCell(15);
//        if (inspectionReport.getInspectionEndTime() != null) {
//            cell54.setCellValue(DateUtil.formatDateTime(inspectionReport.getInspectionEndTime()));
//        }
//
//        cell54.setCellStyle(colStyle2);
//
//        for (int i = 0; i < 18; ++i) {
//            if (i != 0 && i != 5 && i != 10 && i != 15) {
//                cell14 = row5.createCell(i);
//                cell14.setCellStyle(colStyle2);
//            }
//        }
//
//        Row row6 = sheet.createRow(6);
//        row6.setHeight((short) 1000);
//        Cell cell61 = row6.createCell(0);
//        cell61.setCellValue(MessageUtils.get("巡视统计"));
//        cell61.setCellStyle(colStyle2);
//        Cell cell62 = row6.createCell(5);
//        cell62.setCellValue(inspectionReport.getPatrolStatistics());
//        cell62.setCellStyle(colStyle2);
//
//        int i;
//        for (i = 0; i < 18; ++i) {
//            if (i != 0 && i != 5) {
//                cell14 = row6.createCell(i);
//                cell14.setCellStyle(colStyle2);
//            }
//        }
//
//        row6 = sheet.createRow(7);
//
//        for (i = 0; i < 18; ++i) {
//            cell14 = row6.createCell(i);
//            cell14.setCellStyle(colStyle2);
//        }
//
//        Row row7 = sheet.createRow(8);
//        row7.setHeight((short) 1000);
//        Cell cell71 = row7.createCell(0);
//        cell71.setCellValue(MessageUtils.get("巡视结论"));
//        cell71.setCellStyle(colStyle2);
//        Cell cell72 = row7.createCell(5);
//        cell72.setCellValue(inspectionReport.getDescription());
//        cell72.setCellStyle(colStyle2);
//
//        //qinyl
//        for (int j = 0; j < 18; ++j) {
//            if (j != 0 && j != 5) {
//                cell14 = row7.createCell(j);
//                cell14.setCellStyle(colStyle2);
//            }
//        }


        List<InspectionReportData> list = new ArrayList();
        InspectionReportData inspectionReportData = new InspectionReportData();
        inspectionReportData.setPointStatus(MessageUtils.get("缺陷"));
        list.add(inspectionReportData);
        InspectionReportData inspection = new InspectionReportData();
        inspection.setPointStatus(MessageUtils.get("异常"));
        list.add(inspection);
        InspectionReportData inection = new InspectionReportData();
        inection.setPointStatus(MessageUtils.get("正常"));
        list.add(inection);

        int total = 0;

        label186:
        for (Iterator var74 = list.iterator(); var74.hasNext(); total += 2) {
            InspectionReportData arr = (InspectionReportData) var74.next();
            SXSSFDrawing patriarch = sheet.createDrawingPatriarch();
            CellRangeAddress callRangeAddressa1 = new CellRangeAddress(6 + total, 6 + total, 0, 17);
            sheet.addMergedRegion(callRangeAddressa1);
            Row rowa1 = sheet.createRow(6 + total);
            Cell cella1 = rowa1.createCell(0);
            cella1.setCellValue(arr.getPointStatus() + MessageUtils.get("点位汇总"));
            CellStyle styleab = wb.createCellStyle();
            styleab.setAlignment(HorizontalAlignment.CENTER);
            styleab.setVerticalAlignment(VerticalAlignment.CENTER);
            Font fonta = wb.createFont();
            fonta.setFontHeightInPoints((short) 20);
            styleab.setFont(fonta);
            cella1.setCellStyle(styleab);

            //qinyl
            for (int j = 0; j < 18; ++j) {
                if (j != 0) {
                    cell12 = rowa1.createCell(j);
                    cell12.setCellStyle(colStyle2);
                }
            }

            CellRangeAddress callRangeAddressa12 = new CellRangeAddress(7 + total, 7 + total, 15, 17);
            sheet.addMergedRegion(callRangeAddressa12);
            rowa1 = sheet.createRow(7 + total);
            sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total, 2, 4));
            sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total, 5, 7));
            sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total, 8, 9));
            sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total, 12, 13));
            cella1 = rowa1.createCell(0);
            cella1.setCellValue(MessageUtils.get("编号"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(1);
            cella1.setCellValue(MessageUtils.get("区域"));
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(2);
            cella1.setCellValue(MessageUtils.get("设备"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(3);
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(4);
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(5);
            cella1.setCellValue(MessageUtils.get("部件"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(6);
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(7);
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(8);
            cella1.setCellValue(MessageUtils.get("点位"));
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(9);
            cella1.setCellStyle(colStyle);

            cella1 = rowa1.createCell(10);
            cella1.setCellValue(MessageUtils.get("数据来源"));
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(11);
            cella1.setCellValue(MessageUtils.get("识别时间"));
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(12);
            cella1.setCellValue(MessageUtils.get("巡视结果"));
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(13);
            cella1.setCellStyle(colStyle);

            cella1 = rowa1.createCell(14);
            cella1.setCellValue(MessageUtils.get("算法名称"));
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(15);
            cella1.setCellValue(MessageUtils.get("巡视图像"));
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(16);
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(17);
            cella1.setCellStyle(colStyle);

            InspectionReportData insa = new InspectionReportData();
            insa.setReportId(inspectionReport.getLineId() + "");
            insa.setPointStatus(arr.getPointStatus());
            List<InspectionReportData> listarr = new ArrayList();
            if (inspectionReport.getReportDatalist() != null && inspectionReport.getReportDatalist().size() > 0) {
                listarr = (List) inspectionReport.getReportDatalist().stream().filter((a) -> {
                    return arr.getPointStatus().equals(a.getPointStatus());
                }).collect(Collectors.toList());
            }

            Iterator var85 = ((List) listarr).iterator();

            while (true) {
                while (true) {
                    if (!var85.hasNext()) {
                        continue label186;
                    }

                    InspectionReportData brr = (InspectionReportData) var85.next();
                    ++total;
                    InspectionReportImg inspectionReportImg = new InspectionReportImg();
                    inspectionReportImg.setReportInfoId(brr.getLineId() + "");
                    List<InspectionReportImg> imgList = new ArrayList();
                    if (brr.getReportImgList() != null && brr.getReportImgList().size() > 0) {
                        imgList = brr.getReportImgList();
                    }

                    CellRangeAddress callRangeAddressa4 = new CellRangeAddress(7 + total, 7 + total, 15, 17);
                    sheet.addMergedRegion(callRangeAddressa4);
                    Row rowb1 = sheet.createRow(7 + total);
                    if (((List) imgList).size() > 0) {
                        rowb1.setHeight((short) 1000);
                    }

                    cella1 = rowb1.createCell(0);
                    cella1.setCellValue((double) brr.getCode().longValue());
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(1);
                    cella1.setCellValue(brr.getArea());
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(2);
                    cella1.setCellValue(brr.getEqName());
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(3);
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(4);
//                    cella1.setCellValue(brr.getParts());
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(5);
                    cella1.setCellValue(brr.getParts());
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(6);
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(7);
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(8);
                    cella1.setCellValue(brr.getPointName());
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(9);
                    cella1.setCellStyle(colStyle);

                    cella1 = rowb1.createCell(10);
                    cella1.setCellValue(brr.getDataSources());
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(11);
                    if (brr.getAcquisitionTime() != null) {
                        cella1.setCellValue(DateUtil.formatDateTime(brr.getAcquisitionTime()));
                    }
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(12);
                    cella1.setCellValue(brr.getInspectionResults());
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(13);
                    cella1.setCellStyle(colStyle);

                    cella1 = rowb1.createCell(14);
                    cella1.setCellValue(brr.getAlgName());
                    cella1.setCellStyle(colStyle2);

                    String str = "";
                    cella1 = rowb1.createCell(15);
                    cella1.setCellValue(str);
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(16);
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(17);
                    cella1.setCellStyle(colStyle);
                    if (((List) imgList).size() > 0) {
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total + ((List) imgList).size(), 0, 0));
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total + ((List) imgList).size(), 1, 1));
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total + ((List) imgList).size(), 2, 4));
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total + ((List) imgList).size(), 5, 7));
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total + ((List) imgList).size(), 8, 9));
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total + ((List) imgList).size(), 10, 10));
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total + ((List) imgList).size(), 11, 11));
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total + ((List) imgList).size(), 12, 13));
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total + ((List) imgList).size(), 14, 14));
                        new ArrayList();
                        Iterator var93 = ((List) imgList).iterator();

                        while (var93.hasNext()) {
                            InspectionReportImg crr = (InspectionReportImg) var93.next();
                            ++total;
                            CellRangeAddress callRangeAddressb4 = new CellRangeAddress(7 + total, 7 + total, 15, 17);
                            sheet.addMergedRegion(callRangeAddressb4);
                            rowb1 = sheet.createRow(7 + total);
                            rowb1.setHeight((short) 1000);
                            cella1 = rowb1.createCell(0);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(1);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(2);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(3);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(4);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(5);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(6);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(7);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(8);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(9);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(10);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(11);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(12);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(13);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(14);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(15);
                            if (crr.getImgType().equals("0")) {
                                try {
                                    insertImageLingzhou(wb, patriarch, this.images(crr.getImg(), inputStreamMap), 7 + total, 0, 2);
                                } catch (Exception var97) {
                                    var97.printStackTrace();
                                }
                            } else {
                                String sheetName = crr.getImgSrc();
                                cella1.setCellFormula("HYPERLINK(\"" + sheetName + "\")");
                                cella1.setCellStyle(colright);
                            }

                            cella1 = rowb1.createCell(16);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(17);
                            cella1.setCellStyle(colStyle);
                        }
                    } else {
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total, 2, 4));
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total, 5, 7));
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total, 8, 9));
                        sheet.addMergedRegion(new CellRangeAddress(7 + total, 7 + total, 12, 13));
                    }
                }
            }
        }

        return wb;
    }

    public SXSSFWorkbook getSXSSFWorkbookShaoxing(InspectionReport inspectionReport, Map<String, Path> tempFileMap) {
        // 使用SXSSFWorkbook并设置行访问窗口大小（1000行）
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SXSSFSheet sheet = wb.createSheet(System.currentTimeMillis() + "");
        CellStyle colStyle = createCellStyle((SXSSFWorkbook) wb, (short) 15, true, true);
        CellStyle colStyle2 = createCellStylenoborder((SXSSFWorkbook) wb, (short) 15, true, true);
        CellStyle colright = getColRight((SXSSFWorkbook) wb, (short) 10, true, false);
        CellRangeAddress callRangeAddress01 = new CellRangeAddress(0, 0, 0, 14);
        CellRangeAddress callRangeAddress02 = new CellRangeAddress(1, 1, 0, 3);
        CellRangeAddress callRangeAddress03 = new CellRangeAddress(1, 1, 4, 7);
        CellRangeAddress callRangeAddress04 = new CellRangeAddress(1, 1, 8, 11);
        CellRangeAddress callRangeAddress05 = new CellRangeAddress(1, 1, 12, 14);
        CellRangeAddress callRangeAddress21 = new CellRangeAddress(2, 2, 0, 3);
        CellRangeAddress callRangeAddress22 = new CellRangeAddress(2, 2, 4, 7);
        CellRangeAddress callRangeAddress23 = new CellRangeAddress(2, 2, 8, 11);
        CellRangeAddress callRangeAddress24 = new CellRangeAddress(2, 2, 12, 14);
        CellRangeAddress callRangeAddress31 = new CellRangeAddress(3, 3, 0, 3);
        CellRangeAddress callRangeAddress32 = new CellRangeAddress(3, 3, 4, 7);
        CellRangeAddress callRangeAddress33 = new CellRangeAddress(3, 3, 8, 11);
        CellRangeAddress callRangeAddress34 = new CellRangeAddress(3, 3, 12, 14);
        CellRangeAddress callRangeAddress41 = new CellRangeAddress(4, 4, 0, 3);
        CellRangeAddress callRangeAddress42 = new CellRangeAddress(4, 4, 4, 14);
        CellRangeAddress callRangeAddress51 = new CellRangeAddress(5, 5, 0, 3);
        CellRangeAddress callRangeAddress52 = new CellRangeAddress(5, 5, 4, 14);
        CellRangeAddress callRangeAddress61 = new CellRangeAddress(6, 6, 0, 3);
        CellRangeAddress callRangeAddress62 = new CellRangeAddress(6, 6, 4, 14);
        sheet.addMergedRegion(callRangeAddress01);
        sheet.addMergedRegion(callRangeAddress02);
        sheet.addMergedRegion(callRangeAddress03);
        sheet.addMergedRegion(callRangeAddress04);
        sheet.addMergedRegion(callRangeAddress05);
        sheet.addMergedRegion(callRangeAddress21);
        sheet.addMergedRegion(callRangeAddress22);
        sheet.addMergedRegion(callRangeAddress23);
        sheet.addMergedRegion(callRangeAddress24);
        sheet.addMergedRegion(callRangeAddress31);
        sheet.addMergedRegion(callRangeAddress32);
        sheet.addMergedRegion(callRangeAddress33);
        sheet.addMergedRegion(callRangeAddress34);
        sheet.addMergedRegion(callRangeAddress41);
        sheet.addMergedRegion(callRangeAddress42);
        sheet.addMergedRegion(callRangeAddress51);
        sheet.addMergedRegion(callRangeAddress52);
        sheet.addMergedRegion(callRangeAddress61);
        sheet.addMergedRegion(callRangeAddress62);
        Row row0 = sheet.createRow(0);
        row0.setHeight((short) 600);
        Cell cell0 = row0.createCell(0);
        cell0.setCellValue(MessageUtils.get("巡视报告"));
        CellStyle stylea = wb.createCellStyle();
        stylea.setAlignment(HorizontalAlignment.CENTER);
        stylea.setVerticalAlignment(VerticalAlignment.CENTER);
        Font font = wb.createFont();
        font.setFontHeightInPoints((short) 20);
        font.setFontHeight((short) 500);
        font.setBold(true);
        stylea.setFont(font);
        cell0.setCellStyle(stylea);
        Row row1 = sheet.createRow(1);
        Cell cell11 = row1.createCell(0);
        cell11.setCellValue(MessageUtils.get("变电站"));
        cell11.setCellStyle(colStyle2);
        Cell cell12 = row1.createCell(4);
        cell12.setCellValue(inspectionReport.getStationName());
        cell12.setCellStyle(colStyle2);
        Cell cell13 = row1.createCell(8);
        cell13.setCellValue(MessageUtils.get("电压等级"));
        cell13.setCellStyle(colStyle2);
        Cell cell14 = row1.createCell(12);
        cell14.setCellValue(inspectionReport.getVoltLevel());
        cell14.setCellStyle(colStyle2);

        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = row1.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }


        Row row2 = sheet.createRow(2);
        Cell cell21 = row2.createCell(0);
        cell21.setCellValue(MessageUtils.get("审核人"));
        cell21.setCellStyle(colStyle2);
        Cell cell22 = row2.createCell(4);
        cell22.setCellValue(inspectionReport.getCheckPerson());
        cell22.setCellStyle(colStyle2);
        Cell cell23 = row2.createCell(8);
        cell23.setCellValue(MessageUtils.get("审核时间"));
        cell23.setCellStyle(colStyle2);
        Cell cell24 = row2.createCell(12);
        cell24.setCellValue(DateUtil.formatDateTime(inspectionReport.getCheckTime()));
        cell24.setCellStyle(colStyle2);

        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = row2.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        Row row3 = sheet.createRow(3);
        Cell cell31 = row3.createCell(0);
        cell31.setCellValue(MessageUtils.get("巡视开始时间"));
        cell31.setCellStyle(colStyle2);
        Cell cell32 = row3.createCell(4);
        if (inspectionReport.getInspectionStartTime() != null) {
            cell32.setCellValue(DateUtil.formatDateTime(inspectionReport.getInspectionStartTime()));
        }

        cell32.setCellStyle(colStyle2);
        Cell cell33 = row3.createCell(8);
        cell33.setCellValue(MessageUtils.get("巡视结束时间"));
        cell33.setCellStyle(colStyle2);
        Cell cell34 = row3.createCell(12);
        if (inspectionReport.getInspectionEndTime() != null) {
            cell34.setCellValue(DateUtil.formatDateTime(inspectionReport.getInspectionEndTime()));
        }

        cell34.setCellStyle(colStyle2);

        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4 && i != 8 && i != 12) {
                cell14 = row3.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        Row row6 = sheet.createRow(4);
        Cell cell61 = row6.createCell(0);
        cell61.setCellValue(MessageUtils.get("巡视任务"));
        cell61.setCellStyle(colStyle2);
        Cell cell62 = row6.createCell(4);
        cell62.setCellValue(inspectionReport.getInspectionTaskName());
        cell62.setCellStyle(colStyle2);
        autoFitRowHeight(sheet, 4, 4, colStyle2);
//        Cell cell63 = row6.createCell(8);
//        cell63.setCellValue(MessageUtils.get("巡视统计"));
//        cell63.setCellStyle(colStyle2);
//        Cell cell64 = row6.createCell(12);
//        cell64.setCellValue(inspectionReport.getPatrolStatistics());
//        cell64.setCellStyle(colStyle2);
//        autoFitRowHeight(sheet, 4, 12, colStyle2);

        for (int i = 0; i < 15; ++i) {
            if (i != 0 && i != 4) {
                cell14 = row6.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        Row row7 = sheet.createRow(5);
        row7.setHeight((short) 1000);
        Cell cell71 = row7.createCell(0);
        cell71.setCellValue(MessageUtils.get("巡视统计"));
        cell71.setCellStyle(colStyle2);
        Cell cell72 = row7.createCell(4);
        cell72.setCellValue(inspectionReport.getPatrolStatistics());
        cell72.setCellStyle(colStyle2);

        //qinyl
        for (int j = 0; j < 15; ++j) {
            if (j != 0 && j != 4) {
                cell14 = row7.createCell(j);
                cell14.setCellStyle(colStyle2);
            }
        }

        Row row8 = sheet.createRow(6);
        row8.setHeight((short) 1000);
        Cell cell81 = row8.createCell(0);
        cell81.setCellValue(MessageUtils.get("巡视结论"));
        cell81.setCellStyle(colStyle2);
        Cell cell82 = row8.createCell(4);
        cell82.setCellValue(inspectionReport.getDescription());
        cell82.setCellStyle(colStyle2);

        //qinyl
        for (int j = 0; j < 15; ++j) {
            if (j != 0 && j != 4) {
                cell14 = row8.createCell(j);
                cell14.setCellStyle(colStyle2);
            }
        }
        List<InspectionReportData> list = new ArrayList<>();
        InspectionReportData inspectionReportQxData = new InspectionReportData();
        inspectionReportQxData.setPointStatus(MessageUtils.get("缺陷"));
        list.add(inspectionReportQxData);
        if ("1".equals(exportReportFlag)) {
//            InspectionReportData inspectionReportYcData = new InspectionReportData();
//            inspectionReportYcData.setPointStatus(MessageUtils.get("异常"));
//            list.add(inspectionReportYcData);
            InspectionReportData inspectionReportZcData = new InspectionReportData();
            inspectionReportZcData.setPointStatus(MessageUtils.get("正常"));
            list.add(inspectionReportZcData);
        }
        int total = 0;
        label186:
        for (Iterator var74 = list.iterator(); var74.hasNext(); total += 2) {
            InspectionReportData arr = (InspectionReportData) var74.next();
            SXSSFDrawing patriarch = sheet.createDrawingPatriarch();
            CellRangeAddress callRangeAddressa1 = new CellRangeAddress(7 + total, 7 + total, 0, 14);
            sheet.addMergedRegion(callRangeAddressa1);
            Row rowa1 = sheet.createRow(7 + total);
            Cell cella1 = rowa1.createCell(0);
            cella1.setCellValue(arr.getPointStatus() + MessageUtils.get("点位汇总"));
            CellStyle styleab = wb.createCellStyle();
            styleab.setAlignment(HorizontalAlignment.CENTER);
            styleab.setVerticalAlignment(VerticalAlignment.CENTER);
            Font fonta = wb.createFont();
            fonta.setFontHeightInPoints((short) 20);
            styleab.setFont(fonta);
            cella1.setCellStyle(styleab);

            //qinyl
            for (int j = 0; j < 15; ++j) {
                if (j != 0) {
                    cell14 = rowa1.createCell(j);
                    cell14.setCellStyle(colStyle2);
                }
            }

            CellRangeAddress callRangeAddressa12 = new CellRangeAddress(8 + total, 8 + total, 12, 14);
            sheet.addMergedRegion(callRangeAddressa12);
            rowa1 = sheet.createRow(8 + total);
            sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total, 2, 4));
            sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total, 5, 6));
            sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total, 9, 10));
            cella1 = rowa1.createCell(0);
            cella1.setCellValue(MessageUtils.get("编号"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(1);
            cella1.setCellValue(MessageUtils.get("区域"));
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(2);
            cella1.setCellValue(MessageUtils.get("设备"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(3);
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(4);
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(5);
            cella1.setCellValue(MessageUtils.get("点位"));
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(6);
            cella1.setCellStyle(colStyle);

            cella1 = rowa1.createCell(7);
            cella1.setCellValue(MessageUtils.get("数据来源"));
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(8);
            cella1.setCellValue(MessageUtils.get("采集时间"));
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(9);
            cella1.setCellValue(MessageUtils.get("巡视结果"));
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(10);
            cella1.setCellStyle(colStyle);

            cella1 = rowa1.createCell(11);
            cella1.setCellValue(MessageUtils.get("算法类型"));
            cella1.setCellStyle(colStyle2);

            cella1 = rowa1.createCell(12);
            cella1.setCellValue(MessageUtils.get("巡视图像"));
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(13);
            cella1.setCellStyle(colStyle);
            cella1 = rowa1.createCell(14);
            cella1.setCellStyle(colStyle);

            InspectionReportData insa = new InspectionReportData();
            insa.setReportId(inspectionReport.getLineId() + "");
            insa.setPointStatus(arr.getPointStatus());
            List<InspectionReportData> listarr = new ArrayList();
            if (inspectionReport.getReportDatalist() != null && inspectionReport.getReportDatalist().size() > 0) {
                listarr = (List) inspectionReport.getReportDatalist().stream().filter((a) -> {
                    return arr.getPointStatus().equals(a.getPointStatus());
                }).collect(Collectors.toList());
            }

            Iterator var85 = ((List) listarr).iterator();

            while (true) {
                while (true) {
                    if (!var85.hasNext()) {
                        continue label186;
                    }

                    InspectionReportData brr = (InspectionReportData) var85.next();
                    ++total;
//                    InspectionReportImg inspectionReportImg = new InspectionReportImg();
//                    inspectionReportImg.setReportInfoId(brr.getLineId() + "");
                    List<InspectionReportImg> imgList = new ArrayList();
                    if (brr.getReportImgList() != null && brr.getReportImgList().size() > 0) {
                        imgList = brr.getReportImgList();
                    }

                    CellRangeAddress callRangeAddressa4 = new CellRangeAddress(8 + total, 8 + total, 12, 14);
                    sheet.addMergedRegion(callRangeAddressa4);
                    Row rowb1 = sheet.createRow(8 + total);
                    if (((List) imgList).size() > 0) {
                        rowb1.setHeight((short) 1000);
                    }

                    cella1 = rowb1.createCell(0);
                    cella1.setCellValue((double) brr.getCode().longValue());
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(1);
                    cella1.setCellValue(brr.getArea());
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(2);
                    cella1.setCellValue(brr.getEqName());
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(3);
                    cella1.setCellStyle(colStyle2);
                    cella1 = rowb1.createCell(4);
//                    cella1.setCellValue(brr.getParts());
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(5);
                    cella1.setCellValue(brr.getPointName());
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(6);
                    cella1.setCellStyle(colStyle);

                    cella1 = rowb1.createCell(7);
                    cella1.setCellValue(brr.getDataSources());
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(8);
                    if (brr.getAcquisitionTime() != null) {
                        cella1.setCellValue(DateUtil.formatDateTime(brr.getAcquisitionTime()));
                    }
                    cella1.setCellStyle(colStyle2);

                    cella1 = rowb1.createCell(9);
                    cella1.setCellValue(brr.getInspectionResults());
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(10);
                    cella1.setCellStyle(colStyle);

                    cella1 = rowb1.createCell(11);
                    cella1.setCellValue(brr.getAlgName());
                    cella1.setCellStyle(colStyle2);

                    String str = "";
                    cella1 = rowb1.createCell(12);
                    cella1.setCellValue(str);
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(13);
                    cella1.setCellStyle(colStyle);
                    cella1 = rowb1.createCell(14);
                    cella1.setCellStyle(colStyle);
                    if (((List) imgList).size() > 0) {
                        sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total + ((List) imgList).size(), 0, 0));
                        sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total + ((List) imgList).size(), 1, 1));
                        sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total + ((List) imgList).size(), 2, 4));
                        sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total + ((List) imgList).size(), 5, 6));
                        sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total + ((List) imgList).size(), 7, 7));
                        sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total + ((List) imgList).size(), 8, 8));
                        sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total + ((List) imgList).size(), 9, 10));
                        sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total + ((List) imgList).size(), 11, 11));
                        Iterator var93 = ((List) imgList).iterator();

                        while (var93.hasNext()) {
                            InspectionReportImg crr = (InspectionReportImg) var93.next();
                            ++total;
                            CellRangeAddress callRangeAddressb4 = new CellRangeAddress(8 + total, 8 + total, 12, 14);
                            sheet.addMergedRegion(callRangeAddressb4);
                            rowb1 = sheet.createRow(8 + total);
                            rowb1.setHeight((short) 1000);
                            cella1 = rowb1.createCell(0);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(1);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(2);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(3);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(4);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(5);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(6);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(7);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(8);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(9);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(10);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(11);
                            cella1.setCellStyle(colStyle2);
                            cella1 = rowb1.createCell(12);
                            if (crr.getImgType().equals("0")) {
                                try {
                                    byte[] imgData = Files.readAllBytes(tempFileMap.get(crr.getImg()));
                                    insertImage(wb, patriarch, imgData, 8 + total, 0, 2);
                                } catch (Exception var97) {
                                    var97.printStackTrace();
                                }
                            } else {
                                String sheetName = crr.getImgSrc();
                                cella1.setCellFormula("HYPERLINK(\"" + sheetName + "\")");
                                cella1.setCellStyle(colright);
                            }

                            cella1 = rowb1.createCell(13);
                            cella1.setCellStyle(colStyle);
                            cella1 = rowb1.createCell(14);
                            cella1.setCellStyle(colStyle);
                        }
                    } else {
                        sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total, 2, 4));
                        sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total, 5, 6));
                        sheet.addMergedRegion(new CellRangeAddress(8 + total, 8 + total, 9, 10));
                    }
                }
            }
        }

        return wb;
    }

    private static HSSFCellStyle createCellStyle(HSSFWorkbook workbook, short fontsize, boolean flag, boolean flag1) {
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setWrapText(true);
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints(fontsize);
        font.setBold(flag);
        style.setFont(font);
        return style;
    }

    private static CellStyle createCellStyle(SXSSFWorkbook workbook, short fontsize, boolean flag, boolean flag1) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setWrapText(true);
        Font font = workbook.createFont();
        font.setFontHeightInPoints(fontsize);
        font.setBold(flag);
        style.setFont(font);
        return style;
    }

    private static HSSFCellStyle createCellStylenoborder(HSSFWorkbook workbook, short fontsize, boolean flag, boolean flag1) {
        HSSFCellStyle style = workbook.createCellStyle();
        style.setWrapText(true);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        if (flag1) {
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
        }

        style.setWrapText(true);
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints(fontsize);
        font.setBold(flag);
        style.setFont(font);
        return style;
    }

    private static CellStyle createCellStylenoborder(SXSSFWorkbook workbook, short fontsize, boolean flag, boolean flag1) {
        CellStyle style = workbook.createCellStyle();
        style.setWrapText(true);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        if (flag1) {
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
        }

        style.setWrapText(true);
        Font font = workbook.createFont();
        font.setFontHeightInPoints(fontsize);
        font.setBold(flag);
        style.setFont(font);
        return style;
    }

    private static void insertImage(HSSFWorkbook wb, HSSFPatriarch pa, byte[] data, int row, int column, int index) {
        int x1 = 0;
        int y1 = 0;
        int x2 = 1023;
        int y2 = 0;
        HSSFClientAnchor anchor = new HSSFClientAnchor(x1, y1, x2, y2, (short) 12, row - 1, (short) 14, row + 1);
        pa.createPicture(anchor, wb.addPicture(data, 5)).resize(1.0D);
    }

    private static void insertImage(SXSSFWorkbook wb, SXSSFDrawing pa, byte[] data, int row, int column, int index) {
        int x1 = 0;
        int y1 = 0;
        int x2 = 1023;
        int y2 = 255;
        if (data != null && data.length != 0) {
            XSSFClientAnchor anchor = new XSSFClientAnchor(x1, y1, x2, y2, (short) 12, row - 1, (short) 15, row + 1);
            pa.createPicture(anchor, wb.addPicture(data, 5));
        }
    }

    private static void insertImageLingzhou(SXSSFWorkbook wb, SXSSFDrawing pa, byte[] data, int row, int column, int index) {
        int x1 = 0;
        int y1 = 0;
        int x2 = 1023;
        int y2 = 255;
        if (data != null && data.length != 0) {
            XSSFClientAnchor anchor = new XSSFClientAnchor(x1, y1, x2, y2, (short) 15, row - 1, (short) 18, row + 1);
            pa.createPicture(anchor, wb.addPicture(data, 5));
        }
    }

    public byte[] images(String imgSrc, Map<String, byte[]> inputStreamMap) {
        byte[] bytes = (byte[]) inputStreamMap.get(imgSrc);
        return bytes;
    }

    private static HSSFCellStyle getColRight(HSSFWorkbook workbook, short fontsize, boolean flag, boolean flag1) {
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        if (flag1) {
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
        }

        style.setWrapText(true);
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints(fontsize);
        font.setBold(flag);
        font.setColor((short) 4);
        style.setFont(font);
        return style;
    }

    private static CellStyle getColRight(SXSSFWorkbook workbook, short fontsize, boolean flag, boolean flag1) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        if (flag1) {
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
        }

        style.setWrapText(true);
        Font font = workbook.createFont();
        font.setFontHeightInPoints(fontsize);
        font.setBold(flag);
        font.setColor((short) 4);
        style.setFont(font);
        return style;
    }

    public static byte[] getStringByInputStream(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            byte[] b = new byte[10240];

            int n;
            while ((n = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, n);
            }
        } catch (Exception var5) {
            var5.printStackTrace();

            try {
                inputStream.close();
                outputStream.close();
            } catch (Exception var4) {
                var4.printStackTrace();
            }
        }

        return outputStream.toByteArray();
    }

    /**
     * 自适应行高（手动计算）
     *
     * @param sheet
     * @param rowNum  行号
     * @param cellNum 列号
     * @param style   样式
     */
    public void autoFitRowHeight(Sheet sheet, int rowNum, int cellNum, CellStyle style) {
        Row row = sheet.getRow(rowNum);
        if (row == null) {
            return;
        }
        Cell cell = row.getCell(cellNum);
        if (cell == null) {
            return;
        }

        String text = cell.getStringCellValue();
        if (text == null || text.isEmpty()) {
            return;
        }

        int columnWidth = sheet.getColumnWidth(0);
        double widthInChars = columnWidth / 256.0;

        // 获取字体
        double fontHeightInPoints = 15.0;
        try {
            // todo 注意getFontIndexAsInt()，在poi 6.0.0会被废弃
            Font font = sheet.getWorkbook().getFontAt(style.getFontIndexAsInt());
            fontHeightInPoints = font.getFontHeightInPoints();
        } catch (Exception e) {
            logger.error("POI GET FONT ERROR :", e.getMessage());
        }
        // 计算每行可容纳字符数（近似公式）
        // 粗略估计
        double charsPerLine = widthInChars * 1.0;

        // 按换行符分割 + 按列宽折行
        String[] lines = text.split("\n");
        int totalLines = 0;

        for (String line : lines) {
            int lineChars = line.length();
            int linesNeeded = (int) Math.ceil(lineChars / charsPerLine);
            totalLines += Math.max(1, linesNeeded);
        }

        // 设置行高（1 行 ≈ 15 磅，POI 用 points）
        double rowHeightInPoints = totalLines * fontHeightInPoints;
        row.setHeightInPoints((float) Math.max(rowHeightInPoints, row.getHeightInPoints()));
    }

    @GetMapping({"/test"})
    public AjaxResult test(int count) {
        String strs = "menglei/2.jpg,menglei/1123.jpg";
        String[] imsg = strs.split(",");

        for (int i = 0; i < count; ++i) {
            InspectionReportData inspection = new InspectionReportData();
            inspection.setReportId("53");
            inspection.setCode(Long.valueOf((long) i));
            inspection.setArea("间隔单元");
            inspection.setTimeInterval("间隔单元");
            inspection.setEqName("测试设备02");
            inspection.setParts("测试设备02_测试设备部件0301A");
            inspection.setPointName("测试设备部件0301A-广角-安全帽");
            inspection.setDataSources("高清视频");
            inspection.setAcquisitionTime(new Date());
            inspection.setPointStatus("正常");
            int sa = this.inspectionReportDataService.insertInspectionReportData(inspection);

            for (int a = 0; a < imsg.length; ++a) {
                InspectionReportImg InspectionReportImg = new InspectionReportImg();
                InspectionReportImg.setImgType(a + "");
                InspectionReportImg.setImgSrc(imsg[a]);
                InspectionReportImg.setImg(imsg[a]);
                InspectionReportImg.setReportInfoId(sa + "");
                this.inspectionReportImgService.insertInspectionReportImg(InspectionReportImg);
            }
        }

        return this.success();
    }

    @GetMapping({"/execl"})
    public AjaxResult execl(String lineId) {
        this.exportToExcel(lineId);
        return this.success();
    }
}
