package com.easyproject.common.utils;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 方法说明: 文件处理工具类
 * @param
 * @return
 * @author java-101
 * @date 2025-04-09 13:47:48
 */
@Slf4j
public class FileUtil {

    /**
     * 方法说明: 将网络图片地址转换为MultipartFile对象
     * @param
     * @return
     * @author java-101
     * @date 2025-04-09 13:48:16
     */
    public static MultipartFile convertUrlToMultipartFile(String imageUrl) throws IOException {
        // 使用 Hutool 的 HttpUtil 获取图片的字节数组
        byte[] bytes = HttpUtil.downloadBytes(imageUrl);
        String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
        //获取后缀
        String suffix = fileName.substring(fileName.indexOf(".") + 1,fileName.indexOf(".") +8);
        if(suffix.contains("png")){
            suffix = "png";
        }else if(suffix.contains("jpg")){
            suffix = "jpg";
        }else if(suffix.contains("jpeg")){
            suffix = "jpeg";
        }else if(suffix.contains("gif")){
            suffix = "gif";
        }else if(suffix.contains("bmp")){
            suffix = "bmp";
        }else if(suffix.contains("webp")){
            suffix = "webp";
        }else if(suffix.contains("svg")){
            suffix = "svg";
        }
        //重新命名
        fileName = "icon."+suffix;
        // 创建 DiskFileItem 对象
        FileItem fileItem = new DiskFileItem("file", "image/jpeg", false, fileName, bytes.length, new File("."));
        try (InputStream inputStream = new ByteArrayInputStream(bytes)) {
            // 将字节数组写入到 FileItem 的输出流中
            fileItem.getOutputStream().write(bytes);
        }
        // 将 FileItem 转换为 MultipartFile
        return new CommonsMultipartFile(fileItem);
    }
}
