package cn.iocoder.yudao.module.product.utils;

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import gui.ava.html.parser.HtmlParser;
import gui.ava.html.parser.HtmlParserImpl;
import gui.ava.html.renderer.ImageRenderer;
import gui.ava.html.renderer.ImageRendererImpl;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.Assert;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class WordUtils1 {

    public static final Integer WIDTH = 1000;
    public static final Integer HEIGHT = 1000;

    /**
     * 根据模板和参数生成word
     */
    public static void exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params) {
        Assert.notNull(templatePath, "模板路径不能为空");
        Assert.notNull(temDir, "临时文件路径不能为空");
        Assert.notNull(fileName, "导出文件名不能为空");
        Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");
        if (!temDir.endsWith("/")) {
            temDir = temDir + File.separator;
        }
        File dir = new File(temDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            BufferedImage image = WordUtils1.wordToImage2(doc);
            FileOutputStream fos = new FileOutputStream("D://test.png");
            ImageIO.write(image, "png", fos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage wordToImage2(XWPFDocument docx) throws IOException {
        StringWriter writer = new StringWriter();
        XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
        // 获取Html
        xhtmlConverter.convert(docx, writer, null);

        // 转换得到的Html
        String html = writer.toString();
        System.out.println(html);

        HtmlParser htmlParser = new HtmlParserImpl();
        htmlParser.loadHtml(html);
        ImageRenderer imageRenderer = new ImageRendererImpl(htmlParser);
        return imageRenderer.getBufferedImage();
    }

    private static BufferedImage getGrayPicture(BufferedImage originalImage) {
        BufferedImage grayPicture;
        int imageWidth = originalImage.getWidth();
        int imageHeight = originalImage.getHeight();

        grayPicture = new BufferedImage(imageWidth, imageHeight,
                BufferedImage.TYPE_INT_RGB);
        ColorConvertOp cco = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
        cco.filter(originalImage, grayPicture);
        return grayPicture;
    }

    /**
     * Html转为Graphics2D
     * @param graphics Graphics2D
     * @param html html字符串
     * @param rect Rectangle尺寸
     */
    private static void html2Graphics(Graphics2D graphics, String html, Rectangle rect) {
        final JFrame jFrame = new JFrame("temp");
        final JEditorPane jEditorPane = new JEditorPane("text/html", html);
        jEditorPane.setSize(WIDTH, HEIGHT); //最好给个容器大小，否则图片将是一块黑色
        jFrame.getContentPane().add(jEditorPane);
        jFrame.pack();
        jFrame.setVisible(true);
        graphics.setClip(rect);
        jEditorPane.print(graphics);
        jFrame.setVisible(false);
        jFrame.dispose();
    }

    public static void main(String[] args) throws Exception {
        //加载资源文件
        ClassPathResource classPathResource = new ClassPathResource("template/inspection.docx");
        //获取文件
        File file = classPathResource.getFile();
        //获取路径
        String path = classPathResource.getPath();
//        System.out.println("path:" + path);
//        System.out.println("file:" + file);
        //转成输入流
        InputStream in = WordUtils1.class.getClassLoader().getResourceAsStream(path);
        //获取文件流
        FileInputStream inputStream = new FileInputStream(file);

        Map<String, Object> params = new HashMap<>();
        params.put("inspection_id", "aaaaaaaaaaaaaaaaaaaa");


        WordUtils1.exportWord(path, "D://temp", "test.docx", params);
    }
}
