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


import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.utils.RedisUtil;
import org.apache.commons.lang3.ObjectUtils;

/**
 * 重写WxMaService服务，让其支持lettuce客户端
 */
public class WxMaLettuceRedisConfig extends WxMaDefaultConfigImpl {
    private RedisUtil redisUtil;
    private String accessTokenKey;

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

    @Override
    public void setAppid(String appid) {
        super.setAppid(appid);
        this.accessTokenKey = Constant.RedisPrefix.TOKEN_WX+":"+appid;
    }

    @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);
    }
}
