package cn.ezhizao.common.utils;

import cn.ezhizao.common.utils.pdf.PdfWaterMarker;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.extension.service.IService;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.font.FontProvider;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.util.Map;

public class PdfUtil {
    @Autowired
    private Configuration configuration;

    @Value("${ruoyi.pdfFontPath.url}")
    private static String fontPath;

    /**
     * 获取模板内容
     *
     * @param templateDirectory 模板文件夹
     * @param templateName      模板文件名
     * @param paramMap          模板参数
     * @return
     * @throws Exception
     */
    public static String getTemplateContent(String templateDirectory, String templateName, Map<String, Object> paramMap) throws Exception {
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateDirectory));
        } catch (Exception e) {
            System.out.println("-- exception --");
        }

        Writer out = new StringWriter();
        Template template = configuration.getTemplate(templateName, "UTF-8");
        template.process(paramMap, out);
        out.flush();
        out.close();
        return out.toString();
    }

    /**
     * HTML 转 PDF
     *
     * @param content html内容
     * @param outPath 输出pdf路径
     * @return 是否创建成功
     */
    public static boolean html2Pdf(String content, String outPath) {
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setCharset("UTF-8");
            FontProvider fontProvider = new FontProvider();
            PdfFont simsun = PdfFontFactory.createFont(FontProgramFactory.createFont("simsun.ttc", 1, false));
            fontProvider.addFont(simsun.getFontProgram());
//            fontProvider.addDirectory("/usr/share/fonts/chinese/");
//            fontProvider.addDirectory("D:\\code\\yzbh\\ezhizao_yzbh_production_api\\fonts\\chinese");
            fontProvider.addSystemFonts();
            converterProperties.setFontProvider(fontProvider);
            HtmlConverter.convertToPdf(content, new FileOutputStream(outPath), converterProperties);
        } catch (Exception e) {
            System.out.println("生成模板内容失败,{}" + e);
            return false;
        }
        return true;
    }


    /**
     * HTML 转 PDF
     *
     * @param content html内容
     * @return PDF字节数组
     */
    public static byte[] html2Pdf(String content,PageSize pageSize) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setCharset("UTF-8");
            FontProvider fontProvider = new DefaultFontProvider(true, true, false);
            PdfFont simsun = PdfFontFactory.createFont(FontProgramFactory.createFont("simsun.ttc", 1, false));
            fontProvider.addFont(simsun.getFontProgram());
            fontProvider.addSystemFonts();
//            System.out.println(fontProvider.getFontSet().getFonts().stream().map(l -> l.getFontName()).collect(Collectors.joining(",")));
            converterProperties.setFontProvider(fontProvider);

            //设置pdf纸张
            PdfWriter writer = new PdfWriter(outputStream);
            PdfDocument pdf = new PdfDocument(writer);
            pdf.setTagged();
            //设置纸张的大小，并且设置默认的pdf大小
            if (pageSize == null ){
                pageSize = PageSize.A3.rotate();
            }
            pdf.setDefaultPageSize(pageSize);
            pdf.getDefaultPageSize().applyMargins(80, 80, 20, 20, true);
            HtmlConverter.convertToPdf(content, pdf, converterProperties);
        } catch (Exception e) {
            System.out.print("生成 PDF 失败,{}" + e);
        }
        return outputStream.toByteArray();
    }
    public static byte[] html2Pdf(String content) {
        return html2Pdf(content, (PageSize) null);
    }
    /**
     * 带水印的pdf
     * @param waterMarkerType 水印类型 1 文字水印 2 图片水印
     * @param content 详情
     * @param waterMarket 水印内容 假设为文字水印 则内容为文字，假设为图片水印 内容为图片地址
     * @param service 获取图片用的类型
     * @return 返回字节数组
     */
    public static byte[] html2Pdf(int waterMarkerType, String content, String waterMarket, IService service) {
        // waterMarkerType 水印类型 假设为 1 为文字水印 假设为 2 为图片水印
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setCharset("UTF-8");
            FontProvider fontProvider = new DefaultFontProvider(true, true, false);
            PdfFont simsun = PdfFontFactory.createFont(FontProgramFactory.createFont("simsun.ttc", 1, false));
            fontProvider.addFont(simsun.getFontProgram());
            fontProvider.addSystemFonts();
//            System.out.println(fontProvider.getFontSet().getFonts().stream().map(l -> l.getFontName()).collect(Collectors.joining(",")));
            converterProperties.setFontProvider(fontProvider);

            //设置pdf纸张
            PdfWriter writer = new PdfWriter(outputStream);
            PdfDocument pdf = new PdfDocument(writer);

            pdf.setTagged();
            //设置纸张的大小，并且设置默认的pdf大小
            PageSize pageSize = PageSize.A3.rotate();
            pdf.setDefaultPageSize(pageSize);
            switch (waterMarkerType) {
                case 1:
                    pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new PdfWaterMarker(waterMarket, simsun));
                    break;
                case 2:
                    InputStream is = service.getClass().getResourceAsStream(waterMarket);
                    byte[] bytes = IoUtil.readBytes(is);
                    Image img = new Image(ImageDataFactory.create(bytes));
                    pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new PdfWaterMarker(img));
            }
            HtmlConverter.convertToPdf(content, pdf, converterProperties);
        } catch (Exception e) {
            System.out.print("生成 PDF 失败,{}" + e);
        }
        return outputStream.toByteArray();
    }

    /**
     * 带水印的pdf
     * @param waterMarkerType 水印类型 1 文字水印 2 图片水印
     * @param content 详情
     * @param waterMarket 水印内容 假设为文字水印 则内容为文字，假设为图片水印 内容为图片地址
     * @param service 获取图片用的类型
     * @return 状态 是否创建成功
     */
    public static boolean html2Pdf(int waterMarkerType, String content, String waterMarket, IService service, String outPath) {
        // waterMarkerType 水印类型 假设为 1 为文字水印 假设为 2 为图片水印
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setCharset("UTF-8");
            FontProvider fontProvider = new DefaultFontProvider(true, true, false);
            PdfFont simsun = PdfFontFactory.createFont(FontProgramFactory.createFont("simsun.ttc", 1, false));
            fontProvider.addFont(simsun.getFontProgram());
            fontProvider.addSystemFonts();
//            System.out.println(fontProvider.getFontSet().getFonts().stream().map(l -> l.getFontName()).collect(Collectors.joining(",")));
            converterProperties.setFontProvider(fontProvider);

            //设置pdf纸张
            PdfWriter writer = new PdfWriter(outputStream);
            PdfDocument pdf = new PdfDocument(writer);

            pdf.setTagged();
            //设置纸张的大小，并且设置默认的pdf大小
            PageSize pageSize = PageSize.A3.rotate();
            pdf.setDefaultPageSize(pageSize);
            switch (waterMarkerType) {
                case 1:
                    pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new PdfWaterMarker(waterMarket, simsun));
                    break;
                case 2:
                    InputStream is = service.getClass().getResourceAsStream(waterMarket);
                    byte[] bytes = IoUtil.readBytes(is);
                    Image img = new Image(ImageDataFactory.create(bytes));
                    pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new PdfWaterMarker(img));
            }
            HtmlConverter.convertToPdf(content, new FileOutputStream(outPath), converterProperties);
        } catch (Exception e) {
            System.out.print("生成 PDF 失败,{}" + e);
            return false;
        }
        return true;
    }
}