package com.ruoyi.common.auth.wx;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.WxConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wjh
 * 2024/7/29
 */
@Service
@Slf4j
public class WxAuthService {


    @Autowired
    private WxConfig wxConfig;

    /**
     * 使用登录码获取微信用户信息
     * @param jsCode 登录码，通过wx.login获得
     */
    public WxMaJscode2SessionResult wxJsCode2Session(String jsCode) {
        String grantType = "authorization_code";
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=%s", wxConfig.getAppId(), wxConfig.getAppSecret(), jsCode, grantType);
        String body = HttpUtils.sendGet(url);
        return JSON.parseObject(body, WxMaJscode2SessionResult.class);
    }

    public String getOpenId(String loginCode) {
        if (loginCode == null) {
            return null;
        }
        // 通过登录授权码获取到用户信息
        WxMaJscode2SessionResult wxMaJscode2SessionResult = this.wxJsCode2Session(loginCode);
        if (wxMaJscode2SessionResult == null) {
            return null;
        }
        return wxMaJscode2SessionResult.getOpenid();
    }

    /**
     * 通过微信手机号授权码获取微信手机号
     * @param mobileCode 微信手机号授权码
     * @return
     */
    public String getWxPhoneNumber(String mobileCode) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

        // 根据手机号获取到用户名
        String token = AccessTokenUtil.getToken();
        url = url + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", mobileCode);
        String post = HttpUtils.sendPost(url, jsonObject.toString());
        // 获取微信用户手机号
        JSONObject body = JSONObject.parseObject(post);
        if (body == null) {
            return null;
        }

        Integer errcode = body.getInteger("errcode");
        if (errcode == null || !errcode.equals(0)) {
            log.error("获取手机号失败 {}", body);
            throw new ServiceException("获取手机号失败");
        }

        String phoneInfo = body.getString("phone_info");
        WxMaPhoneNumberInfo wxMaPhoneNumberInfo = JSONObject.parseObject(phoneInfo, WxMaPhoneNumberInfo.class);
        if (wxMaPhoneNumberInfo == null) {
            return null;
        }

        return wxMaPhoneNumberInfo.getPhoneNumber();
    }

}
