package yangtz.cs.liu.wechat.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * @author lyric
 * @date 2022/10/18 15:30
 */
@Component
public class AccessTokenUtil {

    @Value("${wx.access-token-uri}")
    private String accessTokenUri;

    public final String ACCESS_TOKEN = "access_token";

    private static Logger log = LoggerFactory.getLogger(AccessTokenUtil.class);

    @Autowired
    public RedisCache redisCache;

    public String getToken() {
        String token = redisCache.getCacheObject(ACCESS_TOKEN);
        if (StringUtils.isEmpty(token)) {
            try {
                String url = accessTokenUri;
                //测试环境
//                String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx765a55464b308d13&secret=aa6741b17f05203975b17f0a64458741";
                // 利用hutool的http工具类请求获取access_token
                String result = HttpUtil.get(url);
                // 将结果解析为json
                JSONObject jsonObject = JSONUtil.parseObj(result);
                // 获取access_token
                String accessToken = (String) jsonObject.get("access_token");
                if (!StringUtils.isEmpty(accessToken)) {
                     token = accessToken;
                    log.info(accessToken);
                    // 将access_token存入redis
                    redisCache.setCacheObject("access_token", accessToken, 90, TimeUnit.MINUTES);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return token;
    }
}
