package com.yeejoin.amos.knowledgebase.face.util.pdf;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.IBlockElement;
import com.itextpdf.layout.element.IElement;
import com.itextpdf.layout.font.FontProvider;
import com.yeejoin.amos.knowledgebase.face.util.IOConfig;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import static com.yeejoin.amos.knowledgebase.face.util.DataTransformator.inputStream2Bytes;

/**
 * pdf导出工具
 *
 * @author tiantao
 */
public class PdfBuilder {

    private static final ConverterProperties CP;

    static {
        CP = new ConverterProperties();
        // 设置字体
        FontProvider fontProvider = new DefaultFontProvider(false, false, false);
        boolean success = false;
        try(InputStream font = PdfBuilder.class.getClassLoader().getResourceAsStream("fonts/msyh.ttf")) {
            fontProvider.addFont(inputStream2Bytes(font));
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!success) {
            fontProvider.addStandardPdfFonts();
        }
        CP.setFontProvider(fontProvider);
        CP.setCharset("utf-8");
    }

    public static byte[] html2Pdf(String html, String docTitle) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        org.jsoup.nodes.Document htmlDocument = Jsoup.parseBodyFragment(html, "UTF-8");
        for (Element imgDocument : htmlDocument.getElementsByTag("img")) {
            String src = imgDocument.attr("src");
            if (null != src && src.length() > 0 && src.startsWith(IOConfig.PIC_ROUTER)) {
                imgDocument.attr("src", src.replaceFirst(IOConfig.PIC_ROUTER, IOConfig.PIC_URI));
            }
        }
        replaceElement(htmlDocument);
        String htmlStr = htmlDocument.html();

        PdfDocument pd = new PdfDocument(new PdfWriter(os));
        pd.getDocumentInfo().setTitle(docTitle);
        Document document = new Document(pd, PageSize.A4);
        try {
            // 设置页面边距 必须先设置边距，再添加内容，否则页边距无效
            document.setMargins(20, 32, 20, 32);
            List<IElement> list = HtmlConverter.convertToElements(htmlStr, CP);
            for (IElement ie : list) {
                document.add((IBlockElement) ie);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
        return os.toByteArray();
    }

    /**
     * 替换显示效果不好的页面元素
     *
     * @param element body
     */
    static void replaceElement(Element element) {
        Elements inputs = element.getElementsByTag("input");
        inputs.forEach(input -> {
            String type = input.attr("type");
            String value = input.attr("value");
            if (type != null) {
                switch (type.trim()) {
                    case "datetime-local":
                        input.removeAttr("type");
                        if (value != null && value.trim().length() > 0) {
                            input.attr("value", value.trim().replaceAll("/", "-").replaceAll("T", " "));
                        }
                        break;
                    case "text":
                        break;
                    default:

                }
            }
        });
        Elements textareas = element.getElementsByTag("textarea");
        textareas.forEach(textarea -> {
            String value = textarea.attr("value");
            textarea.tagName("div").clearAttributes().attr("style", "font-size: 14px; line-height: 30px; padding: 0 7px; border-radius: 4px; border: solid 1px #dedede;");
            String text = "";
            if (value != null) {
                text += text + value;
            }
            textarea.appendChild(new TextNode(text));
        });
    }
}
