package com.tzld.piaoquan.growth.common.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileUtils {

    public static String getExtension(MultipartFile file) {
        if (file == null || file.getOriginalFilename() == null) {
            return "";
        }

        String fileName = file.getOriginalFilename();
        int lastIndex = fileName.lastIndexOf('.');

        // 处理无扩展名或隐藏文件的情况
        if (lastIndex == -1 || lastIndex == 0) {
            return "";
        }

        return fileName.substring(lastIndex).toLowerCase();
    }

    public static void deleteFileByIO(String filePath) {
        File file = new File(filePath);
        File[] list = file.listFiles();
        if (list != null) {
            for (File temp : list) {
                deleteFileByIO(temp.getAbsolutePath());
            }
        }
        file.delete();
    }

    public static void saveFileContent(String filePath, byte[] contentBytes) throws IOException {
        Path path = Paths.get(filePath);
        Path parentDir = path.getParent();
        if (!Files.exists(parentDir)) {
            Files.createDirectories(parentDir);
        }
        Files.write(path, contentBytes);
    }
}
