package org.dromara.zhishu.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

public class Base64Utils {

    /**
     * 从指定URL读取CSV文件并返回Base64编码字符串
     *
     * @param csvUrl CSV文件的网络路径
     * @return Base64编码的文件内容
     * @throws IOException 网络连接或文件读取异常
     */
    public static String readCsvAndEncodeToBase64(String csvUrl) throws IOException {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(csvUrl);
            connection = (HttpURLConnection) url.openConnection();

            // 设置请求属性
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000); // 连接超时5秒
            connection.setReadTimeout(10000);   // 读取超时10秒
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");

            // 检查响应码
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new IOException("Failed to download file. HTTP response code: " + responseCode);
            }

            // 读取文件内容并转换为Base64
            try (InputStream inputStream = connection.getInputStream();
                 ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {

                byte[] data = new byte[1024];
                int bytesRead;

                while ((bytesRead = inputStream.read(data)) != -1) {
                    buffer.write(data, 0, bytesRead);
                }

                byte[] fileBytes = buffer.toByteArray();
                return Base64.getEncoder().encodeToString(fileBytes);
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

}
