package com.ruoyi.kkfileview.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.utils.StringUtils;

/**
 * 文件下载工具类
 * 
 * @author jackeyhuang
 * @version 1.0.0
 * @date 2026-01-11
 */
public class DownloadUtils
{
    private static final Logger log = LoggerFactory.getLogger(DownloadUtils.class);
    
    private static final int CONNECT_TIMEOUT = 30000; // 30秒
    private static final int READ_TIMEOUT = 60000; // 60秒

    /**
     * 从URL下载文件到本地
     * 
     * @param fileUrl 文件URL
     * @param targetFile 目标文件
     * @return 是否下载成功
     */
    public static boolean downloadFile(String fileUrl, File targetFile)
    {
        return downloadFile(fileUrl, targetFile, null);
    }

    /**
     * 从URL下载文件到本地（支持传递认证token）
     * 
     * @param fileUrl 文件URL
     * @param targetFile 目标文件
     * @param token 认证token（可选）
     * @return 是否下载成功
     */
    public static boolean downloadFile(String fileUrl, File targetFile, String token)
    {
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        
        try
        {
            // 确保目标文件的父目录存在
            File parentDir = targetFile.getParentFile();
            if (parentDir != null && !parentDir.exists())
            {
                parentDir.mkdirs();
            }
            
            URL url = new URL(fileUrl);
            URLConnection connection = url.openConnection();
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            
            // 如果是HTTP连接，设置请求头
            if (connection instanceof HttpURLConnection)
            {
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
                httpConnection.setInstanceFollowRedirects(true);
                // 如果提供了token，添加到请求头
                if (token != null && !token.isEmpty())
                {
                    httpConnection.setRequestProperty("Authorization", "Bearer " + token);
                }
            }
            
            // 检查响应码
            if (connection instanceof HttpURLConnection)
            {
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                int responseCode = httpConnection.getResponseCode();
                if (responseCode >= 400)
                {
                    log.error("文件下载失败，HTTP响应码: {}, URL: {}", responseCode, fileUrl);
                    return false;
                }
            }
            
            inputStream = connection.getInputStream();
            outputStream = new FileOutputStream(targetFile);
            
            IOUtils.copy(inputStream, outputStream);
            
            log.info("文件下载成功: {} -> {}", fileUrl, targetFile.getAbsolutePath());
            return true;
        }
        catch (Exception e)
        {
            log.error("文件下载失败: {}", fileUrl, e);
            // 如果下载失败，删除可能创建的不完整文件
            if (targetFile.exists())
            {
                targetFile.delete();
            }
            return false;
        }
        finally
        {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }
    }

    /**
     * 从URL获取文件输入流
     * 
     * @param fileUrl 文件URL
     * @return 输入流
     */
    public static InputStream getInputStream(String fileUrl) throws IOException
    {
        URL url = new URL(fileUrl);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        
        if (connection instanceof HttpURLConnection)
        {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
            httpConnection.setInstanceFollowRedirects(true);
        }
        
        return connection.getInputStream();
    }

    /**
     * 获取文件名（从URL中提取）
     * 
     * @param fileUrl 文件URL
     * @return 文件名
     */
    public static String getFileNameFromUrl(String fileUrl)
    {
        try
        {
            String path = new URL(fileUrl).getPath();
            if (StringUtils.isNotEmpty(path))
            {
                String fileName = path.substring(path.lastIndexOf('/') + 1);
                // URL解码
                return java.net.URLDecoder.decode(fileName, StandardCharsets.UTF_8.name());
            }
        }
        catch (Exception e)
        {
            log.warn("从URL提取文件名失败: {}", fileUrl, e);
        }
        return "file";
    }
}
