package org.jeecg.modules.hikiot;

import org.jeecg.common.exception.JeecgBootException;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import static com.alibaba.dashscope.utils.JsonUtils.gson;
import static org.jeecg.modules.hikiot.HikiotConstant.*;

public class HikiotTool {
    private static final HttpClient httpClient = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_2)
            .build();
    /**
     * 发送HTTPS POST请求
     * @param url 请求地址
     * @param jsonParam 请求参数（JSON格式）
     * @return 响应结果
     */
    public static String sendPostRequest(String url, String jsonParam) {
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type", "application/json; charset=UTF-8")
                    .POST(HttpRequest.BodyPublishers.ofString(jsonParam, StandardCharsets.UTF_8))
                    .build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            return response.body();
        } catch (Exception e) {
            throw new JeecgBootException("请求海康开放平台接口异常", e);
        }
    }
    /**
     * 发送HTTPS GET请求
     * @param url 完整请求地址（包含查询参数）
     * @return 响应结果
     */
    public static String sendGetRequest(String url) {
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Accept", "application/json")
                    .GET()
                    .build();
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            return response.body();
        } catch (Exception e) {
            throw new JeecgBootException("请求海康开放平台接口异常", e);
        }
    }

    /**
     * @Author SheepHy
     * @Description 获取应用访问凭证
     * @Date 16:05 2025/8/12
     **/
    public static String getAppAccessToken() {
        Map<String, String> map = new HashMap<>();
        map.put(APP_KEY, APP_KEY_VALUE);
        map.put(APP_SECRET, APP_SECRET_VALUE);
        return HikiotTool.sendPostRequest(GET_ACCESS_TOKEN_URL, gson.toJson(map));
    }

    /**
     * @Author SheepHy
     * @Description 刷新应用访问凭证
     * @Date 16:25 2025/8/12
     **/
    public static String refreshAppAccessToken(String appAccessToken, String refreshAppToken) {
        Map<String, String> map = new HashMap<>();
        map.put(APP_ACCESS_TOKEN, appAccessToken);
        map.put(REFRESH_APP_TOKEN, refreshAppToken);
        return HikiotTool.sendPostRequest(REFRESH_ACCESS_TOKEN_URL, gson.toJson(map));
    }
    public static void main(String[] args) {
        System.out.println(HikiotTool.getAppAccessToken());
    }
}
