package com.jeeplus.modules.wexinpackage.access.util.access;

import com.jeeplus.common.utils.JedisUtils;
import com.jeeplus.modules.wexinpackage.access.entity.AccessToken;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class AccessTokenUtil {
    private static Logger log = (Logger) LoggerFactory.getLogger(RequestAccess.class);
    //获取redis中得access_token
    public static String getAccessToken(String corpId,String corpSecret){
        String access_token = "";
//        boolean flag = JedisUtils.exists("access_token");
            access_token = JedisUtils.get("access_token");
        if (null==access_token){
            AccessToken accessTokenUtil = getAccessTokenUtil(corpId, corpSecret);
            JedisUtils.set("access_token",accessTokenUtil.getToken(),accessTokenUtil.getExpiresIn()- 1000);
            access_token = accessTokenUtil.getToken();
        }
        return access_token;
    }

    /**
         //     * 3.获取access_token
         //     * @param corpId 凭证
         //     * @param corpsecret 密钥
         //     * @return AccessToken
         //
     */
    public static AccessToken getAccessTokenUtil(String corpId, String corpSecret) {
        AccessToken accessToken = null;
        String requestUrl = WeChatParamsUtil.ACCESS_TOKEN_URL.replace("{corpId}", corpId).replace("{corpsecret}",corpSecret);
        JSONObject jsonObject = RequestAccess.httpRequest(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessToken();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return accessToken;
    }
//    @Test
//    public void getAccessToken(){
//        getAccessToken(WeChatParamsUtil.corpId,WeChatParamsUtil.contactsSecret);
//    }
}
