package com.example.demo.utils;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.FileAlreadyExistsException;
import java.util.UUID;

public class FileUtils {


    public static String fileStoreLocal(MultipartFile file) {


        String fileName = file.getOriginalFilename();
        //获取文件后缀名
        assert fileName != null;
        String suffixName = fileName.substring(fileName.indexOf("."));
        //重新生成文件名（根据具体情况生成对应文件名）
        fileName = UUID.randomUUID() + suffixName;

        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(FileUtils.class);
        File jarF = h.getSource();
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
//        /root/jar/upload
        String dirPath = jarF.getParentFile().toString() + "/" + "upload_dir";

        String a = "";

//        int hashCode = fileName.hashCode();
//        String hexString = Integer.toHexString(hashCode);
//        char[] chars = hexString.toCharArray();
//        for (char aChar : chars) {
//            a = a + "/" + aChar;
//        }
//        /root/jar/upload/1/3/4/6/h/j
        String dirPath2 = dirPath + a;

//        System.out.println(dirPath);


//        创建文件夹
        File filePath = new File(dirPath2);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {
            //将文件写入磁盘
            file.transferTo(new File(dirPath2 + "/" + fileName));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件上传失败");
            return null;

        }


        System.out.println("文件上传成功，地址为：" + dirPath + a + "/" + fileName);
        return dirPath + a + "/" + fileName;

    }


    public static String strToFile(String str) {

        //获取jar包所在目录
        ApplicationHome h = new ApplicationHome(FileUtils.class);
        File jarF = h.getSource();
        //在jar包所在目录下生成一个upload文件夹用来存储上传的图片
//        /root/jar/upload
        String dirPath = jarF.getParentFile().toString() + "/" + "upload_dir" + "/";

        String fileName = UUID.randomUUID() + ".txt";

        StringBuffer realFilePath = new StringBuffer();

//        创建路径
        File path = new File(dirPath);
        if (!path.exists()) {
            path.mkdirs();
        }

        realFilePath.append(dirPath);
        realFilePath.append(fileName);

        System.out.println("生成文件的绝对路径:" + realFilePath);


//        创建文件
        File filePath = new File(path, fileName);


        BufferedWriter out = null;

        try {
            out = new BufferedWriter(new FileWriter(filePath));
//            把输入字符串写入文件中
            out.write(str);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("在字符串写入文件时出错");
        } finally {

            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return String.valueOf(realFilePath);

    }


    /**
     * 查看某个文件夹下有多少个文件
     */
    public static int countFiles(String folderPath) {
        File folder = new File(folderPath);
        if (!folder.exists() || !folder.isDirectory()) {
            throw new IllegalArgumentException("指定的路径不是一个有效的文件夹路径");
        }

        int count = 0;
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    count++;
                } else if (file.isDirectory()) {
                    count += countFiles(file.getAbsolutePath()); // 递归调用
                }
            }
        }

        return count;
    }



    public static void deleteSpecificFiles(File folder, String fileNameToDelete) {
        File[] files = folder.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 递归删除子文件夹中的指定文件
                    deleteSpecificFiles(file, fileNameToDelete);
                } else {
                    // 判断是否为指定的文件名
                    if (file.getName().equals(fileNameToDelete)) {
                        // 删除文件
                        file.delete();
                    }
                }
            }
        }
    }
}
