package com.zanxiang.game.module.manage.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author : lingfeng
 * @time : 2023-02-06
 * @description : 文件工具类
 */
public class FileUtil {

    /**
     * 网络url转MultipartFile
     *
     * @param url : 网络资源url
     * @return {@link MultipartFile}
     */
    public static MultipartFile urlToMultipartFile(String url) {
        byte[] bytes = downloadResources(url);
        String name = "mediaFile" + url.substring(url.lastIndexOf("."));
        return getMultipartFile(name, bytes);
    }

    /**
     * 下载资源
     *
     * @param url url
     * @return {@link byte[]}
     */
    private static byte[] downloadResources(String url) {
        URL urlConnection;
        HttpURLConnection connection = null;
        try {
            urlConnection = new URL(url);
            connection = (HttpURLConnection) urlConnection.openConnection();
            InputStream in = connection.getInputStream();
            byte[] buffer = new byte[1024];
            int len;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            in.close();
            out.close();
            return out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return null;
    }

    /**
     * 得到多部分文件
     *
     * @param name  名字
     * @param bytes 字节
     * @return {@link MultipartFile}
     */
    private static MultipartFile getMultipartFile(String name, byte[] bytes) {
        MultipartFile multipartFile = null;
        ByteArrayInputStream in;
        try {
            in = new ByteArrayInputStream(bytes);
            FileItemFactory factory = new DiskFileItemFactory(16, null);
            FileItem fileItem = factory.createItem("mainFile", "text/plain", false, name);
            IOUtils.copy(new ByteArrayInputStream(bytes), fileItem.getOutputStream());
            multipartFile = new CommonsMultipartFile(fileItem);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }


}
