package ink.wgink.module.wechat.manager;

import ink.wgink.module.wechat.pojo.OfficialAccountAccessToken;
import ink.wgink.module.wechat.request.AccessTokenRestTemplate;
import ink.wgink.properties.wechat.official.account.OfficialAccountProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: AccessTokenManager
 * @Description: access_token控制器
 * @Author: wanggeng
 * @Date: 2021/4/27 5:19 下午
 * @Version: 1.0
 */
public class OfficialAccountAccessTokenManager {

    private static final Logger LOG = LoggerFactory.getLogger(OfficialAccountAccessTokenManager.class);
    /**
     * 最大过期毫秒
     */
    private static long MAXIMUM_EXPIRE_MILLISECOND = 5400000;
    private static OfficialAccountAccessTokenManager officialAccountAccessTokenManager = AccessTokenManagerFactory.officialAccountAccessTokenManager;
    private OfficialAccountAccessToken officialAccountAccessToken;

    private OfficialAccountAccessTokenManager() {
    }

    public static OfficialAccountAccessTokenManager getInstance() {
        return officialAccountAccessTokenManager;
    }

    /**
     * 刷新access_token
     */
    public void refreshAccessToken(OfficialAccountProperties officialAccountProperties) {
        long currentTime = System.currentTimeMillis();
        if (officialAccountAccessToken != null && (currentTime - this.officialAccountAccessToken.getLastUpdated()) < MAXIMUM_EXPIRE_MILLISECOND) {
            return;
        }
        LOG.debug("刷新公众号 AccessToken 开始");
        AccessTokenRestTemplate accessTokenRestTemplate = new AccessTokenRestTemplate(officialAccountProperties);
        accessTokenRestTemplate.get(accessTokenRestTemplate.getAccessTokenUrl());
        LOG.debug("accessToken: {}", this.officialAccountAccessToken);
        LOG.debug("刷新公众号 AccessToken 结束");
    }

    public void setAccessToken(OfficialAccountAccessToken officialAccountAccessToken) {
        this.officialAccountAccessToken = officialAccountAccessToken;
    }

    public OfficialAccountAccessToken getAccessToken() {
        return officialAccountAccessToken;
    }

    private static class AccessTokenManagerFactory {
        public static OfficialAccountAccessTokenManager officialAccountAccessTokenManager = new OfficialAccountAccessTokenManager();
    }

}
