package com.steerinfo.ftp.uploadfile.utils;

import fr.opensagres.poi.xwpf.converter.xhtml.Base64EmbedImgManager;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.converter.WordToHtmlUtils;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * POIExcelToHtml 文件转换：
 *
 * @author generator
 * @version 1.0-SNAPSHORT 2021-08-09 18:06
 * 类描述
 * 修订历史：
 * 日期：2021-08-09
 * 作者：shadow
 * 参考：https://blog.csdn.net/u013585096/article/details/85104888
 * 描述：Execl转HTML
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 * @see null
 */
public class POIWordToHtml {
    private static final String ENCODING = "GB2312";// UTF-8


    public String docToHtml(InputStream input) throws Exception {
        String htmlData = "预览失败";
        try {
        HWPFDocumentCore wordDocument = WordToHtmlUtils.loadDoc(input);
        WordToHtmlConverter wordToHtmlConverter = new ImageConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()
        );
        //wordToHtmlConverter.setPicturesManager(new PicturesManager() {
        //    @Override
        //    public String savePicture(byte[] content,
        //                              PictureType pictureType, String suggestedName,
        //                              float widthInches, float heightInches) {
        //            //给生成的页面写图片的路径
        //            return "word/media/" + suggestedName;
        //    }
        //});
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(outStream);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        htmlData =  outStream.toString();
        outStream.close();
        } catch (Exception e){
            e.printStackTrace();
        }
        return htmlData;
    }

    public String docxToHtml(InputStream inputStream) throws IOException {
        String htmlData = "预览失败";
        try{
        XWPFDocument docxDocument = new XWPFDocument(inputStream);
        XHTMLOptions options = XHTMLOptions.create();
            //获取文档中的图片
        //List<XWPFPictureData> allPictures = docxDocument.getAllPictures();
        //for (XWPFPictureData xwpfPictureData : allPictures) {
        //    String name = xwpfPictureData.getFileName();
        //    byte[] data = xwpfPictureData.getData();
        //    InputStream input = new ByteArrayInputStream(data);
        //    TODO 图片处理
        //
        //}
        //final String imageUrl = "";
        //不把图片生成出来
        options.setExtractor(null);
        options.setIgnoreStylesIfUnused(false);
        options.setFragment(true);
        //options.URIResolver(new IURIResolver() {
        //    @Override
        //    public String resolve(String uri) {
        //        return imageUrl + uri;
        //    }
        //});
        // 图片转base64 新版本支持
        options.setImageManager(new Base64EmbedImgManager());
         //转换htm1
        ByteArrayOutputStream htmlStream = new ByteArrayOutputStream();
        XHTMLConverter.getInstance().convert(docxDocument, htmlStream, options);
        htmlData = htmlStream.toString();
        htmlStream.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
        return htmlData;
    }

    /**
     * 图片处理
     */
    public class ImageConverter extends WordToHtmlConverter {

        public ImageConverter(Document document) {
            super(document);
        }

        @Override
        protected void processImageWithoutPicturesManager(Element currentBlock, boolean inlined, Picture picture) {
            Element imgNode = currentBlock.getOwnerDocument().createElement("img");
            StringBuffer sb = new StringBuffer();
            sb.append(Base64.getMimeEncoder().encodeToString(picture.getRawContent()));
            sb.insert(0, "data:" + picture.getMimeType() + ";base64,");
            imgNode.setAttribute("src", sb.toString());
            currentBlock.appendChild(imgNode);
        }
    }
}
