package com.xiaoniu.subsystem.strategy;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author haoxuyang
 * @Date 2024/11/28 16:14
 */
@Slf4j
public class FileUtil {
    /**
     * 获取文件类型
     *
     * @param fileName fileName
     * @return FileType
     */
    public static String getFileType(String fileName) {
        if (StrUtil.isNotEmpty(fileName)) {
            String[] strArray = fileName.split("\\.");
            if (strArray.length == 1) {
                return "";
            }
            int suffixIndex = strArray.length - 1;
            return strArray[suffixIndex];
        }
        return "";
    }

    public static String formatFileSize(long sizeInBytes) {
        double sizeInKB = sizeInBytes / 1024.0;
        if (sizeInKB < 1024) {
            return String.format("%.2f KB", sizeInKB);
        }

        double sizeInMB = sizeInKB / 1024.0;
        if (sizeInMB < 1024) {
            return String.format("%.2f MB", sizeInMB);
        }

        double sizeInGB = sizeInMB / 1024.0;
        return String.format("%.2f GB", sizeInGB);
    }

    /**
     * 上传文件-inputStream
     *
     * @param inputStream inputStream流
     * @param fileName    文件名
     * @return 结果
     */
    public static MultipartFile inputStreamConvertMultipartFile(InputStream inputStream, String fileName) throws Exception {
        MultipartFile multipartFile = null;
        try {
            multipartFile = new MockMultipartFile(fileName, fileName, "", inputStream);
        } catch (IOException e) {
            log.error("转换失败");
        }
        return multipartFile;
    }
}
