package com.hfkj.channel.saas.utils;

import com.hfkj.config.CommonSysConst;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

/**
 * 生成协议工具
 * @className: GenerateAgreementUtil
 * @author: HuRui
 * @date: 2023/5/15
 **/
public class GenerateAgreementUtil {

    private static final Logger log = LoggerFactory.getLogger(GenerateAgreementUtil.class);

    /**
     * 生成html文件数据
     * @param template
     * @param data
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    // html 替换占位符
    public static File writeHtml(Long merId,Template template, Map<String, Object> data) throws IOException, TemplateException {
        String fileName = "merchant/"+merId+"/"+System.currentTimeMillis()+".html";
        File htmlFile = new File(CommonSysConst.getSysConfig().getFile_url(), fileName);
        FileWriter sw = new FileWriter(htmlFile);
        log.info("生成协议html, 地址:{}, 参数:{} ", htmlFile.getAbsolutePath(), data);
        template.process(data, sw);
        return htmlFile;
    }

    /**
     * html文件 转 png 示例代码
     * @param htmlFile html文件
     * @return
     * @throws IOException
     */
    public static String createAgreementPicture(Long merId,File htmlFile) throws IOException {
        String fileName = "merchant/"+merId+"/"+htmlFile.getName() + ".jpg";
        File outputFile = new File(CommonSysConst.getSysConfig().getFile_url(), fileName);
        log.info("生成图片开始, HTML地址 {}, 图片地址:{}", htmlFile.getAbsolutePath(), outputFile.getAbsolutePath());
        // windows
        // String commandProcess = "cmd.exe /c wkhtmltoimage  --width  400  --quality  94  " + htmlFile.getPath() + "  " + outputFile.getPath();
        String commandProcess = "wkhtmltoimage  --width  400  --quality  94  " + htmlFile.getPath() + "  " + outputFile.getPath();
        log.info("协议执行procommand:{}", commandProcess);
        long startTime = System.currentTimeMillis();   //获取开始时间
        Process process = Runtime.getRuntime().exec(commandProcess);
        try {
            int exitVal = process.waitFor();
            log.info("协议html转换png结果:{}", exitVal);
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.info("协议html转换png错误:{}", e.getMessage());
            throw new IOException(e);
        }
        long endTime = System.currentTimeMillis(); //获取结束时间
        log.info("程序运行时间： " + (endTime - startTime) + "ms");
        log.info("生成图片结束,地址: {}", outputFile.getPath());
        Thumbnails.of(outputFile).scale(1).outputQuality(0.9).toFile(outputFile);
        return fileName;
    }

}
