package com.yunyan.business.document;


import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.yunyan.common.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * word转pdf的工具
 *
 */
@Slf4j
public class Word2PdfUtils {

    // 不保存待定的更改。
    private static final int wdDoNotSaveChanges = 0;
    // word转PDF 格式
    private static final int wdFormatPDF = 17;
    // 类型, 默认1
    private static final int type = 1;

    /**
     * 转换 word to pdf, 不删除 源文件
     * @param sourceWordFile
     * @param targetPdfFile
     * @return
     */
    public static boolean word2pdf(String sourceWordFile, String targetPdfFile) {
        return Word2PdfUtils.word2pdf(sourceWordFile, targetPdfFile, false);
    }

    /**
     * 转换 word to pdf
     * @param sourceWordFile
     * @param targetPdfFile
     * @param deleteSource 是否删除 源文件
     * @return
     */
    public static boolean word2pdf(String sourceWordFile, String targetPdfFile, boolean deleteSource) {
        boolean res = false;
        if(1 == Word2PdfUtils.type) {
            res = word2pdfD4j(sourceWordFile, targetPdfFile);
        }

        if(deleteSource) {
            try {
                FileUtils.deleteFile(sourceWordFile);
            } catch (Exception e) {
                log.error("删除源文件 异常 [{}] ,  [{}]", e.getMessage(), e);
            }
        }

        return res;
    }

    private static boolean word2pdfD4j(String sourceWordFile, String targetPdfFile) {
        try (
                InputStream docxInputStream = new FileInputStream(sourceWordFile);
                OutputStream outputStream = new FileOutputStream(targetPdfFile);
        )  {
            long start = System.currentTimeMillis();

            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();

            if(!converter.isOperational()) {
                //log.debug("正在 operationl");
                converter.kill();
            }


//            converter.shutDown();
            log.debug("success");
            long end = System.currentTimeMillis();
            log.debug("转换完成，用时：" + (end - start) + "ms");
            return true;
        } catch (FileNotFoundException e) {
            log.error("word转 PDF  文件读取未找到异常 : [{}], [{}], 源文件: [{}], 目标文件", e.getMessage(), e, sourceWordFile, targetPdfFile);
        } catch (IOException e) {
            log.error("word转 PDF  IO异常 : [{}], [{}]", e.getMessage(), e);
        } finally {
        }

        return false;
    }

}
