package org.dromara.main.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.main.config.WechatMiniAppConfig;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class WechatMiniAppUtil {
    private static WechatMiniAppConfig config;
    public WechatMiniAppUtil(WechatMiniAppConfig config) {
        WechatMiniAppUtil.config = config;
    }

    private static final String CODE_2_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 通过 code 换取 openid 和 session_key
     */
    public static JSONObject code2Session(String code) {
        String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
            CODE_2_SESSION_URL, config.getAppId(), config.getAppSecret(), code);
        try {
            String response = HttpUtil.get(url);
            JSONObject result = JSONUtil.parseObj(response);
            if (result.containsKey("errcode") && result.getInt("errcode") != 0) {
                log.error("微信code2Session失败: {}", result.getStr("errmsg"));
                return null;
            }
            return result;
        } catch (Exception e) {
            log.error("调用微信code2Session接口异常", e);
            return null;
        }
    }
    /**
     * 通过 phoneCode 获取手机号 (新版API)
     */
    public static JSONObject getPhoneNumberByCode(String phoneCode) {
        String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
            config.getAppId(), config.getAppSecret());
        try {
            String tokenResponse = HttpUtil.get(tokenUrl);
            JSONObject tokenResult = JSONUtil.parseObj(tokenResponse);
            if (tokenResult.containsKey("errcode")) {
                log.error("获取access_token失败: {}", tokenResult.getStr("errmsg"));
                return null;
            }
            String accessToken = tokenResult.getStr("access_token");

            // 使用 access_token 获取手机号
            String phoneUrl = String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s", accessToken);
            JSONObject requestBody = new JSONObject();
            requestBody.set("code", phoneCode);

            String phoneResponse = HttpUtil.post(phoneUrl, requestBody.toString());
            JSONObject phoneResult = JSONUtil.parseObj(phoneResponse);

            if (phoneResult.getInt("errcode") != 0) {
                log.error("获取手机号失败: {}", phoneResult.getStr("errmsg"));
                return null;
            }
            return phoneResult.getJSONObject("phone_info");
        } catch (Exception e) {
            log.error("调用微信获取手机号接口异常", e);
            return null;
        }
    }
}
