package tech.glinfo.enbao.common.utils;

import com.alibaba.nls.client.AccessToken;
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.io.IOException;

@Component
public class AliGetTokenUtils {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${aliyunspeed.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyunspeed.accessKeySecret}")
    private String accessKeySecret;

    @Autowired
    private RedisUtils redisUtils;

    public String getToken() {
        String token = redisUtils.get("aliyun_access_token");
        if (token == null) {
            AccessToken accessToken = new AccessToken(accessKeyId, accessKeySecret);
            try {
                accessToken.apply();
                logger.info("get token: {}, expire time: {}", accessToken.getToken(), accessToken.getExpireTime());
                token = accessToken.getToken();
                redisUtils.set("aliyun_access_token", accessToken.getToken(), (accessToken.getExpireTime() - System.currentTimeMillis()/1000 - 10));
            } catch (IOException e) {
                logger.error("阿里云获取token出错了：", e);
            }
        }
        return token;
    }
}