package leaf.plugin.word2pdf;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uncertain.core.UncertainEngine;
import uncertain.ocm.IObjectRegistry;

import java.io.File;

/**
 * @author niminmin
 */
public class WordToPdf {
    IObjectRegistry registry;
    String jacobDllPath;
    private static final Logger logger = LoggerFactory.getLogger(WordToPdf.class);
    public WordToPdf(IObjectRegistry registry, String jacobDllName)
            throws Exception {
        this.registry = registry;
        UncertainEngine engine = (UncertainEngine) this.registry
                .getInstanceOfType(UncertainEngine.class);
        String webInfPath = engine.getDirectoryConfig().getConfigDirectory();

        // 添加jacob-1.18-x64.dll到C:\Java\jre1.7.0_79\bin目录 或者按照以下代码进行设置
        // D:\work\leafProjects\MX_leasing\web\WEB-INF\server-script\jacob\jacob-1.18-x64.dll
       jacobDllPath = webInfPath + "/server-script/jacob/" + jacobDllName;
        System.setProperty("jacob.dll.path", jacobDllPath);
        System.setProperty("com.jacob.debug", "true");
        logger.info("加载的配置文件路径:" + jacobDllPath);
    }

    public static boolean word2pdf(String inFilePath, String outFilePath) {
        logger.info("Word转PDF开始启动...");
        logger.info("Word转PDF开始启动..."+outFilePath);
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch doc = null;
        boolean flag = false;
        try {
            ComThread.InitMTA();
            app = new ActiveXComponent("Word.Application");
          //  logger.info("Word转PDF开始启动...234");
            app.setProperty("Visible", new Variant(false));
          //  logger.info("Word转PDF开始启动...456");
            Dispatch docs = app.getProperty("Documents").toDispatch();
            logger.info("打开文档:" + inFilePath);
            doc = Dispatch.invoke(
                    docs,
                    "Open",
                    1,
                    new Object[]{inFilePath, new Variant(false),
                            new Variant(true)}, new int[1]).toDispatch();
            logger.info("转换文档到PDF:" + outFilePath);
            File tofile = new File(outFilePath);
            if (tofile.exists()) {
                tofile.delete();
            }

            Dispatch.invoke(doc, "SaveAs", 1, new Object[]{outFilePath,
                    new Variant(17)}, new int[1]);
            Dispatch.call(doc, "Close", new Object[]{new Variant(false)});
            long end = System.currentTimeMillis();
            logger.info("转换完成,用时:" + (end - start) + "ms");
            flag = true;
        } catch (Exception e) {
        // logger.error("error",e);
            logger.info("Word转PDF出错:" + e.getMessage());
          //  logger.info("Word转PDF出错:" + e.toString());
            flag = false;
            logger.info("关闭文档");
            if (app != null) {
                app.invoke("Quit", 0);
            }

            ComThread.Release();
        } finally {
            logger.info("关闭文档");
            if (app != null) {
                app.invoke("Quit", 0);
            }

            ComThread.Release();
        }
        return flag;
    }

    /**
     * 如果PDF存在则删除PDF
     *
     * @param pdfPath
     */
    private static void deletePdf(String pdfPath) {
        File pdfFile = new File(pdfPath);
        if (pdfFile.exists()) {
            pdfFile.delete();
        }
    }


    /**
     * excel to pdf
     *
     * @param inFilePath
     * @param outFilePath
     * @return
     */
    public static boolean excel2pdf(String inFilePath, String outFilePath) {
        ActiveXComponent activeXComponent = new ActiveXComponent("Excel.Application");
        activeXComponent.setProperty("Visible", false);

//		deletePdf(outFilePath);

        Dispatch excels = activeXComponent.getProperty("Workbooks").toDispatch();
        Dispatch excel = Dispatch.call(excels, "Open", inFilePath, false, true).toDispatch();
        Dispatch.call(excel, "ExportAsFixedFormat", 0, outFilePath);
        Dispatch.call(excel, "Close", false);
        activeXComponent.invoke("Quit");
        return true;
    }

    /**
     * excel to pdf Orientation  excel横向转成pdf
     *
     * @param inFilePath
     * @param outFilePath
     * @return
     */
    public static boolean excel2pdfOrientation(String inFilePath, String outFilePath) {
        ActiveXComponent activeXComponent = new ActiveXComponent("Excel.Application");
        activeXComponent.setProperty("Visible", false);

//		deletePdf(outFilePath);

        Dispatch excels = activeXComponent.getProperty("Workbooks").toDispatch();
        Dispatch excel = Dispatch.call(excels, "Open", inFilePath, false, true).toDispatch();

        Dispatch currentSheet = Dispatch.get((Dispatch) excel,
                "ActiveSheet").toDispatch();
        Dispatch pageSetup = Dispatch.get(currentSheet, "PageSetup")
                .toDispatch();
        Dispatch.put(pageSetup, "Orientation", new Variant(2));

        Dispatch.call(excel, "ExportAsFixedFormat", 0, outFilePath);
        Dispatch.call(excel, "Close", false);
        activeXComponent.invoke("Quit");
        return true;
    }
    public static void cutPdf(String pdfPath)
    {
        File file = new File(pdfPath);
        PDDocument document = new PDDocument();
        try{
            document = PDDocument.load(file);
        }catch(Exception e){
            logger.error("error",e);
        }
        int noOfPages = document.getNumberOfPages();
        System.out.println(noOfPages);
        document.removePage(noOfPages-1);

        try{
            document.save(pdfPath);
            document.close();
        }catch(Exception e){
            logger.error("error",e);
        }
    }



    public static void main(String[] args) throws Exception {

//		String jacobDllPath = "D:\\ideaProjects\\leaf-hlcm\\src\\main\\webapp\\WEB-INF\\server-script\\jacob\\jacob-1.18-x64.dll";
//		System.setProperty("jacob.dll.path", jacobDllPath);
//		System.setProperty("com.jacob.debug", "true");
//		word2pdf("D:\\u01\\hls_file\\excel\\8F5D12B0B1504518928FDD193C67A0A5con28168",
//				"D:\\hand-Prpjects\\融资租赁合同文本-4pdf.pdf");
//        cutPdf("D:\\\\hand-Prpjects\\\\付款请求书打印.pdf");
//		excel2pdf("D:\\work\\leafProjects\\YondaTl\\src\\test.xlsx",
//				"D:\\work\\leafProjects\\YondaTl\\src\\付款通知书NEW.pdf");
//		excel2pdfOrientation("D:\\work\\leafProjects\\YondaTl\\src\\test.xlsx",
//				"D:\\work\\leafProjects\\YondaTl\\src\\付款通知书NEW.pdf");
	}
}