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 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;

/**
 * @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;
                // 利用hutool的http工具类请求获取access_token
                String result = HttpUtil.get(url);
                // 将结果解析为json
                JSONObject jsonObject = JSONUtil.parseObj(result);
                // 获取access_token
                String accessToken = jsonObject.getStr("access_token");
                if (!StringUtils.isEmpty(accessToken)) {
                    token = accessToken;
                    log.info(accessToken);
                    // 将access_token存入redis
                    redisCache.setCacheObject("access_token", accessToken, 2, TimeUnit.HOURS);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return token;
    }
}
