package com.staffing.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.staffing.common.core.domain.WxLogin;
import com.staffing.common.core.domain.WxPhone;
import com.staffing.common.core.domain.WxToken;
import com.staffing.common.utils.http.HttpUtils;

import java.util.HashMap;
import java.util.Map;

public class WxUtil {
//  public final static String appId = "wx7bc7df6eb945a84f";//ps
//  public final static String secret = "60dc8f7e8c850dfbe0170acefa48070a";//ps
    public final static String appId = "wx26e952dad7a8aae5";
    public final static String secret = "60a85e94d921a385ce52faaaed4a103b";

    private static WxToken wxToken = null;

    public static synchronized WxToken getAccessToken(){
        if (wxToken == null || System.currentTimeMillis() > wxToken.getExpiresTime() - 60000){
            Map<String, String > getParam = new HashMap<>();
            getParam.put("grant_type", "client_credential");
            getParam.put("appid", appId);
            getParam.put("secret", secret);
            String resJson = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", HttpUtils.getParam(getParam));
            wxToken = JSONObject.parseObject(resJson, WxToken.class);
            wxToken.setExpiresTime(wxToken.getExpires_in() * 1000 + System.currentTimeMillis());
        }
        return wxToken;
    }

    /**
     * 获取手机号码
     * @param code，  前端api获取后 传的
     * @param openId    微信用户唯一表示
     * @return
     */
    public static WxPhone getPhoneNumber(String code, String openId){
        Map<String, String > getParam = new HashMap<>();
        getParam.put("code", code);
        getParam.put("openid", openId);
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + getAccessToken().getAccess_token();
        String resJson = HttpUtils.sendPost(url, JSONObject.toJSONString(getParam));
        WxPhone wxPhone = JSONObject.parseObject(resJson, WxPhone.class);

        return wxPhone;
    }
    /**
     * wx 登录 获取openId
     * @return
     */
    public static WxLogin login(String code){
        Map<String, String > getParam = new HashMap<>();
        getParam.put("grant_type", "authorization_code");
        getParam.put("appid", appId);
        getParam.put("secret", secret);
        getParam.put("js_code", code);
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String resJson = HttpUtils.sendGet(url, HttpUtils.getParam(getParam));
        WxLogin WxLogin = JSONObject.parseObject(resJson, WxLogin.class);
        return WxLogin;
    }

}
