package com.ruoyi.web.controller.utils;


import com.ruoyi.common.utils.uuid.UUID;
import lombok.extern.log4j.Log4j2;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @Author: Ljx
 * @Date: 2023/12/20
 **/
@Log4j2
public class PdfUtils {

    /**
     * 获取不带扩展名的文件名
     */
    public static String getFileNameNoSuffix(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    /**
     * 获取文件扩展名
     */
    public static String getSuffixNameName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }


    /**
     * File转MultipartFile
     *
     * @param mulFile 文件对象
     * @return Multipart文件对象
     */
    public static File multipartFileToFile(MultipartFile mulFile) throws IOException {
        InputStream ins = mulFile.getInputStream();
        String fileName = mulFile.getOriginalFilename();
        String prefix = getFileNameNoSuffix(fileName) + UUID.randomUUID().toString();
        String suffix = "." + getSuffixNameName(fileName);
        File toFile = File.createTempFile(prefix, suffix);
        OutputStream os = new FileOutputStream(toFile);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return toFile;
    }


    /**
     * 校验pdf文件是否包含js脚本
     **/
    public static boolean containsJavaScript(File file) throws IOException {

//        RandomAccessFile is = new RandomAccessFile(file, "r");
        try (PDDocument document = PDDocument.load(file)){
            String CosName = document.getDocument().getTrailer().toString();
            if (CosName.contains("COSName{JavaScript}")
                    || CosName.contains("COSName{JS}")
                    || CosName.contains("COSName{alert}")
                    || CosName.contains("COSName{onmouseover}")
                    || CosName.contains("COSName{alalertert}")
                    || CosName.contains("COSName{embed}")
            ) {
                return true;
            }
        } catch (Exception e) {
            log.error("PDF效验异常：" + e.getMessage());
            return true;
        }
        return false;
    }



}