package com.github.novicezk.midjourney.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.Optional;

@Slf4j
@Component("fileUtil")
public class FileUtil {

    @Value("${file.convert.domain}")
    private String domain;

    /**
     * 将外网地址url转换成华为云地址
     *
     * @param discordUrl
     * @return
     */
    public String convertFile(String discordUrl) {
        File file = urlToFile(discordUrl);
        if(ObjectUtil.isNull(file)) {
            log.info("在线图片地址转换成File返回为空");
            return "";
        }
        log.info("开始调用转换url接口：{}", discordUrl);
        String apiUrl = domain + "/raysserve/v1.0/readArticle/obsUpload";//替换为您的接口URL
        HttpRequest httpRequest = HttpUtil.createPost(apiUrl);
        httpRequest.setReadTimeout(1000 * 60 * 3);
        httpRequest.form("file", file);
        HttpResponse execute = httpRequest.execute();
        String body = execute.body();
        log.info("调用转换url接口返回的数据：{}", body);
        String res = Optional.ofNullable(body)
                .map(JSONObject::new)
                .map(x -> x.getJSONObject("data"))
                .map(x -> x.getString("url"))
                .orElse("");
        return res;
    }

    /**
     * 将外网地址url转换成华为云地址
     *
     * @param discordUrl
     * @return
     */
    public String convertFile1(String discordUrl, String end) {
        File file = urlToFile(discordUrl);
        if(ObjectUtil.isNull(file)) {
            log.info("在线图片地址转换成File返回为空");
            return "";
        }
        log.info("调用华为云上传图片：{}", discordUrl);
        String uploadUrl = OBSUtil.upload(file, discordUrl.substring(discordUrl.lastIndexOf(".") + 1), end);
        return uploadUrl;
    }

    /**
     * 在线图片地址转换成File
     *
     * @param urlStr
     * @return
     */
    public File urlToFile(String urlStr) {
        log.info("开始在线图片地址转换成File:{}", urlStr);
        URLConnection conn = null;
        File file = null;
        try {
            URL url = new URL(urlStr);
            conn = url.openConnection();
            conn.setConnectTimeout(1000 * 60);
            String endLast = urlStr.substring(urlStr.lastIndexOf("."));
            file = new File("mj" + endLast);

            // try-with-resources语句块确保了InputStream和FileOutputStream在代码块结束时自动关闭，无需手动调用close()方法,
            // 我们没有手动关闭URLConnection，但它的资源和连接会在InputStream和FileOutputStream被关闭时自动释放。
            // 这是因为在下载过程中，URLConnection的输入流与远程服务器建立了连接，而输出流与本地文件建立了连接。
            // 在使用try-with-resources的代码块中，当InputStream和FileOutputStream被关闭时，底层的URLConnection也会被关闭。
            try (InputStream inputStream = conn.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(file)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                log.info("在线url地址转换成file文件后的路径：{}", file.getAbsolutePath());
                return file;
            }
        } catch (IOException e) {
            log.info("在线url地址转换成file文件异常：{}", urlStr, e);
        }
        return null;
    }
}
