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

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.lang.NonNull;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;

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

    /**
     * 下载资源
     *
     * @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;
    }


    /**
     * 网络url转MultipartFile
     */
    public static MultipartFile urlToMultipartFile(String url) {
        byte[] bytes = downloadResources(url); // 假设这是你现有的下载方法

        // 简单的文件名截取，建议加个校验防止url不带后缀报错
        String extension = url.contains(".") ? url.substring(url.lastIndexOf(".")) : ".tmp";
        String name = "mediaFile" + extension;

        // 自动探测类型，如果不需要太精确，用 "application/octet-stream" 代替 "text/plain" 更通用
        String contentType = "application/octet-stream";

        return getMultipartFile(name, bytes, contentType);
    }

    /**
     * 得到多部分文件 (重构版)
     */
    private static MultipartFile getMultipartFile(String name, byte[] bytes, String contentType) {
        // 直接返回自定义实现，无需 try-catch，无需 Commons IO
        return new ByteArrayMultipartFile("mainFile", name, contentType, bytes);
    }


    private static class ByteArrayMultipartFile implements MultipartFile {
        private final String name;
        private final String originalFilename;
        private final String contentType;
        private final byte[] content;

        public ByteArrayMultipartFile(String name, String originalFilename, String contentType, byte[] content) {
            this.name = name;
            this.originalFilename = originalFilename;
            this.contentType = contentType;
            this.content = (content != null) ? content : new byte[0];
        }

        @Override
        @NonNull
        public String getName() {
            return name;
        }

        @Override
        @NonNull
        public String getOriginalFilename() {
            return originalFilename;
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public boolean isEmpty() {
            return content.length == 0;
        }

        @Override
        public long getSize() {
            return content.length;
        }

        @Override
        @NonNull
        public byte[] getBytes() {
            return content;
        }

        @Override
        @NonNull
        public InputStream getInputStream() {
            return new ByteArrayInputStream(content);
        }

        @Override
        public void transferTo(@NonNull File dest) throws IOException, IllegalStateException {
            try (OutputStream out = Files.newOutputStream(dest.toPath())) {
                out.write(content);
            }
        }
    }


}
