package com.cyksj.common.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import javax.imageio.stream.FileImageOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * 项目名: yhlxj2
 * 文件名: ImageUploadUtil
 * 创建者: JavaZou
 * 创建时间:2025/4/21 15:16
 */
public class ImageUploadUtil {

	public static String upload(String url, String prefix) throws IOException {
		byte[] body = HttpUtil.downloadBytes(url);
		Path tempFile = Files.createTempFile(prefix, ".jpeg");
		try (
				FileImageOutputStream imageOutput = new FileImageOutputStream(tempFile.toFile())) {
			imageOutput.write(body, 0, body.length);
		}
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("file", tempFile.toFile());
		JSONObject result = JSONUtil.parseObj(HttpUtil.post("https://files.liuliangbang.vip/pic/ups", paramMap));
		FileUtil.del(tempFile);
		return result.getJSONObject("value").getJSONArray("saved").getJSONObject(0).getJSONObject("info").getStr("cdnUrl");
	}
}
