package com.ltgk.framework.config;

import com.ltgk.framework.listener.RedisClusterNodeUtil;
import com.ltgk.framework.listener.RedisKeyExpirationListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置
 *
 * @author wankun
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Value("${spring.redis.password}")
    private String redisPassword; // 从配置文件中获取密码
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    private final RocketMQTemplate rocketMQTemplate;
    private final RedisClusterNodeUtil redisClusterNodeUtil;

    public RedisConfig(RedisClusterNodeUtil redisClusterNodeUtil, RocketMQTemplate rocketMQTemplate, RedisConnectionFactory redisConnectionFactory) {
        this.redisClusterNodeUtil = redisClusterNodeUtil;
        this.rocketMQTemplate = rocketMQTemplate;
        this.redisConnectionFactory = redisConnectionFactory;
    }

    @Bean
    @SuppressWarnings(value = {"unchecked", "rawtypes"})
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public DefaultRedisScript<Long> limitScript() {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(limitScriptText());
        redisScript.setResultType(Long.class);
        return redisScript;
    }

    /**
     * 限流脚本
     */
    private String limitScriptText() {
        return "local key = KEYS[1]\n" +
                "local count = tonumber(ARGV[1])\n" +
                "local time = tonumber(ARGV[2])\n" +
                "local current = redis.call('get', key);\n" +
                "if current and tonumber(current) > count then\n" +
                "    return tonumber(current);\n" +
                "end\n" +
                "current = redis.call('incr', key)\n" +
                "if tonumber(current) == 1 then\n" +
                "    redis.call('expire', key, time)\n" +
                "end\n" +
                "return tonumber(current);";
    }

    @Bean
    public void redisMessageListenerContainer() {
        // 获取集群的所有节点
        Iterable<RedisClusterNode> nodes = redisClusterNodeUtil.getClusterNodes();
        // 为每个节点添加监听器
        for (RedisClusterNode node : nodes) {
            // 创建连接到当前节点的 LettuceConnectionFactory
            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
            config.setHostName(node.getHost()); // 节点主机
            config.setPort(node.getPort());     // 节点端口
            config.setPassword(RedisPassword.of(redisPassword)); // 设置密码
            LettuceConnectionFactory nodeConnectionFactory = new LettuceConnectionFactory(config);
            nodeConnectionFactory.afterPropertiesSet();
            //创建当前节点的监听容器
            RedisMessageListenerContainer nodeContainer = new RedisMessageListenerContainer();
            nodeContainer.setConnectionFactory(nodeConnectionFactory);
            nodeContainer.addMessageListener(messageListener(), new PatternTopic("__keyevent@*__:expired"));
            nodeContainer.afterPropertiesSet();
            // 启动监听容器
            nodeContainer.start();
        }
    }

    @Bean
    public MessageListenerAdapter messageListener() {
        return new MessageListenerAdapter(new RedisKeyExpirationListener(this.rocketMQTemplate), "onMessage");
    }
}
