package com.yeejoin.precontrol.common.fileparser.factory;

import com.yeejoin.precontrol.common.fileparser.product.html.AbstractHtml;
import com.yeejoin.precontrol.common.fileparser.product.html.WordHtml;
import com.yeejoin.precontrol.common.fileparser.product.pdf.AbstractPdf;
import com.yeejoin.precontrol.common.fileparser.product.pdf.WordPdf;
import com.yeejoin.precontrol.common.fileparser.product.png.AbstractPng;
import com.yeejoin.precontrol.common.fileparser.product.png.WordPng;
import com.yeejoin.precontrol.common.fileparser.product.txt.AbstractText;
import com.yeejoin.precontrol.common.fileparser.product.txt.WordText;
import lombok.extern.slf4j.Slf4j;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.AltChunkType;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class WordFactory implements AbstractFactory {

    /**
     * 将word转换为html
     *
     * @param inputFile  需要转换的word文档
     * @param outputFile 转换为html文件名称（全路径）
     * @throws Exception
     */
    @Override
    public void convert2Html(String inputFile, String outputFile) throws Exception {
        log.info("将word转换为html文件开始,输出文件 [" + outputFile + ".html]......");
        long startTime = System.currentTimeMillis();
        AbstractHtml html = new WordHtml();
        html.createHtml(inputFile, outputFile);
        log.info("将word转换为html文件......ok");
        log.info("Generate " + outputFile + ".html with " + (System.currentTimeMillis() - startTime)
                + " ms.");
    }

    @Override
    public void convert2Png(String fileName, String outPutFile) throws Exception {
        log.info("start convert Word to png,out file [" + outPutFile + ".png]......");
        long startTime = System.currentTimeMillis();
        AbstractPng png = new WordPng();
        png.createPng(fileName, outPutFile);
        log.info("将Word转换为png文件......ok");
        log.info("convert success! Generate " + outPutFile + " with "
                + (System.currentTimeMillis() - startTime) + " ms.");
    }

    @Override
    public void convert2Text(String fileName, String outPutFile) throws Exception {
        log.info("start convert Word to txt,out file [" + outPutFile + ".txt]......");
        long startTime = System.currentTimeMillis();
        AbstractText text = new WordText();
        text.createTxt(fileName, outPutFile);
        log.info("将Word转换为Word文件......ok");
        log.info("convert success! Generate " + outPutFile + ".Word with "
                + (System.currentTimeMillis() - startTime) + " ms.");
    }

    @Override
    public boolean convert2Pdf(String fileName, String outPutFile) throws Exception {
        log.info("start convert Word to pdf,out file [" + outPutFile + ".pdf]......");
        long startTime = System.currentTimeMillis();
        AbstractPdf html = new WordPdf();
        html.createPdf(fileName, outPutFile);
        log.info("将Word转换为pdf文件......ok");
        log.info("convert success! Generate " + outPutFile + ".pdf with "
                + (System.currentTimeMillis() - startTime) + " ms.");
        return false;
    }


    /**
     * html转doc
     *
     * @param file 输出doc文件
     * @param html html文本内容
     * @throws Exception
     */
    public static void html2doc(File file, String html) {
        log.info("开始html--->doc");
        try {
            WordprocessingMLPackage wordMlPackage = WordprocessingMLPackage.createPackage();
            String table = "<style type=\"text/css\"> table td{border:1px solid #000000} </style>";
            String htmlContent = "<html><head><title></title>" + table + "</head><body>" + html + "</body></html>";
            htmlContent = processDocStyle(htmlContent);
            wordMlPackage.getMainDocumentPart().addAltChunk(AltChunkType.Html, htmlContent.getBytes());
            wordMlPackage.save(file);
        } catch (Docx4JException e) {
            e.printStackTrace();
            log.error("html转doc出错:{}", e.getMessage());
        }
        log.info("转换完成html--->doc");

    }

    /**
     * 处理 doc 样式
     *
     * @param htmlContent
     * @return
     */
    private static String processDocStyle(String htmlContent) {
        Document doc = Jsoup.parse(htmlContent);
        doc.select("table").attr("cellspacing", "0px")
                .attr("cellpadding", "0px").attr("border-collapse", "collapse");
        return doc.outerHtml();
    }


    public static String closeHtml(String str) {
        List arrTags = new ArrayList();
        arrTags.add("br");
        arrTags.add("hr");
        arrTags.add("img");
        arrTags.add("meta");
        arrTags.add("META");
        for (int i = 0; i < arrTags.size(); i++) {
            for (int j = 0; j < str.length(); ) {
                int tagStart = str.indexOf("<" + arrTags.get(i), j);
                if (tagStart >= 0) {
                    int tagEnd = str.indexOf(">", tagStart);
                    j = tagEnd;
                    String preCloseTag = str.substring(tagEnd - 1, tagEnd);
                    if (!"/".equals(preCloseTag)) {
                        String preStr = str.substring(0, tagEnd);
                        String afterStr = str.substring(tagEnd);
                        str = preStr + "/" + afterStr;
                    }
                } else {
                    break;
                }
            }
        }
        return str;
    }
}

