package shop.alien.util.file;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 获取文件夹下文件
 *
 * @author ssk
 * @version 1.0
 * @date 2024/2/13 11:25
 */
@Slf4j
public class FileGetDir {

    public static void main(String[] args) {
//        String filePath = "E:\\Downloads\\ChromeDownloads\\picture";
//        List<String> fileNames = FileGetDir.getFileNames(filePath);
//        for (String fileName : fileNames) {
//            System.out.println(fileName);
//            //文件夹下所有webp转换为jpg
//            WebpConvertUtil.webpConvertWithLocalPath(filePath + File.separator + fileName, "jpg");
//        }
        System.out.println(getLatestFolder("Z:\\douyin\\待处理图片", "image"));
    }

    /**
     * 一个文件夹放多少文件
     */
    private static final Integer FOLDER_FILE_COUNT = 1000;

    private static String imageCachePath = "";

    private static String videoCachePath = "";

    /**
     * 得到文件名称
     *
     * @param path 路径
     * @return List<String>
     */
    public static List<String> getFileNames(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        List<String> fileNames = new ArrayList<>();
        return getFilePath(file, fileNames);
    }

    /**
     * 得到文件路径
     *
     * @param file      文件
     * @param fileNames 文件名
     * @return List<String>
     */
    public static List<String> getFilePath(File file, List<String> fileNames) {
        File[] files = file.listFiles();
        assert files != null;
        for (File f : files) {
            if (f.isDirectory()) {
                File[] folder = f.listFiles();
                assert folder != null;
                if (folder.length == 0) {
                    f.delete();
                } else {
                    getFilePath(f, fileNames);
                }
            } else {
                fileNames.add(f.getAbsolutePath());
            }
        }
        return fileNames;
    }

    /**
     * 初始化缓存路径
     */
    public static void initCachePath() {
        imageCachePath = "";
        videoCachePath = "";
    }

    /**
     * 获取可以存储的文件夹
     *
     * @param path     可存储的路径(c:/待处理图片/视频)
     * @param fileType 文件类型
     * @return 文件夹路径
     */
    public static String getLatestFolder(String path, String fileType) {
        log.info("FileGetDir.getLatestFolder?path={}&fileType={}", path, fileType);
        try {
            //1.判断/创建,待处理图片/视频
            File parentPath = new File(path);
            if (!parentPath.exists()) {
                parentPath.mkdir();
            }
            //2.判断文件夹数量
            File[] parentPathFiles = parentPath.listFiles();
            if (null == parentPathFiles || parentPathFiles.length == 0) {
                //2.1.主文件夹为空, 创建名为1的文件夹, 缓存
                String firstFolderName = path + "/" + 1;
                FileUtil.mkdir(firstFolderName);
                cacheFolderType(firstFolderName, fileType);
                return firstFolderName;
            } else {
                String resultPath = "";
                //2.2.1.主文件夹不为空, 从缓存获取, 返回
                if ("video".equals(fileType) && !videoCachePath.isEmpty()) {
                    resultPath = videoCachePath;
                    File file = new File(videoCachePath);
                    File[] files = file.listFiles();
                    if (files.length < FOLDER_FILE_COUNT) {
                        log.info("当前文件夹: {}, 文件夹内容数量: {}", videoCachePath, files.length);
                        return videoCachePath;
                    }
                } else if ("image".equals(fileType) && !imageCachePath.isEmpty()) {
                    resultPath = imageCachePath;
                    File file = new File(imageCachePath);
                    File[] files = file.listFiles();
                    if (files.length < FOLDER_FILE_COUNT) {
                        log.info("当前文件夹: {}, 文件夹内容数量: {}", imageCachePath, files.length);
                        return imageCachePath;
                    }
                }
                //2.2.2.不为空, 缓存为空, 排序, 获取不满1k的文件夹, 缓存
                if (resultPath.isEmpty()) {
                    FileUtil.SortFileName(parentPathFiles);
                    for (File f : parentPathFiles) {
                        if (f.isDirectory()) {
                            int length = Objects.requireNonNull(f.list()).length;
                            log.info("当前文件夹: {}, 文件夹内容数量: {}", f.getAbsolutePath(), length);
                            if (length < FOLDER_FILE_COUNT) {
                                resultPath = f.getAbsolutePath();
                                break;
                            }
                        }
                    }
                    //主文件夹不为空, 缓存没有文件夹, 所有文件夹都满了
                    if (resultPath.isEmpty()) {
                        int size = parentPathFiles.length + 1;
                        String newPath = path + "/" + size;
                        cacheFolderType(newPath, fileType);
                        return newPath;
                    } else {
                        cacheFolderType(resultPath, fileType);
                        return resultPath;
                    }
                } else {
                    //2.2.3.不为空, 缓存不为空, 排序, 所有文件夹都大于1K
                    //2.2.3.1.缓存最新的路径+1, 缓存
                    resultPath = resultPath.replace("\\", "/");
                    String folderNum = resultPath.substring(resultPath.lastIndexOf("/") + 1);
                    int count = Integer.parseInt(folderNum) + 1;
                    //c:/待处理图片/latest+1
                    resultPath = resultPath.substring(0, resultPath.lastIndexOf("/") + 1) + count;
                    File file = new File(resultPath);
                    if (file.exists() && file.listFiles().length >= FOLDER_FILE_COUNT) {
                        //清空缓存的路径, 不然会一直循环
                        if ("video".equals(fileType)) {
                            videoCachePath = "";
                        }
                        if ("image".equals(fileType)) {
                            imageCachePath = "";
                        }
                        getLatestFolder(path, fileType);
                    } else {
                        FileUtil.mkdir(resultPath);
                        cacheFolderType(resultPath, fileType);
                        return resultPath;
                    }
                }
            }
        } catch (RuntimeException e) {
            log.error("FileGetDir getLatestFolder ERROR: {}", e.getMessage());
            return null;
        }
        return null;
    }

    /**
     * 缓存文件夹路径
     *
     * @param path     路径
     * @param fileType 文件类型
     */
    public static void cacheFolderType(String path, String fileType) {
        if ("video".equals(fileType)) {
            videoCachePath = path;
        } else if ("image".equals(fileType)) {
            imageCachePath = path;
        }
    }

}
