package com.inspect.insreport.controller;

import com.github.pagehelper.PageInfo;
import com.inspect.base.core.sftp.SftpClient;
import com.inspect.base.core.sftp.SftpUploadEntity;
import com.inspect.base.core.sftp.ftpClient;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.core.web.page.PageDomain;
import com.inspect.base.core.web.page.TableDataInfo;
import com.inspect.base.core.web.page.TableSupport;
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.taskftp.domain.PatrolTaskFtp;
import com.inspect.taskftp.service.IPatrolTaskFtpService;
import com.inspect.taskstatus.domain.PatrolTaskStatus;
import com.inspect.taskstatus.service.IPatrolTaskStatusService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping({"/insreport"})
public class InspectionReportController extends BaseController {
    private final IInspectionReportService inspectionReportService;
    private final IInspectionReportDataService inspectionReportDataService;
    private final IInspectionReportImgService inspectionReportImgService;
    private final SftpClient sftpClient;
    private final IPatrolTaskFtpService patrolTaskFtpService;

    @Autowired
    private IPatrolTaskStatusService patrolTaskStatusService;

    @Autowired
    private MessageUtils MessageUtils;

    public InspectionReportController(IInspectionReportService inspectionReportService, IInspectionReportDataService inspectionReportDataService, IInspectionReportImgService inspectionReportImgService, SftpClient sftpClient, IPatrolTaskFtpService patrolTaskFtpService) {
        this.inspectionReportService = inspectionReportService;
        this.inspectionReportDataService = inspectionReportDataService;
        this.inspectionReportImgService = inspectionReportImgService;
        this.sftpClient = sftpClient;
        this.patrolTaskFtpService = patrolTaskFtpService;
    }

    @GetMapping({"/list"})
    public TableDataInfo list(InspectionReport inspectionReport) {
//        startPage();
        List<InspectionReport> inspectionReportList = inspectionReportService.selectByAllList(inspectionReport);

        logger.info("[REPORT] inspectionReportList size: {}", inspectionReportList.size());
        // 根据 inspectionTaskName 和 inspectionDate 组合去重
        List<InspectionReport> distinctList = inspectionReportList.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toMap(
                                report -> report.getInspectionTaskName() + "_" +
                                        (report.getInspectionDate() != null ? DateUtils.format("yyyy-MM-dd",report.getInspectionDate()) : "null"),
                                Function.identity(),
                                (existing, replacement) -> existing
                        ),
                        map -> map.values().stream()
                                .sorted(Comparator.comparing(InspectionReport::getInspectionDate,
                                        Comparator.nullsLast(Comparator.reverseOrder())))
                                .collect(Collectors.toList())
                ));

        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageNum = pageDomain.getPageNum();
        int pageSize = pageDomain.getPageSize();
        int toNum = Math.min(distinctList.size(), pageNum * pageSize);
        List<InspectionReport> pageList = distinctList.subList((pageNum - 1) * pageSize, toNum);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setRows(pageList);
        rspData.setMsg("查询成功");
        rspData.setTotal((new PageInfo<>(distinctList)).getTotal());
        return rspData;
    }

    public Map<String, String> getImgMap() {
        Map<String, String> map = new HashMap<>();
        InspectionReportImg inspectionReportImg = new InspectionReportImg();
        List<InspectionReportImg> imageList = inspectionReportImgService.selectInspectionReportImgList(inspectionReportImg);
        imageList.forEach((img) -> {
            List<String> reportInfoIdList = new ArrayList<>();
            String reportInfoId;
            if (StringUtils.isNotEmpty(img.getReportInfoId())) {
                reportInfoId = map.get(img.getReportInfoId());
                if (reportInfoId != null) {
                    reportInfoIdList.add(reportInfoId);
                }
                reportInfoIdList.add(img.getImg());
            }

            if (!imageList.isEmpty()) {
                reportInfoId = String.join(StringUtils.COMMA, reportInfoIdList);
                map.put(img.getReportInfoId(), reportInfoId);
            }
        });
        return map;
    }

    @GetMapping({"/{type}/{lineId}/{filter}"})
    public AjaxResult getInfo(@PathVariable("type") String type, @PathVariable("lineId") Long lineId, @PathVariable(value = "filter",required = false) String filter) {
        InspectionReport inspectionReport = new InspectionReport();
        if ("report".equals(type)) {
            inspectionReport = inspectionReportService.selectInspectionReportByLineId(lineId);
        } else if("taskStatus".equals(type)) {
            // 暂时这么处理（进度条报告入口，lineId传的是patrolTaskStatus的lineId）
            PatrolTaskStatus patrolTaskStatus = patrolTaskStatusService.selectPatrolTaskStatusByLineId(lineId);
            String taskPatrolledId = patrolTaskStatus.getTaskPatrolledId();
            inspectionReport = new InspectionReport();
            inspectionReport.setTaskPatrolledId(taskPatrolledId);
            inspectionReport.setFilter(filter);
            logger.info("进度条报告查看,filter:{},taskPatrolledId:{}", filter, taskPatrolledId);
            List<InspectionReport> inspectionReports = inspectionReportService.selectInspectionReportList(inspectionReport);
            if (inspectionReports.size() > 0) {
                inspectionReport = inspectionReports.get(0);
                lineId = inspectionReport.getLineId();
            } else {
                return AjaxResult.error("报告不存在: " + lineId);
            }
        }
        InspectionReportData inspectionReportData = new InspectionReportData();
        inspectionReportData.setReportId(String.valueOf(lineId));
        List<InspectionReportData> inspectionReportDataList =
                inspectionReportDataService.selectInspectionReportDataList(inspectionReportData);
        // 收集所有需要查询的lineId
        List<String> lineIds = inspectionReportDataList.stream()
                .map(InspectionReportData::getLineId)
                .filter(StringUtils::isNotBlank)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询图片数据
        Map<String, String> imageMap = Collections.emptyMap();
        if (!lineIds.isEmpty()) {
            // 批量查询
            List<InspectionReportImg> allImages = inspectionReportImgService.selectByReportInfoIds(lineIds);

            // 按reportInfoId分组，拼接图片URL
            imageMap = allImages.stream()
                    .filter(img -> StringUtils.isNotBlank(img.getReportInfoId()))
                    .filter(img -> StringUtils.isNotBlank(img.getImg()))
                    .collect(Collectors.groupingBy(
                            InspectionReportImg::getReportInfoId,
                            Collectors.mapping(
                                    InspectionReportImg::getImg,
                                    Collectors.joining(StringUtils.COMMA)
                            )
                    ));
        }

        // 设置图片数据
        for (InspectionReportData reportData : inspectionReportDataList) {
            // 记录日志（根据实际情况调整日志级别，避免生产环境过多日志）
            logger.debug("reportData: {}", reportData);

            // 从缓存中获取图片URL
            String imgUrls = imageMap.get(reportData.getLineId());
            if (StringUtils.isNotBlank(imgUrls)) {
                reportData.setInspectionImg(imgUrls);
            }
        }


        inspectionReport.setInfo(inspectionReportDataList);
        return AjaxResult.success(inspectionReport);
    }

    @GetMapping({"/shaoxing/{type}/{lineId}/{filter}"})
    public AjaxResult getInfo_shaoxing(@PathVariable("type") String type, @PathVariable("lineId") Long lineId, @PathVariable(value = "filter",required = false) String filter) {
        InspectionReport inspectionReport = new InspectionReport();
        if ("report".equals(type)) {
            inspectionReport = inspectionReportService.selectInspectionReportByLineId(lineId);
        } else if("taskStatus".equals(type)) {
            // 暂时这么处理（进度条报告入口，lineId传的是patrolTaskStatus的lineId）
            PatrolTaskStatus patrolTaskStatus = patrolTaskStatusService.selectPatrolTaskStatusByLineId(lineId);
            String taskPatrolledId = patrolTaskStatus.getTaskPatrolledId();
            inspectionReport.setTaskPatrolledId(taskPatrolledId);
            inspectionReport.setFilter(filter);
            logger.info("进度条报告查看,filter:{},taskPatrolledId:{}", filter, taskPatrolledId);
            List<InspectionReport> inspectionReports = inspectionReportService.selectInspectionReportList(inspectionReport);
            if (inspectionReports.size() > 0) {
                inspectionReport = inspectionReports.get(0);
                lineId = inspectionReport.getLineId();
            } else {
                return AjaxResult.error("报告不存在: " + lineId);
            }
        }
        InspectionReportData inspectionReportData = new InspectionReportData();
        inspectionReportData.setReportId(String.valueOf(lineId));
        List<InspectionReportData> inspectionReportDataList =
                inspectionReportDataService.selectInspectionReportDataList(inspectionReportData);
        // 收集所有需要查询的lineId
        List<String> lineIds = inspectionReportDataList.stream()
                .map(InspectionReportData::getLineId)
                .filter(StringUtils::isNotBlank)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询图片数据
        Map<String, String> imageMap = Collections.emptyMap();
        if (!lineIds.isEmpty()) {
            // 批量查询
            List<InspectionReportImg> allImages = inspectionReportImgService.selectByReportInfoIds(lineIds);

            // 按reportInfoId分组，拼接图片URL
            imageMap = allImages.stream()
                    .filter(img -> StringUtils.isNotBlank(img.getReportInfoId()))
                    .filter(img -> StringUtils.isNotBlank(img.getImg()))
                    .collect(Collectors.groupingBy(
                            InspectionReportImg::getReportInfoId,
                            Collectors.mapping(
                                    InspectionReportImg::getImg,
                                    Collectors.joining(StringUtils.COMMA)
                            )
                    ));
        }

        // 设置图片数据
        for (InspectionReportData reportData : inspectionReportDataList) {
            // 记录日志（根据实际情况调整日志级别，避免生产环境过多日志）
            logger.debug("reportData: {}", reportData);

            // 从缓存中获取图片URL
            String imgUrls = imageMap.get(reportData.getLineId());
            if (StringUtils.isNotBlank(imgUrls)) {
                reportData.setInspectionImg(imgUrls);
            }
            if (StringUtils.isEmpty(reportData.getTaskName())) {
                reportData.setTaskName(inspectionReport.getInspectionTaskName());
            }
            if (StringUtils.isEmpty(reportData.getTaskPatrolledId())) {
                reportData.setTaskPatrolledId(inspectionReport.getTaskPatrolledId());
            }
            if (StringUtils.isEmpty(reportData.getTaskResultId())) {
                reportData.setTaskResultId(inspectionReport.getTaskResultId());
            }
        }


//        inspectionReport.setInfo(inspectionReportDataList);
        Map<String, List<Map<String, List<InspectionReportData>>>> resultTaskInfoMap = new HashMap<>();
        // 按 pointStatus 分组，再按 taskResultId_taskName 分组
        // key: pointStatus，value: {taskResultId_taskName -> List<InspectionReportData>}
        Map<String, Map<String, List<InspectionReportData>>> detailGrouped =
                inspectionReportDataList.stream()
                        .collect(Collectors.groupingBy(
                                item -> item.getPointStatus() == null ? "unknown" : item.getPointStatus(),
                                Collectors.groupingBy(item -> item.getTaskResultId() + "_" + item.getTaskName())
                        ));
        // 将分组结果转换为所需的格式
        for (Map.Entry<String, Map<String, List<InspectionReportData>>> stringMapEntry : detailGrouped.entrySet()) {
            // key：taskPatrolledId_taskName -> value：List<InspectionReportData>
            Map<String, List<InspectionReportData>> value = stringMapEntry.getValue();

            List<Map<String, List<InspectionReportData>>> collect = value.entrySet().stream().map(entry -> {
                Map<String, List<InspectionReportData>> resultHashMap = new HashMap<>();
                // 从分组中的任意一个元素获取 taskName（因为同一分组内 taskName 相同）
                String taskName = entry.getValue().get(0).getTaskName();
                resultHashMap.put(taskName, entry.getValue());
                return resultHashMap;
            }).collect(Collectors.toList());
            resultTaskInfoMap.put(stringMapEntry.getKey(), collect);
        }

        inspectionReport.setDetail(resultTaskInfoMap);


        return AjaxResult.success(inspectionReport);
    }

    @Log(
            title = "巡视报告头数据",
            businessType = BizType.INSERT
    )
    @PostMapping
    public AjaxResult add(@RequestBody InspectionReport inspectionReport) {
        return toAjax(inspectionReportService.insertInspectionReport(inspectionReport));
    }

    @Log(
            title = "巡视报告头数据",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult edit(@RequestBody InspectionReport inspectionReport) {
        return toAjax(inspectionReportService.updateInspectionReport(inspectionReport));
    }

    @Log(
            title = "巡视报告头数据",
            businessType = BizType.DELETE
    )
    @PostMapping({"/remove/{lineIds}"})
    public AjaxResult remove(@PathVariable Long[] lineIds) {
        return toAjax(inspectionReportService.deleteInspectionReportByLineIds(lineIds));
    }

    public void downloadXlsWright(HttpServletResponse response) {
        InspectionReport inspectionReport = inspectionReportService.selectInspectionReportByLineId(2L);
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        try {
            hssfWorkbook = getHSSFWorkbook(hssfWorkbook, inspectionReport, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fn = "xlsx" + sdf.format(new Date()) + ".xlsx";
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        try {
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fn, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
            hssfWorkbook.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (hssfWorkbook != null) {
                try {
                    hssfWorkbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public HSSFWorkbook getHSSFWorkbook(HSSFWorkbook wb, InspectionReport inspectionReport, Map<String, byte[]> inputStreamMap) throws Exception {
        if (wb == null) {
            wb = new HSSFWorkbook();
        }

        HSSFSheet sheet = wb.createSheet(String.valueOf(System.currentTimeMillis()));
        HSSFCellStyle colStyle = createCellStyle(wb, (short) 15, true, true);
        HSSFCellStyle colStyle2 = createCellStyleNoBorder(wb, (short) 15, true, true);
        HSSFCellStyle colRight = crigh(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);
        HSSFRow row0 = sheet.createRow(0);
        row0.setHeight((short) 600);
        HSSFCell cell0 = row0.createCell(0);
        cell0.setCellValue(MessageUtils.get("巡视报告"));
        HSSFCellStyle hssfCellStyle = wb.createCellStyle();
        hssfCellStyle.setAlignment(HorizontalAlignment.CENTER);
        hssfCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 20);
        font.setFontHeight((short) 500);
        font.setBold(true);
        hssfCellStyle.setFont(font);
        cell0.setCellStyle(hssfCellStyle);
        HSSFRow row1 = sheet.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 row2 = sheet.createRow(2);
        HSSFCell cell21 = row2.createCell(0);
        cell21.setCellValue(MessageUtils.get("巡视计划创建日期"));
        cell21.setCellStyle(colStyle2);
        HSSFCell cell22 = row2.createCell(4);
        if (inspectionReport.getInspectionDate() != null) {
            cell22.setCellValue(DateUtils.format(DateUtils.yyyyMMdd2, inspectionReport.getInspectionDate()));
        }

        cell22.setCellStyle(colStyle2);
        HSSFCell cell23 = row2.createCell(8);
        cell23.setCellValue(MessageUtils.get("变电站类别"));
        cell23.setCellStyle(colStyle2);
        HSSFCell 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);
            }
        }

        HSSFRow row3 = sheet.createRow(3);
        HSSFCell cell31 = row3.createCell(0);
        cell31.setCellValue(MessageUtils.get("巡视任务"));
        cell31.setCellStyle(colStyle2);
        HSSFCell cell32 = row3.createCell(4);
        cell32.setCellValue(inspectionReport.getInspectionTaskName());
        cell32.setCellStyle(colStyle2);
        HSSFCell cell33 = row3.createCell(8);
        cell33.setCellValue("环境信息");
        cell33.setCellStyle(colStyle2);
        HSSFCell 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);
            }
        }

        HSSFRow row4 = sheet.createRow(4);
        HSSFCell cell41 = row4.createCell(0);
        cell41.setCellValue(MessageUtils.get("审核人"));
        cell41.setCellStyle(colStyle2);
        HSSFCell cell42 = row4.createCell(4);
        cell42.setCellValue(inspectionReport.getCheckPerson());
        cell42.setCellStyle(colStyle2);
        HSSFCell cell43 = row4.createCell(8);
        cell43.setCellValue(MessageUtils.get("审核时间"));
        cell43.setCellStyle(colStyle2);
        HSSFCell cell44 = row4.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 = row4.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

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

        cell52.setCellStyle(colStyle2);
        HSSFCell cell53 = row5.createCell(8);
        cell53.setCellValue(MessageUtils.get("巡视结束时间"));
        cell53.setCellStyle(colStyle2);
        HSSFCell cell54 = row5.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 = row5.createCell(i);
                cell14.setCellStyle(colStyle2);
            }
        }

        HSSFRow row6 = sheet.createRow(6);
        row6.setHeight((short) 1000);
        HSSFCell cell61 = row6.createCell(0);
        cell61.setCellValue(MessageUtils.get("巡视统计"));
        cell61.setCellStyle(colStyle2);
        HSSFCell 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);
        }

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

        for (int j = 0; j < 15; ++j) {
            if (j != 0 && j != 4) {
                cell14 = row7.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 inspectionReportData1 = new InspectionReportData();
        inspectionReportData1.setPointStatus(MessageUtils.get("正常"));
        list.add(inspectionReportData1);
        int total = 0;
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();

        label178:
        for (Iterator<InspectionReportData> iterator = list.iterator(); iterator.hasNext(); total += 2) {
            InspectionReportData arr = iterator.next();
            CellRangeAddress cellRangeAddress1 = new CellRangeAddress(9 + total, 9 + total, 0, 14);
            sheet.addMergedRegion(cellRangeAddress1);
            HSSFRow rowa1 = sheet.createRow(9 + total);
            HSSFCell cella1 = rowa1.createCell(0);
            cella1.setCellValue(arr.getPointStatus() + MessageUtils.get("点位汇总"));
            HSSFCellStyle cellStyle = wb.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            HSSFFont wbFont = wb.createFont();
            wbFont.setFontHeightInPoints((short) 20);
            cellStyle.setFont(wbFont);
            cella1.setCellStyle(cellStyle);

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

            CellRangeAddress cellAddresses = new CellRangeAddress(10 + total, 10 + total, 12, 14);
            sheet.addMergedRegion(cellAddresses);
            rowa1 = sheet.createRow(10 + total);
            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.setCellValue(MessageUtils.get("设备"));
            cella1.setCellStyle(colStyle2);
            cella1 = rowa1.createCell(4);
            cella1.setCellValue(MessageUtils.get("部件"));
            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 reportData = new InspectionReportData();
            reportData.setReportId(inspectionReport.getLineId() + "");
            reportData.setPointStatus(arr.getPointStatus());
            List<InspectionReportData> inspectionReportDataList =
                    inspectionReportDataService.selectInspectionReportDataList(reportData);
            Iterator<InspectionReportData> iterator1 = inspectionReportDataList.iterator();
            while (true) {
                while (true) {
                    if (!iterator1.hasNext()) {
                        continue label178;
                    }

                    InspectionReportData brr = iterator1.next();
                    ++total;
                    InspectionReportImg inspectionReportImg = new InspectionReportImg();
                    inspectionReportImg.setReportInfoId(brr.getLineId());
                    List<InspectionReportImg> imgList = this.inspectionReportImgService.selectInspectionReportImgList(inspectionReportImg);
                    CellRangeAddress cellRangeAddress = new CellRangeAddress(10 + total, 10 + total, 12, 14);
                    sheet.addMergedRegion(cellRangeAddress);
                    HSSFRow rowb1 = sheet.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.getTimeInterval());
                    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.getPointStatus());
                    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()) {
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 0, 0));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 1, 1));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 2, 2));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 3, 3));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 4, 4));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 5, 6));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 7, 7));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 8, 8));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 9, 10));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + total + imgList.size(), 11, 11));

                        for (InspectionReportImg crr : imgList) {
                            ++total;
                            CellRangeAddress rangeAddress = new CellRangeAddress(10 + total, 10 + total, 12, 14);
                            sheet.addMergedRegion(rangeAddress);
                            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 e) {
                                    e.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, 5, 6));
                        sheet.addMergedRegion(new CellRangeAddress(10 + total, 10 + 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 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 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);
    }

    public byte[] image2bytes(String imgSrc) {
        byte[] bytes = null;
        try {
            FileInputStream fin = new FileInputStream(imgSrc);
            bytes = new byte[fin.available()];
            fin.read(bytes);
            fin.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bytes;
    }

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

    private static HSSFCellStyle crigh(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;
    }

    @PostMapping({"/export"})
    public void downloadAll(HttpServletRequest request, HttpServletResponse response) {
        Map<String, byte[]> streamHashMap = new HashMap<>();
        List<String> imgSrcList = new ArrayList<>();
        String fileName = "总览.zip";
        String lineId = request.getParameter("lineId");
        InspectionReport inspectionReport = this.inspectionReportService.selectInspectionReportByLineId(Long.valueOf(lineId));
        InspectionReportData inspectionReportData = new InspectionReportData();
        inspectionReportData.setReportId(String.valueOf(inspectionReport.getLineId()));
        List<InspectionReportData> inspectionReportDataList =
                this.inspectionReportDataService.selectInspectionReportDataList(inspectionReportData);
        if (inspectionReportDataList != null && !inspectionReportDataList.isEmpty()) {
            inspectionReport.setReportDatalist(inspectionReportDataList);
            for (InspectionReportData reportData : inspectionReportDataList) {
                InspectionReportImg inspectionReportImg = new InspectionReportImg();
                inspectionReportImg.setReportInfoId(reportData.getLineId());
                List<InspectionReportImg> inspectionReportImgList
                        = this.inspectionReportImgService.selectInspectionReportImgList(inspectionReportImg);
                if (inspectionReportImgList != null && !inspectionReportImgList.isEmpty()) {
                    reportData.setReportImgList(inspectionReportImgList);
                    for (InspectionReportImg reportImg : inspectionReportImgList) {
                        if (StringUtils.isNotEmpty(reportImg.getImgSrc())) {
                            imgSrcList.add(reportImg.getImgSrc());
                        }
                    }
                }
            }

            try {
                File zipFile = File.createTempFile("download", ".zip");
                FileOutputStream f = new FileOutputStream(zipFile);
                CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
                ZipOutputStream zos = new ZipOutputStream(csum);
                for (String imgSrc : imgSrcList) {
                    try {
                        String name = "a" + System.currentTimeMillis() + ".jpg";
                        zos.putNextEntry(new ZipEntry(name));
                        this.sftpClient.downLoad(imgSrc, (inputStream) -> {
                            byte[] imgSrcBytes = streamHashMap.get(imgSrc);
                            byte[] bytes = getStringByInputStream(inputStream);
                            if (imgSrcBytes == null) {
                                streamHashMap.put(imgSrc, bytes);
                            }

                            zos.write(bytes);
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
                hssfWorkbook = this.getHSSFWorkbook(hssfWorkbook, inspectionReport, streamHashMap);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                hssfWorkbook.write(bos);
                byte[] byteArray = bos.toByteArray();
                InputStream inputStream = new ByteArrayInputStream(byteArray);
                String name = "巡视报告.xlsx";
                zos.putNextEntry(new ZipEntry(name));

                int bytesRead;
                while ((bytesRead = inputStream.read()) != -1) {
                    zos.write(bytesRead);
                }

                inputStream.close();
                zos.closeEntry();
                zos.close();
                String header = request.getHeader("User-Agent").toUpperCase();
                if (!header.contains("MSIE") && !header.contains("TRIDENT") && !header.contains("EDGE")) {
                    fileName = new String(fileName.getBytes(), "ISO8859-1");
                } else {
                    fileName = URLEncoder.encode(fileName, "utf-8");
                    fileName = fileName.replace("+", "%20");
                }

                response.reset();
                response.setContentType("text/plain");
                response.setContentType("application/octet-stream; charset=utf-8");
                response.setHeader("Location", fileName);
                response.setHeader("Cache-Control", "max-age=0");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                FileInputStream fis = new FileInputStream(zipFile);
                BufferedInputStream buff = new BufferedInputStream(fis);
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
                byte[] car = new byte[1024];
                int l = 0;

                while ((long) l < zipFile.length()) {
                    int j = buff.read(car, 0, 1024);
                    l += j;
                    out.write(car, 0, j);
                }

                fis.close();
                buff.close();
                response.flushBuffer();
                out.close();
                zipFile.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    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 e) {
            e.printStackTrace();

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

        return outputStream.toByteArray();
    }

    @Log(
            title = "阀厅巡检报告数据入库",
            businessType = BizType.INSERT
    )
    @PostMapping({"/saveReport"})
    public AjaxResult saveReport(@RequestBody InspectionReport inspectionReport) {
        this.logger.info("==============进入阀厅巡检报告数据入库功能=====================");
        System.out.println("==============进入阀厅巡检报告数据入库功能=====================");
        if (inspectionReport.getCheckPerson() == null) {
            inspectionReport.setCheckPerson("阀厅系统");
            inspectionReport.setCheckTime(new Date());
            inspectionReport.setTaskId("0000");
        }

        if (inspectionReport.getInspectionDate() == null) {
            inspectionReport.setInspectionDate(new Date());
        }

        InputStream inputStream = null;
        String filePath = "";
        PatrolTaskFtp patrolTaskFtp = patrolTaskFtpService.selectPatrolTaskFtpByLineId(4L);

        int i;
        try {
            i = inspectionReport.getFilePath().lastIndexOf("/");
            String fileName = inspectionReport.getFilePath().substring(i + 1);
            inputStream = ftpClient.login(patrolTaskFtp.getFtpIp(), Integer.parseInt(patrolTaskFtp.getFtpPort()), patrolTaskFtp.getFtpUserName(), patrolTaskFtp.getFtpPwd(), fileName, inspectionReport.getFilePath());
            if (inputStream == null) {
                return AjaxResult.error("文件下载失败");
            }

            SftpUploadEntity sftpUploadEntity = new SftpUploadEntity(inputStream);
            sftpUploadEntity.setFileFullName("/Model" + inspectionReport.getFilePath());
            sftpUploadEntity.setInputStream(inputStream);
            sftpUploadEntity.setFileName(fileName);
            sftpUploadEntity.setSuffix(".xls");
            filePath = this.sftpClient.upload(sftpUploadEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }

        i = 0;
        if (!"".equals(filePath)) {
            inspectionReport.setFilePath("/" + filePath);
            i = this.inspectionReportService.insertInspectionReport(inspectionReport);
        }

        return this.toAjax(i);
    }
}
