package com.yaoyicloud.render;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 抽象渲染器
 *
 */
public abstract class AbstractRender {

    /*
    * 导出文件位置
    */
    protected final String cwd;

    /*
     * Docx结果文件路径
     */
    protected String docxResultPath;

    /*
     * html结果文件路径
     */
    protected String htmlResultPath;

    /*
     * pdf结果文件路径
     */
    protected String pdfResultPath;

    public AbstractRender(String cwd) {
        this.cwd = cwd;
    }

    /**
     * Docx 渲染
     *
     * @param jsonStr 数据
     * @param addtionalMap 全局数据和动态增加的数据
     * @param templateFileContent 模板内容
     * @return 本地文件目录
     * @throws IOException
     */
    public final String renderDocx(String jsonStr, Map<String, Object> addtionalMap, byte[] templateFileContent,
        ConfigureBuilder builder, String outputPath) throws IOException {

        // 注： 报告模板的模板变量按照json序列化的结果命名
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> data = objectMapper.readValue(jsonStr, new TypeReference<Map<String, Object>>() {});
        data.putAll(addtionalMap);

        Configure config = builder.build();
        XWPFTemplate template =
            XWPFTemplate.compile(new ByteArrayInputStream(templateFileContent), config).render(data);
        template.writeToFile(outputPath);
        template.close();

        this.docxResultPath = outputPath;
        return this.docxResultPath;
    }

    /**
     * docx转换为pdf
     *
     * @return 本地文件目录
     * @throws IOException
     */
    public final String fromDocxToPdf() throws IOException {
        // 转换 docxResultPath 为 html
        // 加工html
        // 把 html 文件转成 pdf
        fromDocxToHtml();
        this.pdfResultPath = fromHtmlToPdf();
        return this.pdfResultPath;
    }

    /**
     * docx转换为Html
     *
     * @return 本地文件目录
     * @throws IOException
     */
    public final String fromDocxToHtml() throws IOException {
        // 转换 docxResultPath 为 html
        // 加工html
        this.htmlResultPath = cwd + "/1.html";
        return this.htmlResultPath;
    }

    /**
     * html转换为pdf
     *
     * @return 本地文件目录
     * @throws IOException
     */
    public final String fromHtmlToPdf() throws IOException {
        // 转换 htmlResultPath 为 pdf
        this.pdfResultPath = cwd + "/1.pdf";
        return this.pdfResultPath;
    }

}
