package com.ruoyi.common.utils.file;

import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.rmi.RemoteException;
import java.security.MessageDigest;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.CRC32;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.constant.Constants;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

/**
 * 文件处理工具类
 * 
 * @author ruoyi
 */
public class FileUtils
{
    private static final Logger log = LoggerFactory.getLogger(FileUtils.class);
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    /**
     * 输出指定文件的byte数组
     * 
     * @param filePath 文件路径
     * @param os 输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException
    {
        FileInputStream fis = null;
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            IOUtils.close(os);
            IOUtils.close(fis);
        }
    }

    public static InputStream readBytes(String filePath) {
        FileInputStream fis = null;
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            try {
                IOUtils.close(fis);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return fis;
    }

    /**
     * 写数据到文件中
     *
     * @param data 数据
     * @return 目标文件
     * @throws IOException IO异常
     */
    public static String writeImportBytes(byte[] data) throws IOException
    {
        return writeBytes(data, RuoYiConfig.getImportPath());
    }

    /**
     * 写数据到文件中
     *
     * @param data 数据
     * @param uploadDir 目标文件
     * @return 目标文件
     * @throws IOException IO异常
     */
    public static String writeBytes(byte[] data, String uploadDir) throws IOException
    {
        FileOutputStream fos = null;
        String pathName = "";
        try
        {
            String extension = getFileExtendName(data);
            pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
            File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName);
            fos = new FileOutputStream(file);
            fos.write(data);
        }
        finally
        {
            IOUtils.close(fos);
        }
        return FileUploadUtils.getPathFileName(uploadDir, pathName);
    }

    /**
     * 删除文件
     * 
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath)
    {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists())
        {
            flag = file.delete();
        }
        return flag;
    }

    public static boolean deleteFileNew(String filePath) {
        try {
            Files.delete(Paths.get(filePath));
            return true;
        } catch (IOException e) {
            return false;
        }
    }
    public static boolean deleteFileNew2(String filePath) {
        try {
            // 将 URL 转换为 URI，然后获取本地路径
            URI uri = URI.create(filePath);
            String localPath = Paths.get(uri).toString();

            // 删除本地文件
            Files.delete(Paths.get(localPath));

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 文件名称验证
     * 
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename)
    {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 检查文件是否可下载
     * 
     * @param resource 需要下载的文件
     * @return true 正常 false 非法
     */
    public static boolean checkAllowDownload(String resource)
    {
        // 禁止目录上跳级别
        if (StringUtils.contains(resource, ".."))
        {
            return false;
        }

        // 检查允许下载的文件规则
        if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource)))
        {
            return true;
        }

        // 不在允许下载的文件规则
        return false;
    }

    /**
     * 下载文件名重新编码
     * 
     * @param request 请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException
    {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE"))
        {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        }
        else if (agent.contains("Firefox"))
        {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        }
        else if (agent.contains("Chrome"))
        {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        else
        {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    /**
     * 下载文件名重新编码
     *
     * @param response 响应对象
     * @param realFileName 真实文件名
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
    {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", contentDispositionValue.toString());
        response.setHeader("download-filename", percentEncodedFileName);
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException
    {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }

    /**
     * 获取图像后缀
     * 
     * @param photoByte 图像数据
     * @return 后缀名
     */
    public static String getFileExtendName(byte[] photoByte)
    {
        String strFileExtendName = "jpg";
        if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
                && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97))
        {
            strFileExtendName = "gif";
        }
        else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70))
        {
            strFileExtendName = "jpg";
        }
        else if ((photoByte[0] == 66) && (photoByte[1] == 77))
        {
            strFileExtendName = "bmp";
        }
        else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71))
        {
            strFileExtendName = "png";
        }
        return strFileExtendName;
    }

    /**
     * 获取文件名称 /profile/upload/2022/04/16/ruoyi.png -- ruoyi.png
     * 
     * @param fileName 路径名称
     * @return 没有文件路径的名称
     */
    public static String getName(String fileName)
    {
        if (fileName == null)
        {
            return null;
        }
        int lastUnixPos = fileName.lastIndexOf('/');
        int lastWindowsPos = fileName.lastIndexOf('\\');
        int index = Math.max(lastUnixPos, lastWindowsPos);
        return fileName.substring(index + 1);
    }

    /**
     * 获取不带后缀文件名称 /profile/upload/2022/04/16/ruoyi.png -- ruoyi
     * 
     * @param fileName 路径名称
     * @return 没有文件路径和后缀的名称
     */
    public static String getNameNotSuffix(String fileName)
    {
        if (fileName == null)
        {
            return null;
        }
        String baseName = FilenameUtils.getBaseName(fileName);
        return baseName;
    }

    /**
     * 删除多级目录
     * 删除指定目录和目录下子目录和文件
     *
     * @param filePath 目录路径
     * @throws IOException
     */
    public static void removeDirectory(String filePath) throws IOException {
        if (StringUtils.isBlank(filePath)) return;

        Files.walkFileTree(Paths.get(filePath), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
                // return super.visitFile(file, attrs);
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }

    /**
     * 拷贝多级目录
     * 拷贝指定目录和目录下子目录和文件
     *
     * @param sourcePath 源目录路径
     * @param targetPath 目标目录路径
     * @throws IOException
     */
    public static void transferDirectory(String sourcePath, String targetPath) throws IOException {
        transferDirectory(sourcePath, targetPath, false);
    }

    /**
     * 拷贝多级目录
     * 拷贝指定目录和目录下子目录和文件
     * 
     * @param sourcePath    源目录路径
     * @param targetPath    目标目录路径
     * @param onlyFile      是否只拷贝文件
     * @throws IOException
     */
    public static void transferDirectory(String sourcePath, String targetPath, boolean onlyFile) throws IOException {
        if (StringUtils.isBlank(sourcePath) || StringUtils.isBlank(targetPath))
            throw new IOException("sourcePath or targetPath is null");
        
        // sourcePath 去除盘符


        Path source = Paths.get(sourcePath);
        try (Stream<Path> pathStream = Files.walk(source)) {
            for (Path path : pathStream.collect(Collectors.toList())) {
                Path target = Paths.get(targetPath, path.toString().replace(source.toString(), ""));
                
                if (Files.isDirectory(path)) {
                    if (!onlyFile) {
                        Files.createDirectory(target);
                    }
                } else {
                    Files.copy(path, target);
                }
            }

            // pathStream.forEach(source -> {
            //     // try {
            //         // String targetName = source.toString().replace(sourcePath, targetPath);
            //         // 目录
            //         Path path = Paths.get(targetPath);
            //         if (Files.isDirectory(source)) {
            //             if (!onlyFile) {
            //                 Files.createDirectory(path);
            //             }
            //         } else {
            //             // 文件
            //             Files.copy(source, path);
            //         }
            //     // } catch (IOException e) {
            //     //     e.printStackTrace();
            //     // }
            // });
        }

    }
    
    public static void createDirectory(String path) throws IOException {
        Path newDirectoryPath = Paths.get(path);

        if (!Files.exists(newDirectoryPath)) {
            Files.createDirectories(newDirectoryPath);
        }
    }



    // 正则表达式匹配URL
    private static final Pattern URL_PATTERN = Pattern.compile(
            "^(http://|https://|ftp://|file://|www\\.)[\\w\\-]+(\\.[\\w\\-]+)+([\\w\\-,@?^=%&:/~\\+#]*[\\w\\-,@?^=%&/~\\+#])?$",
            Pattern.CASE_INSENSITIVE);

    // 判断是否为URL
    public static boolean isUrl(String input) {
        return URL_PATTERN.matcher(input).matches();
    }

    // 判断是否为本地文件路径
    public static boolean isLocalFilePath(String input) {
        try {
            Path path = Paths.get(input);
            return Files.exists(path);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 使用MD5算法生成文件摘要
     * 较快 不安全 碰撞几率低 注意使用场景
     * 
     * @param filePath
     * @return
     * @throws Exception
     */
    public static String getFileChecksum(String filePath) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        try (FileInputStream fis = new FileInputStream(filePath)) {
            byte[] byteArray = new byte[1024];
            int bytesCount = 0;
            while ((bytesCount = fis.read(byteArray)) != -1) {
                digest.update(byteArray, 0, bytesCount);
            }
        }

        byte[] bytes = digest.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }


    /**
     * 使用CRC32算法生成文件摘要
     * 快速 碰撞几率较低 注意使用场景
     * 
     * @param filePath
     * @return
     * @throws IOException
     */
    public static long getFileCRC32(String filePath) throws IOException {
        CRC32 crc = new CRC32();
        try (FileInputStream fis = new FileInputStream(filePath)) {
            byte[] byteArray = new byte[1024];
            int bytesCount;
            while ((bytesCount = fis.read(byteArray)) != -1) {
                crc.update(byteArray, 0, bytesCount);
            }
        }
        return crc.getValue();
    }


    // /**
    //  * 使用xxHash算法生成文件摘要
    //  * 网上说这个算法比MD5和CRC32更快 但是测试结果却最慢.可能写法有问题
    //  * 算法碰撞几率最低
    //  * 
    //  * @param filePath
    //  * @return
    //  * @throws IOException
    //  */
    // public static long getFileXXHash(String filePath) throws IOException {
    //     XXHashFactory factory = XXHashFactory.fastestInstance();
    //     StreamingXXHash64 hasher = factory.newStreamingHash64(0x9747b28c); // 这里使用一个seed值
    //
    //     byte[] buf = new byte[8192];
    //     try (FileInputStream fis = new FileInputStream(filePath)) {
    //         int read;
    //         while ((read = fis.read(buf)) != -1) {
    //             hasher.update(buf, 0, read);
    //         }
    //     }
    //
    //     return hasher.getValue();
    // }


    public static void main(String[] args) {
        String filePath1 = "D:/KOYO_BJXT/dataPath/cc/教师感恩卡_20240715132137A005.docx";
        String filePath2 = "D:/KOYO_BJXT/dataPath/cc/教师感恩卡_20240715132137A005.docx";
        // String filePath2 = "D:/KOYO_BJXT/dataPath/cc/返校新闻稿_20240715111632A001.docx";

        StopWatch stopWatch = new StopWatch();
        try {
            // 使用MD5算法比较
            stopWatch.start("MD5");
            String md5_1 = getFileChecksum(filePath1);
            String md5_2 = getFileChecksum(filePath2);
            stopWatch.stop();
            System.out.println("MD5 comparison: " + md5_1.equals(md5_2));
            
            
            // 使用CRC32算法比较
            stopWatch.start("CRC32");
            long crc1 = getFileCRC32(filePath1);
            long crc2 = getFileCRC32(filePath2);
            stopWatch.stop();
            System.out.println("CRC32 comparison: " + (crc1 == crc2));

            // 使用xxHash算法比较
            // stopWatch.start("xxHash");
            // long xxHash1 = getFileXXHash(filePath1);
            // long xxHash2 = getFileXXHash(filePath2);
            // stopWatch.stop();
            // System.out.println("xxHash comparison: " + (xxHash1 == xxHash2));
            
            System.out.println(stopWatch.prettyPrint());

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
