package vip.xiaonuo.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.URIBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.exception.CommonException;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author wulei
 * @date 2024/11/1
 * @Version 1.0
 * @Description 获取微信openId 工具类
 */
@Slf4j
@Component
public class CommonWxUtil {

    //private static final String APP_ID = "wx3f94e7be85c27ff7";
    private static final String APP_ID = "wx2a107b653bd186f2";

    //private static final String SECRET = "9c9c0dee6be8a67d9946f0deb762ac7e";
    private static final String SECRET = "98988885bbc944567012e8331fe12dc2";

    private static final String GRANT_TYPE = "client_credential";

    private static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    /**
     * 获取微信openId
     *
     * @param code         小程序code 码
     * @param getOpenIdUrl 交换openId 地址
     * @param appId        appId
     * @param secret       secret
     * @return openId
     */
    public String getOpenId(String code, String getOpenIdUrl, String appId, String secret) {
        try {
            // 使用 URIBuilder 构建 URL
            URIBuilder uriBuilder = new URIBuilder(getOpenIdUrl);
            uriBuilder.addParameter("appid", appId)
                    .addParameter("secret", secret)
                    .addParameter("js_code", code)
                    .addParameter("grant_type", "authorization_code");
            String url = uriBuilder.build().toString();
            String responseBody = HttpUtil.get(url);
            if (responseBody == null || responseBody.isEmpty()) {
                return null;
            }
            JSONObject jsonObjectBody = JSONObject.parseObject(responseBody);
            if (jsonObjectBody.containsKey("openid")) {
                return jsonObjectBody.getString("openid");
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 调用微信接口获取accessToken
     *
     * @return
     * @throws Exception
     */
    public String getAccessToken() throws Exception {
        String accessToken = "";
        StringBuffer requestParam = new StringBuffer();
        requestParam.append(ACCESS_TOKEN_URL)
                .append("?appid=")
                .append(APP_ID)
                .append("&secret=")
                .append(SECRET)
                .append("&grant_type=")
                .append(GRANT_TYPE);
        try {
            String responseBody = HttpUtil.get(requestParam.toString());
            log.info("Calling WeChat to obtain return value information:{}", responseBody);
            JSONObject jsonObject = JSONObject.parseObject(responseBody);
            accessToken = jsonObject.getString("access_token");
        } catch (Exception e) {
            throw new CommonException("微信获取授权token异常，请联系管理员");
        }
        return accessToken;
    }

    /**
     * 调用微信接口获取手机号
     *
     * @param code
     * @return
     * @throws Exception
     */
    public String getPhoneNumber(String code) throws Exception {
        String accessToken = getAccessToken();
        if (StrUtil.isEmpty(accessToken)) {
            throw new CommonException("微信获取授权token异常，请联系管理员");
        }
        String phoneNumber = "";
        Map<String, String> map = new LinkedHashMap<>();
        map.put("code", code);
        try {
            String post = HttpUtil.post(GET_PHONE_URL + accessToken, JSONObject.toJSONString(map));
            JSONObject jsonObject = JSONObject.parseObject(post);
            if (jsonObject.getInteger("errcode") != 0) {
                throw new CommonException("微信获取授权手机号异常，请联系管理员");
            }
            JSONObject phoneInfo = (JSONObject) jsonObject.get("phone_info");
            phoneNumber = phoneInfo.getString("phoneNumber");
        } catch (Exception e) {
            log.error("Exception in calling WeChat to obtain phoneNumber:{}", e.getMessage());
            throw new CommonException("微信获取授权手机号异常，请联系管理员");
        }
        return phoneNumber;
    }



}
