package com.qmth.distributed.print.business.util;

import com.qmth.teachcloud.common.config.DictionaryConfig;
import com.qmth.teachcloud.common.contant.SpringContextHolder;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.enums.PageSizeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * @Description: htmltopdf
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/4/7
 */
public class HtmlToPdfUtil {
    private final static Logger log = LoggerFactory.getLogger(HtmlToPdfUtil.class);

    /**
     * html转pdf
     *
     * @param srcPath
     * @param destPath
     * @param pageSizeEnum
     * @return
     */
    public static boolean convert(String srcPath, String destPath, PageSizeEnum pageSizeEnum) throws IOException {
        File file = new File(destPath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        StringBuilder cmd = new StringBuilder();
//        if (System.getProperty("os.name").indexOf("Windows") == -1) {
        // 非windows 系统
//            toPdfTool = "/usr/local/bin/wkhtmltopdf";
//        }
        DictionaryConfig dictionaryConfig = SpringContextHolder.getBean(DictionaryConfig.class);
        cmd.append(dictionaryConfig.sysDomain().getHtmlToPdfUrl());
        cmd.append(" ");
        cmd.append(" --page-size ").append(pageSizeEnum.name()).append(" ");
        cmd.append(" --disable-smart-shrinking ");
        if (pageSizeEnum == PageSizeEnum.A3) {
            cmd.append(" --orientation Landscape ");
        }
//        cmd.append(" --page-width 1200px ");
//        cmd.append(" --page-width 1200px ");
        cmd.append("  --margin-top 0 ");
        cmd.append("  --margin-bottom 0 ");
        cmd.append("  --margin-left 0 ");
        cmd.append("  --margin-right 0 ");

        cmd.append(srcPath);
        cmd.append(" ");
        cmd.append(destPath);

        log.info("proc:{}", cmd.toString());
        boolean result = true;
        try {
            Process proc = Runtime.getRuntime().exec(cmd.toString());
            proc.waitFor();
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            result = false;
        }
        log.info("proc result:{}", result);
        return result;
    }

//    public static void main(String[] args) {
////        HtmlToPdfUtil.convert("http://www.baidu.com", "/Users/king/Downloads/baidu.pdf", PageSizeEnum.A4);
//        String filename = "3120ee49668e4bf48fd8c161a2abb73b的副本";
//        HtmlToPdfUtil.convert("/Users/king/Downloads/测试附件/" + filename + ".html", "/Users/king/Downloads/pdf/" + filename + "A4.pdf", PageSizeEnum.A3);
//    }
}
