package com.ssyf.plugs.cache.config;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.ssyf.plugs.cache.AdaptCacheManager;
import com.ssyf.plugs.cache.RedisCacheMessageListener;
import com.ssyf.plugs.cache.customs.CustomRedisMessageListener;
import com.ssyf.plugs.cache.properties.CacheProperties;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.List;
import java.util.stream.Collectors;

/**
 * redis 缓存
 * @author huwei
 * @date 2022/11/29 8:46
 */
@Configuration
@ConditionalOnProperty(value = "cache.redis-enabled")
public class RedisConfig {

    @Autowired
    private CacheProperties cacheProperties;

    private ApplicationContext applicationContext;

    public RedisConfig(@Autowired ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        // 使用Jackson2JsonRedisSerialize 替换默认序列化(默认采用的是JDK序列化)
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.registerModule(new JavaTimeModule());
        // 解决jackson无法反序列化LocalDateTime的问题
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//        om.registerModule(new JavaTimeModule());
        om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        template.setKeySerializer(stringRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();
        return template;
    }


    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisTemplate<String, Object> redisTemplate) {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisTemplate.getConnectionFactory());

        List<CustomRedisMessageListener> listenerList = getRedisMessageListener();
        if(listenerList.isEmpty()){
            return redisMessageListenerContainer;
        }
        for(CustomRedisMessageListener listener : listenerList){
            if(listener.topics() == null || listener.topics().isEmpty()){
                continue;
            }
            for(String topic : listener.topics()){
                if(StrUtil.isBlank(topic)){
                    continue;
                }
                redisMessageListenerContainer.addMessageListener(listener.listener(), new ChannelTopic(topic));
            }
        }
        return redisMessageListenerContainer;
    }

    private List<CustomRedisMessageListener> getRedisMessageListener(){
        return applicationContext.getBeansOfType(CustomRedisMessageListener.class).values().stream().collect(Collectors.toList());
    }
}
