package com.tofly.auth.callback;

import com.tofly.auth.feign.BaseUserLoginService;
import com.tofly.common.core.entity.ResultRespone;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

//@Component
@Slf4j
public class RedisKeyExpirationListerner extends KeyExpirationEventMessageListener {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private BaseUserLoginService baseUserLoginService;
    public RedisKeyExpirationListerner(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
 
    /**
     * 使用该方法监听 ,当我们的key失效的时候执行改方法
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String keyExpira = message.toString();
        log.info("keyExpira======>>>>>>{}"+keyExpira);
        //拿到过期key ,处理业务逻辑
        String key = keyExpira + "_2";
        Boolean aBoolean = redisTemplate.hasKey(key);
        if(null!=aBoolean && aBoolean){
            String username = (String) redisTemplate.opsForValue().get(key);
            if(!StringUtils.isEmpty(username)){
                log.info("计算当前用户登录时长{}",username);
                ResultRespone<Boolean> booleanResultRespone = baseUserLoginService.updateUserOperationTime(username);
                // 删除回调token
                redisTemplate.delete(key);
                System.out.println(booleanResultRespone.getResult());
            }
        }
    }
}