package com.gree.mall.manager.config.wx;


import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.utils.RedisUtil;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.apache.commons.lang3.ObjectUtils;


public class WxCpLettuceRedisConfig extends WxCpDefaultConfigImpl {
    private RedisUtil redisUtil;
    private String accessTokenKey;

    public WxCpLettuceRedisConfig(RedisUtil redisUtil){
        this.redisUtil = redisUtil;
    }


    @Override
    public void setAgentId(Integer agentId){
        super.setAgentId(agentId);
        this.accessTokenKey = Constant.RedisPrefix.WORK_MINI_ACCESS_TOKEN+":"+agentId;
    }

    @Override
    public String getAccessToken() {
        return redisUtil.get(accessTokenKey).toString();
    }

    @Override
    public boolean isAccessTokenExpired() {
        Long expireTime = redisUtil.getExpire(accessTokenKey);
        if (ObjectUtils.isEmpty(expireTime)) {
            return true;
        }
        // 到期时间小于100秒就算作过期了，就重新调用接口获取
        return expireTime < 100;
    }

    @Override
    public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) {
        redisUtil.set(accessTokenKey, accessToken, expiresInSeconds - 200);
    }

    @Override
    public void expireAccessToken() {
        redisUtil.expire(accessTokenKey, 0);
    }


    @Override
    public long getExpiresTime() {
        Long expire = redisUtil.getExpire(accessTokenKey);
        return expire == null ? 0 : expire;
    }

    @Override
    public void setExpiresTime(long expiresTime) {
        redisUtil.expire(accessTokenKey, expiresTime);
    }
}
