package com.mortals.xhx.common.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CompletableFuture;

/**
 * @author ZYW
 * @date 2024-12-24 16:16
 */

public class FileDownloader {
    public interface Callback {
        void onSuccess();
        void onError(Exception e);
    }

    public static void downloadFileFromUrl(String urlPath, String downloadDir, Callback callback) {
        CompletableFuture.runAsync(() -> {
            File file = null;
            try {
                // 统一资源
                URL url = new URL(urlPath);
                // 连接类的父类，抽象类
                URLConnection urlConnection = url.openConnection();
                // http的连接类
                HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                //设置超时
                httpURLConnection.setConnectTimeout(1000 * 30);
                //设置请求方式，默认是GET
                httpURLConnection.setRequestMethod("GET");
                // 设置字符编码
                httpURLConnection.setRequestProperty("Charset", "UTF-8");
                // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
                httpURLConnection.connect();
                // 文件大小
                int fileLength = httpURLConnection.getContentLength();

                // 控制台打印文件大小
                // System.out.println("下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");

                // 建立链接从请求中获取数据
                URLConnection con = url.openConnection();
                BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
                // 指定文件名称(有需求可以自定义)
                String fileFullName =  urlPath.split("/")[urlPath.split("/").length - 1];
                // 指定存放位置(有需求可以自定义)
                String path = downloadDir;
                file = new File(path);
                // 校验文件夹目录是否存在，不存在就创建一个目录
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }

                OutputStream out = new FileOutputStream(file);
                int size = 0;
                int len = 0;
                byte[] buf = new byte[2048];
                while ((size = bin.read(buf)) != -1) {
                    len += size;
                    out.write(buf, 0, size);
                    // 控制台打印文件下载的百分比情况
                    // System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
                }
                // 关闭资源
                bin.close();
                out.close();
                // 成功后调用回调函数
                if (callback != null) {
                    callback.onSuccess();
                }
            } catch (Exception e) {
                // 出错时调用回调函数
                if (callback != null) {
                    callback.onError(e);
                }
            }
        });
    }

    public static void main(String[] args) {
        String url = "http://example.com/somefile.zip"; // 替换为实际的URL
        String filename = "somefile.zip"; // 替换为想要保存的文件名
        downloadFileFromUrl(url, filename, new Callback() {
            @Override
            public void onSuccess() {
                System.out.println("文件下载成功！");
            }

            @Override
            public void onError(Exception e) {
                System.out.println("文件下载出错：" + e.getMessage());
            }
        });
    }
}
