package com.tuoheng.admin.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lowagie.text.*;
import com.tuoheng.admin.common.ServiceExceptionEnum;
import com.tuoheng.admin.entity.domain.Question;
import com.tuoheng.admin.entity.domain.QuestionHandle;
import com.tuoheng.admin.entity.domain.Report;
import com.tuoheng.admin.entity.domain.ThMission;
import com.tuoheng.admin.entity.request.ReportRequest;
import com.tuoheng.admin.entity.vo.*;
import com.tuoheng.admin.enums.*;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.service.IQuestionService;
import com.tuoheng.admin.service.IReportService;
import com.tuoheng.admin.service.IThInspectionService;
import com.tuoheng.admin.utils.ImgTypeConvert;
import com.tuoheng.admin.utils.WordUtilsOld;
import com.tuoheng.common.common.BaseServiceImpl;
import com.tuoheng.common.config.CommonConfig;
import com.tuoheng.common.config.UploadFileConfig;
import com.tuoheng.common.exception.ServiceException;
import com.tuoheng.common.utils.DateUtils;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.common.utils.StringUtils;
import com.tuoheng.system.service.impl.UserServiceImpl;
import com.tuoheng.system.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 巡检报告表 服务实现类
 *
 * @author qiujinyang
 * @since 2022-08-04
 */
@Slf4j
@Service
public class ReportServiceImpl extends BaseServiceImpl<ReportMapper, Report> implements IReportService {

    @Autowired
    private ThInspectionMapper inspectionMapper;

    @Autowired
    private IThInspectionService inspectionService;

    @Autowired
    private ThMissionMapper missionMapper;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private IQuestionService questionService;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private QuestionHandleMapper questionHandleMapper;


    @Override
    public JsonResult generateReport(Integer missionId) {

        Assert.notNull(missionId,"任务ID为空");
        String reportNo = createReportNo();
        //查询巡检信息
        LambdaQueryWrapper<ThMission> queryWrapper = new LambdaQueryWrapper<>();//xz
        queryWrapper.eq(ThMission::getTenantId, ShiroUtils.getTenantId()).eq(ThMission::getId, missionId);//xz
        ThMission mission = missionMapper.selectOne(queryWrapper);//xz
        Assert.notNull(mission,"任务不能为空！");

        //如果报告已经生成，就修改，如果未生成就创建
        if(mission.getReportStatus() == ReportStatusEnum.GENERATE.getCode()){
            //生成报告
            Report report = setInfo(missionId, reportNo, mission);
            reportMapper.insert(report);
        }else if(mission.getReportStatus() == ReportStatusEnum.UPDATE.getCode()){
            Report update = reportMapper.selectOne(new LambdaQueryWrapper<Report>().eq(Report::getMissionId, missionId).
                    eq(Report::getTenantId, ShiroUtils.getTenantId()));//xz

            if(ObjectUtil.isEmpty(update)){
                //生成报告
                Report report = setInfo(missionId, reportNo, mission);
                reportMapper.insert(report);
            }else{
                update.setWeather(mission.getWeather());
                update.setGenerateTime(new Date());
                //修改报告
                reportMapper.updateById(update);
            }

        }
        //更新任务的状态
        mission.setReportStatus(ReportStatusEnum.UN_GENERATE.getCode());
        missionMapper.updateById(mission);

        return JsonResult.success(missionMapper.updateById(mission)>0);
    }

    private Report setInfo(Integer missionId, String reportNo, ThMission mission) {
        Report report = new Report(UpdateOrCreateEnum.CREATE.getCode());
        report.setTenantId(ShiroUtils.getTenantId());//xz
        report.setReportNo(reportNo);
        report.setMissionId(missionId);
        report.setMissionName(mission.getName());
        report.setExecutionStartTime(mission.getExecutionStartTime());
        report.setGenerateTime(new Date());
        report.setAirportId(mission.getAirportId());
        report.setAirportName(mission.getAirportName());
        report.setTenantId(mission.getTenantId());
        report.setType(mission.getType());
        report.setInspectionType(mission.getInspectionType());
        report.setWeather(mission.getWeather());
        return report;
    }

    @Override
    public JsonResult<IPage<Report>> queryPage(ReportRequest request) {
        if(null == request.getPage() || null == request.getLimit()){
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        // 获取分页数据
        IPage<Report> page = new Page<>(request.getPage(), request.getLimit());
        IPage<Report> pageData = reportMapper.selectPage(page, new LambdaQueryWrapper<Report>()
                .eq(Report::getTenantId, ShiroUtils.getTenantId())//xz
                .like(StringUtils.isNotEmpty(request.getReportNo()), Report::getReportNo, request.getReportNo())
                .like(StringUtils.isNotEmpty(request.getName()), Report::getMissionName, request.getName())
                .eq(StringUtils.isNotEmpty(request.getAirportId()), Report::getAirportId, request.getAirportId())
                .eq(ObjectUtil.isNotEmpty(request.getType()), Report::getType, request.getType())
                .eq(Report::getMark, MarkTypeEnum.VALID.getCode())
                .orderByDesc(Report::getCreateTime));
        return JsonResult.success(pageData);
    }

    @Override
    public ReportInfoVO detail(Integer reportId) {
        ReportInfoVO reportInfoVO = new ReportInfoVO();
        //查询报告
        LambdaQueryWrapper<Report> queryWrapper = new LambdaQueryWrapper<>();//xz
        queryWrapper.eq(Report::getTenantId,ShiroUtils.getTenantId()).eq(Report::getId, reportId);//xz
        Report report = reportMapper.selectOne(queryWrapper);//xz
        Integer missionId = report.getMissionId();
        reportInfoVO.setReportNo(report.getReportNo());
        reportInfoVO.setMissionId(missionId);
        reportInfoVO.setCompany("汤山林场");
        reportInfoVO.setLcName("汤山林场");
        //任务信息
        setMission(reportInfoVO, missionId);
        //添加巡检天气
        reportInfoVO.setAirWeather(report.getWeather());
        //setWeather(reportInfoVO, report);
        //查询巡检结果
        setQueestionCount(reportInfoVO, missionId);
        //问题类型
        setQuestionType(reportInfoVO, missionId);
        //查询问题清单
        setQuestonList(reportInfoVO, missionId);
        return reportInfoVO;
    }

//    private void setWeather(ReportInfoVO reportInfoVO, Report report) {
//        reportInfoVO.setAirWeather(inspectionService.getWeather(report.getAirportId()));
//    }

    private void setMission(ReportInfoVO reportInfoVO, Integer missionId) {
        LambdaQueryWrapper<ThMission> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ThMission::getTenantId, ShiroUtils.getTenantId()).eq(ThMission::getId, missionId);
        ThMission thMission = missionMapper.selectOne(lambdaQueryWrapper);
        if(ObjectUtil.isEmpty(thMission)){
            thMission=new ThMission(UpdateOrCreateEnum.CREATE.getCode());
        }
        MissionVO missionVO=new MissionVO();
        BeanUtils.copyProperties(thMission,missionVO);
        reportInfoVO.setMission(missionVO);
    }

    private void setQuestionType(ReportInfoVO reportInfoVO, Integer missionId) {
        JsonResult<List<QuestionTypeCountVO>> analyzeType = questionService.analyzeType(missionId);
        reportInfoVO.setQuestionTypeInfo(analyzeType.getData());
    }

    private void setQueestionCount(ReportInfoVO reportInfoVO, Integer missionId) {
        JsonResult<List<QuestionCountVO>> analyze = questionService.analyze(missionId);
        Iterator<QuestionCountVO> iterator = analyze.getData().stream().iterator();
        int questionCount=0;
        while (iterator.hasNext()){
            QuestionCountVO questionCountVo = iterator.next();
            //只统计已经确认的问题
            if(QuestionStatusEnum.CONFIRM.getCode()==questionCountVo.getStatus()){
                questionCount+=questionCountVo.getQuantity();
            }
        }
        reportInfoVO.setQuestionCount(questionCount);
    }

    private void setQuestonList(ReportInfoVO reportInfoVO, Integer missionId) {
        List<Question> questionList = questionService.list(new LambdaQueryWrapper<Question>()
                //.eq(Question::getTenantId, ShiroUtils.getTenantId())
                .eq(Question::getMissionId, missionId)
                .eq(Question::getStatus, QuestionStatusEnum.CONFIRM.getCode())
        );

        List<QuestionReportVO> questionReportVOList=new ArrayList<>();
        for (Question question : questionList) {
            QuestionReportVO questionReportVO=new QuestionReportVO();
            BeanUtils.copyProperties(question,questionReportVO);
            List<QuestionHandleVO> questionHandleList = questionHandleMapper.getList(question.getId());
            for (QuestionHandleVO questionHandleVO : questionHandleList) {
                //拼接图片域名
                if(null != questionHandleVO && StringUtils.isNotEmpty(questionHandleVO.getHandlerImage())){
                    String[] imgHanders = questionHandleVO.getHandlerImage().split(",");
                    for (int i = 0; i < imgHanders.length; i++) {
                        imgHanders[i] = CommonConfig.imageURL + imgHanders[i];
                    }
                    String handerImg = StringUtils.join(imgHanders, ",");
                    questionHandleVO.setHandlerImage(handerImg);
                }
            }
            questionReportVO.setQuestionHandleList(questionHandleList);

            questionReportVOList.add(questionReportVO);
        }
        //问题列表
        reportInfoVO.setQuestionReportList(questionReportVOList);
    }

    @Override
    public String exportReportWord(Integer reportId, HttpServletRequest request, HttpServletResponse response) throws Exception {

        ReportInfoVO reportInfoVO = detail(reportId);
        //创建word
        String fileName = "汤山林场无人机巡检报告【"+ reportInfoVO.getReportNo() + "】.doc";
        String filePath = UploadFileConfig.uploadFolder+"doc/"+fileName;
        File fd = new File(UploadFileConfig.uploadFolder+"doc");
        File f = new File(filePath);
        if(!fd.exists()){
            fd.mkdirs();
        }
        WordUtilsOld wordUtils = new WordUtilsOld();

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if(f.exists()){
                f.delete();
                f.createNewFile();
            }
            log.info("开始编写word文件，文件为：{}",filePath);
            wordUtils.openDocument(filePath);
            wordUtils.getDocument().setPageSize(PageSize.A4);
            wordUtils.getDocument().setMargins(71f, 71f, 72f, 72f);
            //标题
            wordUtils.insertTitlePattern("汤山林场无人机巡检报告", WordUtilsOld.rtfGsBt1);
            wordUtils.insertContext("报告编号："+reportInfoVO.getReportNo(),10, Font.NORMAL, Element.ALIGN_RIGHT,20,0,0);
            wordUtils.insertTitlePatternThird("一：林场信息", WordUtilsOld.rtfGsBt3);
            Table table = new Table(2);//生成一表格
            table.setOffset(1f);
            int[] width = {1, 1};
            table.setWidths(width);//设置系列所占比例
            table.setWidth(100);
            table.setAutoFillEmptyCells(true);
            table.setAlignment(Element.ALIGN_LEFT);//居中显示
            for (int i = 0; i < 6; i++) {
                Cell cell = new Cell();
                String str;
                cell.setVerticalAlignment(Element.ALIGN_RIGHT);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                Font font = new Font();
                font.setSize(10.5f);
                font.setStyle(Font.BOLD);
                if (i == 0) {
                    str = "责任单位";
                    font.setStyle(Font.NORMAL);
                } else if (i == 1) {
                    str = reportInfoVO.getCompany();
                } else if (i == 2) {
                    str = "林场名称";
                    font.setStyle(Font.NORMAL);
                } else if (i == 3) {
                    str = reportInfoVO.getLcName();
                } else if (i == 4) {
                    str = "巡查里程";
                    font.setStyle(Font.NORMAL);
                } else {
                    if(StringUtils.isNotEmpty(reportInfoVO.getMission().getMileage())){
                        try{
                            BigDecimal mileageBd = new BigDecimal(reportInfoVO.getMission().getMileage()).divide(new BigDecimal(1000));
                            str = mileageBd + "公里";
                        }catch (Exception e){
                            log.info("转换里程出错：{}",e.getMessage());
                            str="";
                        }
                    }else{
                        str = "";
                    }

                }
                Paragraph p = new Paragraph(str, font);
                cell.add(p);
                table.addCell(cell);
            }
            wordUtils.getDocument().add(table);
            log.info("林场信息写入完成");

            wordUtils.insertTitlePatternThird("二：巡检信息", WordUtilsOld.rtfGsBt3);
            Table table2 = new Table(2);//生成一表格
            table2.setOffset(1f);
            int[] width2 = {1, 1};
            table2.setWidths(width2);//设置系列所占比例
            table2.setWidth(100);
            table2.setAutoFillEmptyCells(true);
            table2.setAlignment(Element.ALIGN_CENTER);//居中显示
            table2.setAlignment(Element.ALIGN_MIDDLE);//垂直居中显示


            for (int i = 0; i < 12; i++) {
                Cell cell = new Cell();
                String str;
                cell.setVerticalAlignment(Element.ALIGN_LEFT);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                Font font = new Font();
                font.setSize(10.5f);
                font.setStyle(Font.BOLD);
                if (i == 0) {
                    str = "气象信息";
                } else if (i == 1) {
                    str = reportInfoVO.getAirWeather();
                    font.setStyle(Font.NORMAL);
                } else if (i == 2) {
                    str = "巡检方式";
                } else if (i == 3) {
                    //巡检方式  1 机场服务，2 人工巡检
                    str = reportInfoVO.getMission().getInspectionType().equals(1) ? "机场服务" :"人工巡检";
                    font.setStyle(Font.NORMAL);
                } else if (i == 4) {
                    str = "巡检设备";
                } else if (i == 5) {
                    str = reportInfoVO.getMission().getDroneName();
                    font.setStyle(Font.NORMAL);
                } else if (i == 6) {
                    str = "巡检开始时间";
                } else if (i == 7) {
                    str = simpleDateFormat.format(reportInfoVO.getMission().getExecutionStartTime());
                    font.setStyle(Font.NORMAL);
                } else if (i == 8) {
                    str = "巡检结束时间";
                }else if (i == 9) {
                    str = simpleDateFormat.format(reportInfoVO.getMission().getExecutionEndTime());
                    font.setStyle(Font.NORMAL);
                } else if (i == 10) {
                    str = "问题数量";
                } else {
                    Integer questionCount = reportInfoVO.getQuestionCount();
                    str = ObjectUtil.isNotEmpty(questionCount)?questionCount.toString():"0";
                    font.setStyle(Font.NORMAL);
                }

                Paragraph p = new Paragraph(str, font);
                cell.add(p);
                table2.addCell(cell);
            }
            wordUtils.getDocument().add(table2);
            log.info("巡检信息写入完成");

            List<QuestionTypeCountVO> questionTypeInfo = reportInfoVO.getQuestionTypeInfo();
            Map<String, Integer> questionCount=new HashMap<>();
            for (QuestionTypeCountVO questionTypeCountVO : questionTypeInfo) {
                questionCount.put(questionTypeCountVO.getType(),questionTypeCountVO.getQuantity());
            }

            if(questionTypeInfo.size()>0) {
                wordUtils.insertTitlePatternThird("三：巡检结果", WordUtilsOld.rtfGsBt3);
                Table table3 = new Table(2);//生成一表格
                table3.setOffset(1f);
                int[] width3 = {1, 1};
                table3.setWidths(width3);//设置系列所占比例
                table3.setWidth(100);
                table3.setAutoFillEmptyCells(true);
                table3.setAlignment(Element.ALIGN_CENTER);//居中显示
                table3.setAlignment(Element.ALIGN_MIDDLE);//垂直居中显示


                for (int i = 0; i < 10; i++) {
                    Cell cell = new Cell();
                    String str;
                    cell.setVerticalAlignment(Element.ALIGN_CENTER);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    Font font = new Font();
                    font.setSize(10.5f);
                    font.setStyle(Font.BOLD);
                    if (i == 0) {
                        str = "巡检内容";
                    } else if (i == 1) {
                        str = "巡检检查结果";
                    } else if (i == 2) {
                        str = "林场问题图斑";
                    } else if (i == 3) {
                            if(questionCount.containsKey("002000")){
                            str = questionCount.get("002000").toString().trim();
                            font.setStyle(Font.NORMAL);
                        }else{
                            str = "0";
                            font.setStyle(Font.NORMAL);
                        }
                    } else if (i == 4) {
                        str = "病死树";
                    } else if (i == 5) {
                        if(questionCount.containsKey("002001")){
                            str = questionCount.get("002001").toString().trim();
                            font.setStyle(Font.NORMAL);
                        }else{
                            str = "0";
                            font.setStyle(Font.NORMAL);
                        }
                    } else if (i == 6) {
                        str = "人员活动";
                    } else if (i == 7) {
                        if(questionCount.containsKey("002003")){
                            str = questionCount.get("002003").toString().trim();
                            font.setStyle(Font.NORMAL);
                        }else{
                            str = "0";
                            font.setStyle(Font.NORMAL);
                        }
                    } else if (i == 8) {
                        str = "火灾隐患";
                    } else{
                        if(questionCount.containsKey("002004")){
                            str = questionCount.get("002004").toString().trim();
                            font.setStyle(Font.NORMAL);
                        }else{
                            str = "0";
                            font.setStyle(Font.NORMAL);
                        }
                    }

                    Paragraph p = new Paragraph(str, font);
                    cell.add(p);
                    table3.addCell(cell);
                }
                wordUtils.getDocument().add(table3);
            }

            log.info("巡检结果写入完成");
            if (reportInfoVO.getQuestionReportList().size() > 0) {
                wordUtils.insertTitlePatternThird("四：问题清单", WordUtilsOld.rtfGsBt3);
                log.info("报告标题四成功");
                // wordUtils.getDocument().add(new Paragraph(""));
                for (int i = 0; i < reportInfoVO.getQuestionReportList().size(); i++) {

                    Table table4 = new Table(2);//生成一表格
                    table4.setOffset(1f);
                    int[] width4 = {1, 2};
                    table4.setWidths(width4);//设置系列所占比例
                    table4.setWidth(100);
                    table4.setAutoFillEmptyCells(true);
                    table4.setAlignment(Element.ALIGN_LEFT);//居中显示
                    table4.setAlignment(Element.ALIGN_MIDDLE);//垂直居中显示
                    for (int j = 0; j < 7; j++) {
                        Cell cell = new Cell();
                        //cell.setVerticalAlignment(Element.ALIGN_LEFT);
                        //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        String str = "";
                        Font font = new Font();
                        font.setSize(10.5f);
                        cell.setVerticalAlignment(Element.ALIGN_CENTER);
                        if (j == 0) {
                            font.setSize(12);
                            str = " 问题" + (i + 1);
                            cell.add(new Paragraph(str, font));
                            cell.setColspan(2);
                            font.setStyle(Font.BOLD);
                            //cell.setVerticalAlignment(Element.ALIGN_LEFT);
                        } else if (j == 1) {
                            str = " 坐标";
                            cell.add(new Paragraph(str, font));
                        } else if (j == 2) {
                            str = reportInfoVO.getQuestionReportList().get(i).getLng() + "," + reportInfoVO.getQuestionReportList().get(i).getLat();
                            cell.add(new Paragraph(str, font));
                        } else if (j == 3) {
                            str = " 问题描述";
                            cell.add(new Paragraph(str, font));
                        } else if (j == 4) {
                            str = reportInfoVO.getQuestionReportList().get(i).getQuestionDesc();
                            cell.add(new Paragraph(str, font));
                        } else if (j == 5) {
                            str = " 问题图片";
                            cell.add(new Paragraph(str, font));
                        } else{
                            //String url = CommonConfig.imageURL + reportInfoVO.getQuestionReportList().get(i).getFileMarkerUrl();
                            Image image = null;
                            String url = reportInfoVO.getQuestionReportList().get(i).getFileMarkerUrl();
                            if (new UrlResource(url).exists()) {
                                try {
                                    image = Image.getInstance(Base64.getDecoder().decode(ImgTypeConvert.requestUrlToBase64(url)));
                                    image.setAlignment(Image.ALIGN_CENTER);
                                    image.scalePercent(100); //依照比例缩放
                                    image.setAbsolutePosition(0, 0);
                                    image.scaleToFit(300, 300);//自定义大
                                    cell.add(image);
                                }catch (Exception e){
                                    log.info("图片获取失败！");
                                    e.printStackTrace();
                                    cell.add(new Paragraph(""));
                                }
                            } else {
                                log.error("图片不存在！" + url);
                            }
                        }
                        table4.addCell(cell);

                    }
                    wordUtils.getDocument().add(table4);
                }
            }

         wordUtils.closeDocument();
         log.info("问题清单写入完成");




        //清空缓存
            /*response.reset();
            // 定义浏览器响应表头，并定义下载名
            String urlFileName = URLEncoder.encode("汤山林场无人机巡检报告【"+ reportInfoVO.getReportNo() + "】.doc", "UTF-8");
            //String urlFileName =new String(("汤山林场无人机巡检报告【"+ reportInfoVO.getReportNo() + "】.doc").getBytes(), StandardCharsets.UTF_8);
            response.setHeader("Content-Disposition", "attachment;filename=" + urlFileName);
            //response.setCharacterEncoding("utf-8");
            //定义下载的类型
            //response.setContentType("application/msword;charset=GBK");
            response.setContentType("application/msword");
            OutputStream out;
            File files = new File(filePath);

            log.info("读出的文件文件地址为：{}",filePath);
            //InputStream inputStream = this.getClass().getResourceAsStream(filePath);
            FileInputStream inputStream = new FileInputStream(files);
            //3.通过response获取ServletOutputStream对象(out)
            out = response.getOutputStream();
            int b = 0;
            byte[] buffer = new byte[1024];
            while (b != -1){
                b = inputStream.read(buffer);
                //4.写到输出流(out)中
                out.write(buffer,0,b);
            }
            inputStream.close();
            out.close();
            out.flush();*/


            System.out.println("结束。。。。。。");
        }catch (Exception e){
            log.info("异常信息：{}",e.getMessage());
            e.printStackTrace();
        }finally {
            wordUtils.closeDocument();
        }
        return UploadFileConfig.docDownLoad+"/lc/doc/"+fileName;
    }

    @Override
    public String exportReportHandleWord(Integer reportId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ReportInfoVO reportInfoVO = detail(reportId);
        //创建word
        String fileName = "汤山林场无人机处理报告【"+ reportInfoVO.getReportNo() + "】.doc";
        String filePath = UploadFileConfig.uploadFolder+"doc/"+fileName;
        File fd = new File(UploadFileConfig.uploadFolder+"doc");
        File f = new File(filePath);
        if(!fd.exists()){
            fd.mkdirs();
        }
        WordUtilsOld wordUtils = new WordUtilsOld();

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if(f.exists()){
                f.delete();
                f.createNewFile();
            }
            log.info("开始编写word文件，文件为：{}",filePath);
            wordUtils.openDocument(filePath);
            wordUtils.getDocument().setPageSize(PageSize.A4);
            wordUtils.getDocument().setMargins(71f, 71f, 72f, 72f);
            //标题
            wordUtils.insertTitlePattern("汤山林场无人机处理报告", WordUtilsOld.rtfGsBt1);
            wordUtils.insertContext("报告编号："+reportInfoVO.getReportNo(),10, Font.NORMAL, Element.ALIGN_RIGHT,20,0,0);
            wordUtils.insertTitlePatternThird("一：林场信息", WordUtilsOld.rtfGsBt3);
            Table table = new Table(2);//生成一表格
            table.setOffset(1f);
            int[] width = {1, 1};
            table.setWidths(width);//设置系列所占比例
            table.setWidth(100);
            table.setAutoFillEmptyCells(true);
            table.setAlignment(Element.ALIGN_LEFT);//居中显示
            for (int i = 0; i < 6; i++) {
                Cell cell = new Cell();
                String str;
                cell.setVerticalAlignment(Element.ALIGN_RIGHT);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                Font font = new Font();
                font.setSize(10.5f);
                font.setStyle(Font.BOLD);
                if (i == 0) {
                    str = "责任单位";
                    font.setStyle(Font.NORMAL);
                } else if (i == 1) {
                    str = reportInfoVO.getCompany();
                } else if (i == 2) {
                    str = "林场名称";
                    font.setStyle(Font.NORMAL);
                } else if (i == 3) {
                    str = reportInfoVO.getLcName();
                } else if (i == 4) {
                    str = "巡查里程";
                    font.setStyle(Font.NORMAL);
                } else {
                    if(StringUtils.isNotEmpty(reportInfoVO.getMission().getMileage())){
                        try{
                            BigDecimal mileageBd = new BigDecimal(reportInfoVO.getMission().getMileage()).divide(new BigDecimal(1000));
                            str = mileageBd + "公里";
                        }catch (Exception e){
                            log.info("转换里程出错：{}",e.getMessage());
                            str="";
                        }
                    }else{
                        str = "";
                    }

                }
                Paragraph p = new Paragraph(str, font);
                cell.add(p);
                table.addCell(cell);
            }
            wordUtils.getDocument().add(table);
            log.info("林场信息写入完成");

            wordUtils.insertTitlePatternThird("二：巡检信息", WordUtilsOld.rtfGsBt3);
            Table table2 = new Table(2);//生成一表格
            table2.setOffset(1f);
            int[] width2 = {1, 1};
            table2.setWidths(width2);//设置系列所占比例
            table2.setWidth(100);
            table2.setAutoFillEmptyCells(true);
            table2.setAlignment(Element.ALIGN_CENTER);//居中显示
            table2.setAlignment(Element.ALIGN_MIDDLE);//垂直居中显示

            for (int i = 0; i < 12; i++) {
                Cell cell = new Cell();
                String str;
                cell.setVerticalAlignment(Element.ALIGN_LEFT);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                Font font = new Font();
                font.setSize(10.5f);
                font.setStyle(Font.BOLD);
                if (i == 0) {
                    str = "气象信息";
                } else if (i == 1) {
                    str = reportInfoVO.getAirWeather();
                    font.setStyle(Font.NORMAL);
                } else if (i == 2) {
                    str = "巡检方式";
                } else if (i == 3) {
                    //巡检方式  1 机场服务，2 人工巡检
                    str = reportInfoVO.getMission().getInspectionType().equals(1) ? "机场服务" :"人工巡检";
                    font.setStyle(Font.NORMAL);
                } else if (i == 4) {
                    str = "巡检设备";
                } else if (i == 5) {
                    str = reportInfoVO.getMission().getDroneName();
                    font.setStyle(Font.NORMAL);
                } else if (i == 6) {
                    str = "巡检开始时间";
                } else if (i == 7) {
                    str = simpleDateFormat.format(reportInfoVO.getMission().getExecutionStartTime());
                    font.setStyle(Font.NORMAL);
                } else if (i == 8) {
                    str = "巡检结束时间";
                }else if (i == 9) {
                    str = simpleDateFormat.format(reportInfoVO.getMission().getExecutionEndTime());
                    font.setStyle(Font.NORMAL);
                } else if (i == 10) {
                    str = "问题数量";
                } else {
                    Integer questionCount = reportInfoVO.getQuestionCount();
                    str = ObjectUtil.isNotEmpty(questionCount)?questionCount.toString():"0";
                    font.setStyle(Font.NORMAL);
                }

                Paragraph p = new Paragraph(str, font);
                cell.add(p);
                table2.addCell(cell);
            }
            wordUtils.getDocument().add(table2);
            log.info("巡检信息写入完成");

            List<QuestionTypeCountVO> questionTypeInfo = reportInfoVO.getQuestionTypeInfo();
            Map<String, Integer> questionCount=new HashMap<>();
            for (QuestionTypeCountVO questionTypeCountVO : questionTypeInfo) {
                questionCount.put(questionTypeCountVO.getType(),questionTypeCountVO.getQuantity());
            }

            if(questionTypeInfo.size()>0) {
                wordUtils.insertTitlePatternThird("三：巡检结果", WordUtilsOld.rtfGsBt3);
                Table table3 = new Table(2);//生成一表格
                table3.setOffset(1f);
                int[] width3 = {1, 1};
                table3.setWidths(width3);//设置系列所占比例
                table3.setWidth(100);
                table3.setAutoFillEmptyCells(true);
                table3.setAlignment(Element.ALIGN_CENTER);//居中显示
                table3.setAlignment(Element.ALIGN_MIDDLE);//垂直居中显示

                for (int i = 0; i < 10; i++) {
                    Cell cell = new Cell();
                    String str;
                    cell.setVerticalAlignment(Element.ALIGN_CENTER);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    Font font = new Font();
                    font.setSize(10.5f);
                    font.setStyle(Font.BOLD);
                    if (i == 0) {
                        str = "巡检内容";
                    } else if (i == 1) {
                        str = "巡检检查结果";
                    } else if (i == 2) {
                        str = "林场问题图斑";
                    } else if (i == 3) {
                        if(questionCount.containsKey("002000")){
                            str = questionCount.get("002000").toString().trim();
                            font.setStyle(Font.NORMAL);
                        }else{
                            str = "0";
                            font.setStyle(Font.NORMAL);
                        }
                    } else if (i == 4) {
                        str = "病死树";
                    } else if (i == 5) {
                        if(questionCount.containsKey("002001")){
                            str = questionCount.get("002001").toString().trim();
                            font.setStyle(Font.NORMAL);
                        }else{
                            str = "0";
                            font.setStyle(Font.NORMAL);
                        }
                    } else if (i == 6) {
                        str = "人员活动";
                    } else if (i == 7) {
                        if(questionCount.containsKey("002003")){
                            str = questionCount.get("002003").toString().trim();
                            font.setStyle(Font.NORMAL);
                        }else{
                            str = "0";
                            font.setStyle(Font.NORMAL);
                        }
                    } else if (i == 8) {
                        str = "火灾隐患";
                    } else{
                        if(questionCount.containsKey("002004")){
                            str = questionCount.get("002004").toString().trim();
                            font.setStyle(Font.NORMAL);
                        }else{
                            str = "0";
                            font.setStyle(Font.NORMAL);
                        }
                    }
                    Paragraph p = new Paragraph(str, font);
                    cell.add(p);
                    table3.addCell(cell);
                }
                wordUtils.getDocument().add(table3);
            }

            log.info("巡检结果写入完成");
            if (reportInfoVO.getQuestionReportList().size() > 0) {
                wordUtils.insertTitlePatternThird("四：问题清单", WordUtilsOld.rtfGsBt3);
                log.info("报告标题四成功");
                for (int i = 0; i < reportInfoVO.getQuestionReportList().size(); i++) {
                    Table table4 = new Table(2);//生成一表格
                    table4.setOffset(1f);
                    int[] width4 = {1, 2};
                    table4.setWidths(width4);//设置系列所占比例
                    table4.setWidth(100);
                    table4.setAutoFillEmptyCells(true);
                    table4.setAlignment(Element.ALIGN_LEFT);//居中显示
                    table4.setAlignment(Element.ALIGN_MIDDLE);//垂直居中显示
                    //查询处理数据
                    List<QuestionHandleVO> questionHandleList = questionHandleMapper.getList(reportInfoVO.getQuestionReportList().get(i).getId());
                    String[] imgHanders = new String[0];
                    if(StringUtils.isNotEmpty(questionHandleList)){
                        String handlerImage = questionHandleList.get(0).getHandlerImage();
                        //拼接图片域名
                        imgHanders = handlerImage.split(",");
                        for (int h = 0; h < imgHanders.length; h++) {
                            imgHanders[h] = CommonConfig.imageURL + imgHanders[h];
                        }
                    }

                    for (int j = 0; j < 14 + imgHanders.length; j++) {
                        Cell cell = new Cell();
                        String str = "";
                        Font font = new Font();
                        font.setSize(10.5f);
                        cell.setVerticalAlignment(Element.ALIGN_CENTER);
                        if (j == 0) {
                            font.setSize(12);
                            str = " 问题" + (i + 1);
                            cell.add(new Paragraph(str, font));
                            cell.setColspan(2);
                            font.setStyle(Font.BOLD);
                        } else if (j == 1) {
                            str = " 坐标";
                            cell.add(new Paragraph(str, font));
                        } else if (j == 2) {
                            str = reportInfoVO.getQuestionReportList().get(i).getLng() + "," + reportInfoVO.getQuestionReportList().get(i).getLat();
                            cell.add(new Paragraph(str, font));
                        } else if (j == 3) {
                            str = " 问题描述";
                            cell.add(new Paragraph(str, font));
                        } else if (j == 4) {
                            str = reportInfoVO.getQuestionReportList().get(i).getQuestionDesc();
                            cell.add(new Paragraph(str, font));
                        } else if (j == 5) {
                            str = " 问题图片";
                            cell.add(new Paragraph(str, font));
                        } else if (j == 6) {
                            Image image = null;
                            String url = reportInfoVO.getQuestionReportList().get(i).getFileMarkerUrl();
                            if (new UrlResource(url).exists()) {
                                try {
                                    image = Image.getInstance(Base64.getDecoder().decode(ImgTypeConvert.requestUrlToBase64(url)));
                                    image.setAlignment(Image.ALIGN_CENTER);
                                    image.scalePercent(100); //依照比例缩放
                                    image.setAbsolutePosition(0, 0);
                                    image.scaleToFit(300, 300);//自定义大
                                    cell.add(image);
                                }catch (Exception e){
                                    log.info("图片获取失败！");
                                    e.printStackTrace();
                                    cell.add(new Paragraph(""));
                                }
                            } else {
                                log.error("图片不存在！" + url);
                            }
                        }else if (j == 7) {
                            str = " 处理人员";
                            cell.add(new Paragraph(str, font));
                        }else if (j == 8) {
                            if(StringUtils.isNotEmpty(questionHandleList)){
                                str = questionHandleList.get(0).getHandlerUserName();
                            }
                            cell.add(new Paragraph(str, font));
                        }else if (j == 9) {
                            str = " 处理时间";
                            cell.add(new Paragraph(str, font));
                        }else if (j == 10) {
                            if(StringUtils.isNotEmpty(questionHandleList)){
                                String handlerTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, questionHandleList.get(0).getHandlerTime());
                                str = handlerTime;
                            }
                            cell.add(new Paragraph(str, font));
                        }else if (j == 11) {
                            str = " 处理描述";
                            cell.add(new Paragraph(str, font));
                        }else if (j == 12) {
                            if(StringUtils.isNotEmpty(questionHandleList)){
                                str = questionHandleList.get(0).getHandlerResult();
                            }
                            cell.add(new Paragraph(str, font));
                        }else if (j == 13) {
                            str = " 处理图片";
                            cell.add(new Paragraph(str, font));
                            if(imgHanders.length > 0){
                                cell.setRowspan(imgHanders.length);
                            }
                        }else if (j >= 14) {
                            Image image = null;
                            if (new UrlResource(imgHanders[j-14]).exists()) {
                                try {
                                    image = Image.getInstance(Base64.getDecoder().decode(ImgTypeConvert.requestUrlToBase64(imgHanders[j-14])));
                                    image.setAlignment(Image.ALIGN_CENTER);
                                    image.scalePercent(100); //依照比例缩放
                                    image.setAbsolutePosition(0, 0);
                                    image.scaleToFit(300, 300);//自定义大
                                    cell.setRowspan(1);
                                    cell.add(image);
                                }catch (Exception e){
                                    log.info("图片获取失败！");
                                    e.printStackTrace();
                                    cell.add(new Paragraph(""));
                                }
                            } else {
                                log.error("图片不存在！" + imgHanders[0]);
                            }
                        }
                        table4.addCell(cell);
                    }
                    wordUtils.getDocument().add(table4);
                }
            }

            wordUtils.closeDocument();
            log.info("问题清单写入完成");
        }catch (Exception e){
            log.info("异常信息：{}",e.getMessage());
            e.printStackTrace();
        }finally {
            wordUtils.closeDocument();
        }
        return UploadFileConfig.docDownLoad+"/lc/doc/"+fileName;
    }


    /**
     * 生成报告编号，R+年月日+随机四位数
     * @return 返回报告编号
     */
    public String createReportNo(){
        String Date = DateUtils.dateTimeNow(DateUtils.YYYYMMDD);
        int randomNum = new Random().nextInt(9999) % (9999 - 1000 + 1) + 1000;
        return "R" + Date + randomNum;
    }
}
