package com.zksy.common.utils.pdf;

import com.zksy.common.config.zksyConfig;
import com.itextpdf.text.pdf.PdfReader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author sy
 * @date 2022/4/21 10:40
 */
public class PdfUtils {
    /**
     * dpi越大转换后越清晰，相对转换速度越慢
     */
    private static final Integer DPI = 100;

    /**
     * 转换后的图片类型
     */
    private static final String IMG_TYPE = "png";

    /**
     * PDF转图片
     *
     * @param fileContent PDF文件的二进制流
     * @return 图片文件的二进制流
     */
    public static List<byte[]> pdfToImage(byte[] fileContent) throws IOException {
        List<byte[]> result = new ArrayList<>();
        try (PDDocument document = PDDocument.load(fileContent)) {
            PDFRenderer renderer = new PDFRenderer(document);
            for (int i = 0; i < document.getNumberOfPages(); ++i) {
                BufferedImage bufferedImage = renderer.renderImageWithDPI(i, DPI);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, IMG_TYPE, out);
                result.add(out.toByteArray());
            }
        }
        return result;
    }

    /**
     * PDF文件转PNG图片，全部页数
     * 改为转流返回给客户端
     *
     * @param pdfFilePath  pdf完整路径
     * @param dstImgFolder 图片存放的文件夹
     * @return 返回转换后图片集合list
     */
    public static List<byte[]> pdfToImage2(String pdfFilePath, String dstImgFolder) {
        UUID uuid = UUID.randomUUID();
        String uuId = uuid.toString();
        System.out.println(uuId);
        File file = new File(pdfFilePath);
        //定义集合保存返回图片数据
        // List<File> fileList = new ArrayList<File>();
        //定义集合 保存返回图片转流的数据
        List<byte[]> result = new ArrayList<>();
        @SuppressWarnings("resource")//抑制警告
                PDDocument pdDocument = new PDDocument();
        ByteArrayOutputStream out = null;
        try {
            //String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
            String imgFolderPath = null;
            if (dstImgFolder == null || dstImgFolder.equals("")) {
                // imgFolderPath = dstImgFolder + File.separator + uuId;// 获取图片存放的文件夹路径
                //imgFolderPath = DyConfig.getUploadPathLinshi() + File.separator + uuId;
                imgFolderPath = zksyConfig.getUploadPath() + File.separator + uuId;
            } else {
                imgFolderPath = dstImgFolder + File.separator + uuId;
            }
            if (createDirectory(imgFolderPath)) {
                pdDocument = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(pdDocument);
                /* dpi越大转换后越清晰，相对转换速度越慢 */
                PdfReader reader = new PdfReader(pdfFilePath);
                int pages = reader.getNumberOfPages();
                System.out.println("pdf总共多少页-----" + pages);
                StringBuffer imgFilePath = null;


                for (int i = 0; i < pages; i++) {
                    String imgFilePathPrefix = imgFolderPath + File.separator + "pdf";
                    System.out.println("imgFilePathPrefix=====" + imgFilePathPrefix);
                    imgFilePath = new StringBuffer();
                    imgFilePath.append(imgFilePathPrefix);
                    imgFilePath.append("-");
                    imgFilePath.append(String.valueOf(i));
                    imgFilePath.append(".jpg");
                    // File dstFile = new File(imgFilePath.toString());
                    BufferedImage image = renderer.renderImageWithDPI(i, DPI);
                    //ImageIO.write(image, "png", dstFile);
                    //fileList.add(dstFile);
                    out = new ByteArrayOutputStream();
                    ImageIO.write(image, IMG_TYPE, out);
                    result.add(out.toByteArray());
                    PdfUtils.delFolder(imgFolderPath);//删除文件
                }
                //System.out.println("PDF文档转PNG图片成功！");
                System.out.println("PDF文档转PNG图片再转流成功！");
//                return fileList;
                out.close();
                pdDocument.close();
                return result;
            } else {
                System.out.println("PDF文档转PNG图片失败：" + "创建" + imgFolderPath + "失败");
                out.close();
                pdDocument.close();
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //创建文件夹
    private static boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }

    //删除文件夹
    //param folderPath 文件夹完整绝对路径
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除指定文件夹下所有文件
    //param path 文件夹完整绝对路径
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();

            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }


}
