package com.pusong.common.doc.util;

import com.alibaba.fastjson.JSON;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PdfGenerator {

    private static final Logger log = LoggerFactory.getLogger(PdfGenerator.class);
    //标题
    public static final String HEAD = "head";
    //是否签章
    public static final String SIGN = "isSign";
    public static  Configuration configuration =null;
    static {
        configuration = new Configuration(Configuration.VERSION_2_3_31);
        // 设置模板目录
        File file = new File(System.getProperty("user.dir") + "/doc");
        try {
            configuration.setDirectoryForTemplateLoading(file);
        } catch (IOException e) {
            configuration =null;
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) throws Exception {


//        // 创建数据模型
//        Map<String, Object> data = new HashMap<>();
//        data.put("text1", "天津浦颂企业管理咨询有限公司");
//        data.put("text2", "");
//        data.put("total", 1000);
//        List<Map<String,String>> map = new ArrayList<>();
//        Map<String,String> map1=new HashMap<>();
//        map1.put("id","7894564123");
//        map.add(map1);
//        Map<String,String> map2 =new HashMap<>();
//        map2.put("id","7894564123");
//        map.add(map2);
//        data.put("items",map);
//
//        // 设置模板目录
//        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
//        configuration.setDirectoryForTemplateLoading(new File(System.getProperty("user.dir")+"\\doc"));
//        // 加载模板
//        Template template = configuration.getTemplate("report.ftl");
//        data.put("imagePath",System.getProperty("user.dir"));
//        // 生成HTML
//        String html = processTemplate(template, data);
//        // 生成PDF
//        generatePdf(html, "D:/王立帅/临时/output.pdf");
        String str = "{\"business\":[{\"businessAmount\":500,\"businessType\":\"1\",\"contractCode\":\"\",\"detailBos\":[{\"amount\":100,\"amountDesc\":\"备注\",\"businessProject\":\"1\",\"businessProjectLabel\":\"测试1\",\"contractCode\":\"\",\"id\":0}],\"id\":0}],\"contract\":{\"applyDate\":1722355200000,\"companyId\":0,\"contractAmount\":500,\"contractCode\":\"\",\"contractMain\":\"1\",\"contractName\":\"合同名称\",\"customId\":1816388144534081538,\"customManager\":1,\"customScene\":\"\",\"isProxy\":\"\",\"params\":{},\"payModeDesc\":\"支付方式\",\"signDesc\":\"描述描述\"},\"company\":{\"companyAccountBank\":\"银行编码\",\"companyAccountBankAdress\":\"开户行地址\",\"companyAdress\":\"公司地址\",\"companyName\":\"公司名\",\"customId\":0,\"id\":0,\"legalPersonIdcard\":\"法人身份证\",\"legalPersonName\":\"法人姓名\",\"legalPersonPhone\":\"法人手机号\"},\"customer\":{\"black\":\"0\",\"createBy\":1,\"createDept\":103,\"createTime\":1721895655000,\"customLevel\":\"2\",\"customManager\":3,\"customMobile\":\"13511245332\",\"customName\":\"东洲\",\"customSource\":\"抖音\",\"customStatus\":\"1\",\"delFlag\":0,\"id\":1816388144534081538,\"params\":{},\"tenantId\":\"000000\",\"updateBy\":1,\"updateTime\":1723097358000}}";
        Map map = JSON.parseObject(str, Map.class);
        map.put(HEAD,"sss");
        map.put(SIGN,true);
        makePdf(map,"D:/王立帅/临时/output.pdf","report.ftl");
    }


    public static void makePdf(Map<String, Object> data, String pdfpath, String templateName) throws Exception{
        // 加载模板
        Template template = configuration.getTemplate(templateName);
        data.put("imagePath",System.getProperty("user.dir"));
        // 生成HTML
        String html = processTemplate(template, data);
        // 生成PDF
        PDFBuilder builder = new PDFBuilder(data.get(HEAD),data.get(SIGN),System.getProperty("user.dir"));
        generatePdf(html, pdfpath, builder);

    }
    private static String processTemplate(Template template, Map<String, Object> data) throws IOException, TemplateException {
        StringWriter writer = new StringWriter();
        template.process(data, writer);
        return writer.toString();
    }

    private static void generatePdf(String html, String outputPath,PDFBuilder builder)  {
        Document document = null;
        PdfWriter writer = null;
        try{
            document = new Document(PageSize.A4, 36, 36, 50, 50);
            writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));

            writer.setPageEvent(builder);
            document.open();
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(html.getBytes()),
                    XMLWorkerHelper.class.getResourceAsStream("/default.css"),
                    Charset.forName("UTF-8"),
                    new CustomXMLWorkerFontProvider());
        }catch (Exception e){
            log.error("生成pdf异常",e);
        }finally {
            if(document != null){
                document.close();
            }
            if(writer != null){
                writer.close();
            }
        }


    }
}
