package com.ruoyi.project.plant.controller;

import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.document.service.ITPlantproglistService;
import com.ruoyi.project.document.service.ITPublicdocService;
import com.ruoyi.project.ehs.service.ITEhskpinewService;
import com.ruoyi.project.ehs.service.impl.TJobticketServiceImpl;
import com.ruoyi.project.plant.service.ITAwardrecordService;
import com.ruoyi.project.plant.service.ITTargetreviewService;
import com.ruoyi.project.process.service.ITAlarmmodifyService;
import com.ruoyi.project.production.domain.TMonthplan;
import com.ruoyi.project.production.service.ITAccidentService;
import com.ruoyi.project.production.service.ITAlarmstatisticsMonthService;
import com.ruoyi.project.production.service.ITMonthplanService;
import com.ruoyi.project.production.service.ITWsglService;
import com.ruoyi.project.reliability.service.ITAbnormalreportService;
import com.ruoyi.project.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * 报告自动生成Generatereport
 *
 * @author chenqi
 * @date 2020-12-22
 */
@RestController
@RequestMapping("/plant/generatereport")
public class GeneratereportController extends BaseController {

    @Autowired
    private ITTargetreviewService targetreviewService;

    @Autowired
    private ITMonthplanService tMonthplanService;

    @Autowired
    private ITAlarmmodifyService alarmmodifyService;

    @Autowired
    private ITEhskpinewService tEhskpinewService;

    @Autowired
    private ITAccidentService accidentService;
    @Autowired
    private ITAlarmstatisticsMonthService alarmstatisticsMonthService;
    @Autowired
    private ITEhskpinewService ehskpinewService;
    @Autowired
    private TJobticketServiceImpl jobticketService;
    @Autowired
    private ITAbnormalreportService abnormalreportService;
    @Autowired
    private ITPublicdocService publicdocService;
    @Autowired
    private ITPlantproglistService plantproglistService;

    /**
     * 生成报告
     */
//    @PreAuthorize("@ss.hasPermi('plant:generatereport:export')")
//    @GetMapping("/export/{ids}")
//    public void export(@PathVariable Long[] ids, HttpServletRequest request, HttpServletResponse response) {
//        /*for (Long i : ids) {
//            logger.info("i:" + i);
//        }*/
//
//    }

    /**
     * 自动生成报告
     */
    @RequestMapping(value = "/export", produces = "application/json;charset=utf-8")
    @ResponseBody
    public void AutoReport(HttpServletRequest request, HttpServletResponse response, Long year) {
        logger.info("exportexportexportexportexportexportexport");
        String savePath = request.getSession().getServletContext().getRealPath("/"); // 系统根路径
        String tempUrl = "";
                tempUrl =  "static/word/report-gcs-template.docx"; // 经理模板文件
        // 保存结果文
        InputStream is = null;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(tempUrl);
            XWPFDocument doc = new XWPFDocument(is);
            // 替换word模板数据
            List<POIXMLDocumentPart> relations = doc.getRelations();

//            relations.remove(4);
//            relations.remove(5);
//            relations.remove(6);
//            relations.remove(7);
//            relations.remove(8);
            replaceAll(doc,year);

            response.setContentType("application/octet-stream");// 下载,默认就是下载
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + URLEncoder.encode("Report" + ".docx", "UTF-8"));
            // 刷新缓冲
            response.flushBuffer();
            OutputStream ouputStream = response.getOutputStream();
            doc.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 替换段落和表格
     */
    private void replaceAll(XWPFDocument doc, Long year) throws Exception {
        TMonthplan tMonthplan = new TMonthplan();
        tMonthplan.setYear(2020l);
        List<TMonthplan> monList = tMonthplanService.selectTMonthplanList(tMonthplan);
        doParagraphs(doc, monList);// 处理段落文字数据，包括文字和表格、图片
        doCharts(doc, monList); // 处理图表数据，柱状图、折线图、饼图、组合图之类的
    }

    /**
     * 处理段落文字数据，包括文字和表格、图片
     *
     * @param doc
     * @param monList
     *            生产计划月报list
     *            主页角色ID
     *
     *            一个文档包含多个段落，一个段落包含多个Runs，一个Runs包含多个Run，Run是文档的最小单元
     */
    private void doParagraphs(XWPFDocument doc, List<TMonthplan> monList) {
        // 文本数据
        Calendar cal = Calendar.getInstance();
        Map<String, String> textMap = new HashMap<String, String>();
        textMap.put("year", String.valueOf(cal.get(Calendar.YEAR)));
        textMap.put("month", String.valueOf(cal.get(Calendar.MONTH) + 1));
        textMap.put("targetreview", "");
        /** ----------------------------处理段落------------------------------------ **/
        List<XWPFParagraph> paragraphList = doc.getParagraphs();
        int num = -1;
        if (paragraphList != null && paragraphList.size() > 0) {
            for (XWPFParagraph paragraph : paragraphList) {
                List<XWPFRun> runs = paragraph.getRuns();
//                paragraph.removeRun(0);
//                paragraph.removeRun(1);
                num++;
                logger.info("段落======" + num);
                for (XWPFRun run : runs) {
                    String text = run.getText(0);
                    logger.info("text======" + text);
                    if (text == null) {
                    }
                    if (text != null) {
                        // 替换文本信息
                        String tempText = text;
                        String key = tempText.replaceAll("\\{\\{", "").replaceAll("}}", "");
                        if (!StringUtils.isEmpty(textMap.get(key))) {
                            run.setText(textMap.get(key), 0);
                        }

                        /**
                         * ----------------------------替换表格数据
                         * ------------------------------------
                         **/
                         doJLParagraphs(doc, paragraph, run, tempText,monList);// 处理段落文字数据，包括文字和表格、图片
                    }
                }
            }
        }
        //
    }
    /**
     * 处理段落文字--经理
     *
     * @param doc
     * @throws InvalidFormatException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void doJLParagraphs(XWPFDocument doc, XWPFParagraph paragraph, XWPFRun run, String text,
                               List<TMonthplan> monList) {
        // 动态表格 ---目标回顾
        if (text.contains("${table1}")) {
            targetreviewService.dealTargetreview(doc, paragraph, run);
        }
        // 动态表格 ---报警值修改
        if (text.contains("${table2}")) {
            alarmmodifyService.dealAlarmmodify(doc, paragraph, run);
        }
        // 动态表格 ---乙烯产量及OAE
        if (text.contains("${table3}")) {
            tMonthplanService.dealMonthplan(doc, paragraph, run, monList, 1);
        }
        // 动态表格 ---芳烃产量及OAE
        if (text.contains("${table4}")) {
            tMonthplanService.dealMonthplan(doc, paragraph, run, monList, 2);
        }
        // 动态表格 ---产能利用率/工厂损失
        if (text.contains("${table5}")) {
            tMonthplanService.dealMonthplan(doc, paragraph, run, monList, 3);
        }
        // 动态表格 ---能源消耗
        if (text.contains("${table6}")) {
            tMonthplanService.dealMonthplan(doc, paragraph, run, monList, 4);
        }
        // 动态表格 --- COD排放
        if (text.contains("${table7}")) {
            tMonthplanService.dealMonthplan(doc, paragraph, run, monList, 5);
        }
        // 动态表格 ---隐患排查
        if (text.contains("${table8}")) {
            accidentService.dealAccident(doc, paragraph, run);
        }
        // 动态表格 ---报警统计
        if (text.contains("${table9}")) {
            alarmstatisticsMonthService.dealAlarmstatistics(doc, paragraph, run);
        }
//        // 动态表格 ---KPI统计及表格
        if (text.contains("${table10}")) {
            ehskpinewService.dealKPI(doc, paragraph, run);
        }
//        // 动态表格 ---工作票
        if (text.contains("${table11}")) {
            jobticketService.dealJobticket(doc, paragraph, run);
        }
//        // 动态表格 ---异常报告管理
        if (text.contains("${table12}")) {
            abnormalreportService.dealAbnormalreport(doc, paragraph, run);
        }
//        // 动态表格 ---表格汇总
        if (text.contains("${table13}")) {
            publicdocService.dealPublicdoc(doc, paragraph, run);
        }
//        // 动态表格 ---程序汇总
        if (text.contains("${table14}")) {
            plantproglistService.dealPlantproglist(doc, paragraph, run);
        }
    }

    // ==================================================================================================================================================
    // 图表处理
    // ==================================================================================================================================================

    /**
     * 处理图表
     *
     * @param doc
     * @throws FileNotFoundException
     */
    public void doCharts(XWPFDocument doc, List<TMonthplan> monList) throws FileNotFoundException {
        /** ----------------------------处理图表------------------------------------ **/
        // 获取word模板中的所有图表元素，用map存放
        // 为什么不用list保存：查看doc.getRelations()的源码可知，源码中使用了hashMap读取文档图表元素，
        // 对relations变量进行打印后发现，图表顺序和文档中的顺序不一致，也就是说relations的图表顺序不是文档中从上到下的顺序
        Map<String, POIXMLDocumentPart> chartsMap = new HashMap<String, POIXMLDocumentPart>();
        // 动态刷新图表
        List<POIXMLDocumentPart> relations = doc.getRelations();
        int num = 0;

        for (POIXMLDocumentPart poixmlDocumentPart : relations) {
            if (poixmlDocumentPart instanceof XWPFChart) { // 如果是图表元素
                // 获取图表对应的表格数据里面的第一行第一列数据，可以拿来当作key值
                // String text = PoiWordTools.getZeroData(poixmlDocumentPart);
                logger.error(num + "!!!");

                String str = poixmlDocumentPart.toString();
                logger.info("str：" + str);
                String key = str.replaceAll("Name: ", "")
                        .replaceAll(
                                " - Content Type: application/vnd\\.openxmlformats-officedocument\\.drawingml\\.chart\\+xml",
                                "")
                        .trim();
                logger.info("key：" + key);
                chartsMap.put(key, poixmlDocumentPart);
            }
            num ++;
        }
        logger.info("\n图表数量：" + chartsMap.size() + "\n");
        tMonthplanService.doChartsYX(chartsMap, monList, 1);
        tMonthplanService.doChartsFT(chartsMap, monList, 2);
        tMonthplanService.doChartsCN(chartsMap, monList, 3);
        tMonthplanService.doChartsNYXH(chartsMap, monList, 4);
        tMonthplanService.doChartsCOD(chartsMap, monList, 5);
        logger.info("\n图表数量：" + chartsMap.size() + "\n");
    }


}
