package com.ruoyi.common.third.cache.redis;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.ruoyi.common.third.cache.HzCacheManager;
import com.ruoyi.common.third.properties.HzRedisProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;


@Configuration
@EnableConfigurationProperties({HzRedisProperties.class})
@ConditionalOnProperty(prefix = "third-switch.cache", name = "cacheType", havingValue = "redis")
public class HzRedisAutoConfiguration {
    private  final Logger logger = LoggerFactory.getLogger(HzRedisAutoConfiguration.class);
    private HzRedisProperties hzRedisProperties;

    public HzRedisAutoConfiguration(HzRedisProperties hussarRedisProperties) {
        this.hzRedisProperties = hussarRedisProperties;
    }


    /***
     * 配置key的序列化方式
     * */
    @Bean
    public RedisSerializer<String> stringRedisSerializer() {
        return new StringRedisSerializer();
    }
    /**
     * 配置value的序列的方式
     * */
    @Bean
    public RedisSerializer jackson2JsonRedisSerializer() {
        //使用Jackson2JsonRedisSerializer替换默认的JdkSerializationRedisSerializer来序列化和反序列化redis的value值
        ObjectMapper mapper = new ObjectMapper();
        // 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型，类必须是非final修饰的，final修饰的类，比如String,Integer等会跑出异常
        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
        // 解决locadatetime 序列化的问题
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        // json 和多余的字段无法匹配不报异常
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.registerModule(new JavaTimeModule());
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        jackson2JsonRedisSerializer.setObjectMapper(mapper);
        return jackson2JsonRedisSerializer;
    }

    /**
     * zp 增加了stringRedisTemplate的模板方法
     * */
    @Bean
    @ConditionalOnMissingBean(name = "stringRedisTemplate")
    public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(lettuceConnectionFactory);
        //key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer());
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer());
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer());
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
    /**
     *  RedisCacheManager 的自定义配置
     * @param redisCacheWriter
     * @return
     */
    @Bean
    public RedisCacheManager cacheManager(RedisCacheWriter redisCacheWriter) {
        //初始化一个RedisCacheWriter
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                //缓存失效时间
                .entryTtl(Duration.ZERO)
                //key序列化方式
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer()))
                //value序列化方式
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))
                //不允许缓存null值
                .disableCachingNullValues();
        //return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
        // 通过两种方式进行builder factory 一个事writer
        return RedisCacheManager.builder(redisCacheWriter)
                //默认缓存配置
                .cacheDefaults(defaultCacheConfig)
                //初始化缓存空间
                 //.initialCacheNames(cacheNames)
               .build();
    }
    /***
     * 注入自定义的缓存管理器主要是用来utils 操作缓存
     * 强转了HUssarRedisCacheWriter方法  因为新增的新的方法
     * **/
    @Bean
    public HzCacheManager hussarRedisManager(RedisCacheManager cacheManager, LettuceConnectionFactory lettuceConnectionFactor, RedisCacheWriter redisCacheWriter){
        return new RedisManager(cacheManager,lettuceConnectionFactor,(HzRedisCacheWriter)redisCacheWriter);
    }
    /***
     * 注入 HussarRedisManager 时候需要注入 RedisCacheWriter
     * */
    @Bean
    public RedisCacheWriter redisCacheWriter(LettuceConnectionFactory lettuceConnectionFactory) {
        return HzRedisCacheWriter.nonLockingRedisCacheWriter(lettuceConnectionFactory);
    }

}
