package com.github.novicezk.midjourney.util;

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 springfox.documentation.schema.Maps;

import javax.crypto.spec.OAEPParameterSpec;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
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) {
        log.info("开始转换图片：{}", discordUrl);
        try {
            // 在线图片地址转换成base64
            URL url = new URL(discordUrl);
            InputStream inputStream = url.openStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            // 将图片数据读取到字节数组输出流
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 将字节数组输出流中的图片数据进行 Base64 编码
            byte[] imageBytes = outputStream.toByteArray();
            String base64Data = Base64.getEncoder().encodeToString(imageBytes);
            log.info("下载转换成了base64：{}", discordUrl);
            String last = discordUrl.substring(discordUrl.lastIndexOf(".") + 1);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("base64Image", base64Data);
            jsonObject.put("extension", last);
            HttpRequest request = HttpRequest.post(domain + "/raysserve/v1.0/readArticle/obsUploadbase64")
                    .setConnectionTimeout(1000 * 60 * 10)
                    .header("accept", "application/json")
                    .header("content-type", "application/json")
                    .body(jsonObject.toString(), "application/json;charset=utf-8");
            HttpResponse httpResponse = request.execute();
            log.info("调用远程上传接口返回：{}", httpResponse.body());
            String uploadUrl = Optional.ofNullable(httpResponse.body())
                    .map(JSONObject::new)
                    .map(x -> x.getJSONObject("data"))
                    .map(x -> x.getString("url"))
                    .orElse("");
            return uploadUrl;
        } catch (Exception e) {
            log.error("将在线图片url转换成base64异常：{}", e);
        }
        return "";
    }
}
