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.mp.config.impl.WxMpDefaultConfigImpl;
import org.apache.commons.lang3.ObjectUtils;

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

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

    @Override
    public void setAppId(String appId) {
        super.setAppId(appId);
        this.accessTokenKey = Constant.RedisPrefix.TOKEN_MP_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);
    }
}
