package com.jfinal.club.common.doc.convert;

import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.jodconverter.local.JodConverter;

import java.io.File;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

;

/**
 * word 转pdf
 *
 * @author lr
 */
@Slf4j
public class TransferUtil {

    private static String[] officeExtNames = new String[]{"doc","docx","ppt","pptx","xls","xlsx","pdf","txt"};
    private static String[] skipExtNames = new String[]{"txt","pdf"};

    private static String datetimePattern = "yyyyMMddHHmmssSSS";
    /**
     * 根据拓展名判断是否是OFFICE文件
     * @param extName 拓展名
     * @return
     */
    public static boolean isOfficeFile(String extName){
        return ArrayUtils.contains(officeExtNames,extName);
    }

    /**
     * word,excel,ppt ->pdf
     *
     * @return 相同文件夹下的转换后的pdf文件 如/test/wd_20190517151515333.pdf
     * @throws Exception
     */
    public static String transferWordToPdf(String originContextFilePath) throws Exception {
        //转换成本地实际磁盘路径
        File inputFile = new File(Paths.get(PathKit.getWebRootPath(),originContextFilePath).toString());

        if (!inputFile.exists() || !inputFile.isFile() || !isOfficeFile(FilenameUtils.getExtension(originContextFilePath))) {
            log.error("文件 -> pdf转换错误  当前文件不是office 文档或文件不存在: {}",originContextFilePath);
            return null;
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(datetimePattern);
        String timeNow = formatter.format(LocalDateTime.now());

        String newPdfWebPath = Paths.get(FilenameUtils.getPath(originContextFilePath),"pdf",timeNow+".pdf").toString();

        try {
            JodConverter.convert(inputFile).to(Paths.get(PathKit.getWebRootPath(),newPdfWebPath).toFile()).execute();
        } catch (Exception e) {
            log.error("word->pdf 转换错误------------> Exception: ", e);
            return null;
        }
        return "/" + newPdfWebPath;
    }

    /**
     * pdf转图片 返回本地存储路径图片集合
     *
     * @param originLocalFilePath pdf 文件路径
     * @return
     * @throws Exception
     */
    public static List<String> transferPdfToImage(String originLocalFilePath) throws Exception {
        File inputFile = new File(originLocalFilePath);
        if (!inputFile.exists() ||
                !inputFile.isFile() ||
                originLocalFilePath.lastIndexOf(".pdf") < 0) {
            throw new Exception("pdf-> img 源文件不是pdf文件 或者文件不存在！");
        }
        String localPdfPath = originLocalFilePath;

        PdfTransferUtil transferUtil = new PdfTransferUtil();
        List<byte[]> ins = transferUtil.pdf2Image(localPdfPath, "png", 1.5f);
        List<String> localFilePath = new ArrayList<>(ins.size());
        for (int i = 0; i < ins.size(); i++) {
            byte[] data = ins.get(i);
            File pathReal = Paths.get(FilenameUtils.getPath(originLocalFilePath)+ "..",FilenameUtils.getBaseName(originLocalFilePath) + "_" + i + ".png").toFile();
            FileUtils.writeByteArrayToFile(pathReal, data);
            localFilePath.add(pathReal.toString());
        }
        return localFilePath;
    }

    /**
     * pdf转图片 返回web可访问图片集合
     *
     * @param webPath
     * @return
     * @throws Exception
     */
    public static List<String> transferPdfToWebImage(String webPath) throws Exception {
        List<String> localPathImage = transferPdfToImage(webPath);
        List<String> webPathImage = new ArrayList<>(localPathImage.size());
        for (String s : localPathImage) {
            webPathImage.add(s);
        }
        return webPathImage;
    }

    /**
     * 上传文件保存到本地，返回可访问web路径
     *
     * @param suffix
     * @param file
     * @return
     * @throws Exception
     */
    public static String saveLocation(String suffix, UploadFile file) throws Exception {
        String fileName = System.currentTimeMillis() + "." + suffix;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(datetimePattern);
        String time = formatter.format(LocalDateTime.now());

        File saveFile = Paths.get(file.getUploadPath(),  time + "."+FilenameUtils.getExtension(file.getFileName())).toFile();
        file.getFile().renameTo(saveFile);

        log.info("保存的文件路径--> fileLocalSavePath:{}", saveFile.getAbsolutePath());
        return saveFile.getPath();
    }

}