package yangtz.cs.liu.dingding.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
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.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class AccessTokenUtils {

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

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

    @Autowired
    public RedisCache redisCache;

    /**
     * 获取token
     * @return
     * @throws Exception
     */
    public String getToken(){
        String token = redisCache.getCacheObject("dd_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 = (String) jsonObject.get("access_token");
                if (!StringUtils.isEmpty(accessToken)) {
                    token = accessToken;
                    log.info(accessToken);
                    // 将access_token存入redis
                    redisCache.setCacheObject("dd_access_token", accessToken, 7200, TimeUnit.MILLISECONDS);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return token;
    }
}
