/*
 * 版权所有 © 成都太阳高科技有限责任公司
 * http://www.suncd.com
 */
package org.jeecg.modules.stm.utils;

import com.lowagie.text.pdf.BaseFont;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.Map;

/**
 * 功能：pdf处理工具类
 *
 * @author qust
 * @version 1.0 2018/2/23 17:21
 */
public class PdfUtils {
    private PdfUtils() {
    }

    private static final Logger LOGGER = LoggerFactory.getLogger(PdfUtils.class);
    private static  String tplName= "pdfPage.ftl";
    private static  String fileName= "fxc.pdf";

    public static void setTplName(String tplName1) {
        tplName = tplName1;
    }
    public static void setFileName(String fileName1) {
        fileName = fileName1;
    }

    private static String generateDocString(FreeMarkerConfigurer configurer, Object variables){
        StringWriter writer = new StringWriter();
        try {
            Template template = configurer.getConfiguration().getTemplate(tplName);
            template.process(variables, writer);
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
        }
        writer.flush();
        return writer.toString();
    }

    @Deprecated
    private static Document generateDoc(FreeMarkerConfigurer configurer, Map<String, Object> variables)  {
        Template tp;
        try {
            tp = configurer.getConfiguration().getTemplate(tplName);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
            return null;
        }
        StringWriter stringWriter = new StringWriter();
        try(BufferedWriter writer = new BufferedWriter(stringWriter)) {
            try {
                tp.process(variables, writer);
                writer.flush();
            } catch (TemplateException e) {
                LOGGER.error("模板不存在或者路径错误", e);
            } catch (IOException e) {
                LOGGER.error("IO异常", e);
            }
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            return builder.parse(new ByteArrayInputStream(stringWriter.toString().getBytes()));
        }catch (Exception e){
            LOGGER.error(e.getMessage(), e);
            return null;
        }
    }

    private static void generateAll(FreeMarkerConfigurer cfg, OutputStream out, SubVo subVo) throws Exception {

        ITextRenderer renderer = new ITextRenderer();
        CgxVo cgxVo = new CgxVo();
        cgxVo.setCgx(subVo);

        String doc = generateDocString(cfg, cgxVo);
        renderer.setDocumentFromString(doc);
        ITextFontResolver fontResolver = (ITextFontResolver)renderer.getSharedContext().getFontResolver();
        //fontResolver.addFont("simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        fontResolver.addFont("GB2312.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        //fontResolver.addFont("fzhtjw.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        renderer.layout();
        renderer.createPDF(out, false);
        renderer.finishPDF();
    }

    public static void download(FreeMarkerConfigurer cfg, SubVo subVo, HttpServletResponse res) {
        res.setCharacterEncoding("utf-8");
        res.setContentType("multipart/form-data");
        try {
            res.setHeader("Content-Disposition", "attachment;fileName=" +
                    new String(fileName.getBytes("gb2312"), "ISO8859-1"));
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        }
//        try (ServletOutputStream out = res.getOutputStream()) {
//            generateAll(cfg, out, subVo);
//            out.flush();
//        } catch (Exception e) {
//            LOGGER.error(e.getMessage(), e);
//        }
    }

    public static void preview(FreeMarkerConfigurer cfg,SubVo subVo, HttpServletResponse res) {
//        try (ServletOutputStream out = res.getOutputStream()) {
//            generateAll(cfg, out, subVo);
//            out.flush();
//        } catch (Exception e) {
//            LOGGER.error(e.getMessage(), e);
//        }
    }
}
