package com.ruoyi.common.utils.wechat;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 获取微信公众号token工具
 * </p>
 */
@Slf4j
public class AccessTokenUtils {

    public static String appId;
    public static String secret;
    public static int expireTime;
    public static String accessTokenUrl;

    /**
     * 获取token
     *
     * @return 结果
     */
    public static String getToken() {
        String token = SpringUtils.getBean(RedisCache.class).getCacheObject("wechat_token");
        if (StringUtils.isEmpty(token)) {
            try {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(accessTokenUrl + "?grant_type=client_credential&appid=" + appId + "&secret=" + secret).build();
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    String string = response.body().string();
                    token = JSON.parseObject(string).getString("access_token");
                    SpringUtils.getBean(RedisCache.class).setCacheObject("wechat_token", token, expireTime, TimeUnit.MINUTES);
                    System.out.println("**********************************************************************");
                }
            } catch (Exception e) {
                log.info("获取weChat_token时异常" + e);
            }
        }
        return token;
    }
}
