package com.ruoyi.common.utils;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

public class WeChat {

    private static final String APP_ID = "wxa5c97dfa28e626a9";
    private static final String APP_SECRET = "aec1f83119a370f49d1b430dcd90f3a5";
    private static final String CODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 通过 code 换取 openid 和 session_key
     *
     * @param code 微信小程序登录时获取的 code
     * @return 包含 openid 和 session_key 的 Map
     * @throws IOException 如果请求失败或解析响应时出错
     */
    public static Map<String, String> getOpenIdAndSessionKey(String code) throws IOException {
        // 构建请求 URL
        String url = CODE_TO_SESSION_URL + "?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";

        // 创建 HttpClient 实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建 GET 请求
            HttpGet httpGet = new HttpGet(url);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                // 获取响应内容
                String responseBody = EntityUtils.toString(response.getEntity());

                // 使用 Jackson 解析 JSON 响应
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, String> resultMap = objectMapper.readValue(responseBody, Map.class);

                // 检查是否有错误码
                if (resultMap.containsKey("errcode")) {
                    throw new RuntimeException("微信接口调用失败: " + resultMap.get("errmsg"));
                }

                return resultMap;
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
