/*
 * Copyright (c) 京北方信息技术股份有限公司 Corporation 2021 . All rights reserved.
 *
 */
package net.northking.cctp.common.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
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 net.northking.cctp.common.cache.EntityNameCache;
import net.northking.cctp.common.cache.EntityNameRedisRepository;
import net.northking.cctp.common.saas.cache.SaaSTenantCache;
import net.northking.cctp.common.saas.cache.StaticTenantCache;
import net.northking.cctp.common.security.authorization.ResourceAuthorityCache;
import net.northking.cctp.common.security.authorization.ResourceAuthorityRedisRepository;
import net.northking.cctp.common.sequence.SequenceDistributedService;
import net.northking.cctp.common.sequence.SequenceNoneStorage;
import net.northking.cctp.common.sequence.SequenceService;
import net.northking.cctp.common.sequence.SequenceStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.integration.redis.util.RedisLockRegistry;

/**
 * 平台缓存配置
 *
 * @author : xiusong.xie
 * @version : 1.0
 */
@Configuration
public class CacheConfiguration
{
  private static final Logger logger = LoggerFactory.getLogger(CacheConfiguration.class);

  /**
   * 统一配置 redisTemplate
   *
   * @return redisTemplate
   */
  @Bean
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory)
  {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    // 配置连接工厂
    template.setConnectionFactory(factory);

    //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值（默认使用JDK的序列化方式）
    Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

    ObjectMapper om = new ObjectMapper();
    // 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    // 指定序列化输入的类型，类必须是非final修饰的，final修饰的类，比如String,Integer等会跑出异常
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jsonRedisSerializer.setObjectMapper(om);

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

    // 设置hash key 和value序列化模式
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(jsonRedisSerializer);
    template.afterPropertiesSet();

    logger.info("注册公共组件提示：统一配置 RedisTemplate<String, Object> 已完成。");
    return template;
  }

  /**
   * 配置Spring Cache序列化方式：JSON
   *
   * @return RedisCacheConfiguration
   */
  @Bean
  public RedisCacheConfiguration redisCacheConfiguration()
  {
    //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值（默认使用JDK的序列化方式）
    Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

    ObjectMapper om = new ObjectMapper();
    // 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    // 指定序列化输入的类型，类必须是非final修饰的，final修饰的类，比如String,Integer等会跑出异常
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    // 找不到匹配属性时忽略报错
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // 不包含任何属性的bean也不报错
    om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    // JSON序列化忽略空值（包含NULL和空字符串）
    om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    jsonRedisSerializer.setObjectMapper(om);
    logger.info("注册公共组件提示：统一配置 Spring Cache序列化方式：JSON。");
    return RedisCacheConfiguration.defaultCacheConfig()
        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jsonRedisSerializer));
  }

  /**
   * 基于Redis的全局锁
   *
   * @return 全局锁
   */
  @Bean
  public RedisLockRegistry redisLockRegistry(RedisConnectionFactory factory)
  {
    logger.info("注册公共组件提示：统一配置 全局锁(RedisLockRegistry) 已完成。");
    return new RedisLockRegistry(factory, "CCTP_LOCK");
  }

  /**
   * 资源权限缓存
   *
   * @return 资源权限缓存
   */
  @Bean
  @ConditionalOnMissingBean
  public ResourceAuthorityCache resourceAuthorityCache(RedisTemplate<String, Object> redisTemplate)
  {
    logger.info("注册公共组件提示：统一配置 用户权限缓存(ResourceAuthorityCache) 已完成。");
    return new ResourceAuthorityRedisRepository(redisTemplate);
  }

  /**
   * 实体命名缓存
   *
   * @return 实体命名缓存
   */
  @Bean
  @ConditionalOnMissingBean
  public EntityNameCache entityNameCache(RedisTemplate<String, Object> redisTemplate)
  {

    logger.info("注册公共组件提示：统一配置 实体命名缓存(EntityNameCache) 已完成。");
    return new EntityNameRedisRepository(redisTemplate);
  }

  /**
   * 静态租户缓存
   *
   * @return 静态租户缓存
   */
  @Bean
  @ConditionalOnMissingBean
  public SaaSTenantCache staticTenantCache()
  {
    return new StaticTenantCache();
  }


  /**
   * 注册：序列持久化服务
   *
   * @return 序列持久化服务
   */
  @Bean
  @ConditionalOnMissingBean
  public SequenceStorage sequenceStorage()
  {
    return new SequenceNoneStorage();
  }

  /**
   * 注册： 分布式序列服务
   *
   * @param factory         redis连接工厂
   * @param sequenceStorage 序列持久化服务
   * @return 分布式序列服务
   */
  @Bean
  public SequenceService sequenceService(RedisConnectionFactory factory, SequenceStorage sequenceStorage)
  {
    logger.info("注册公共组件提示：统一配置 分布式序列服务(SequenceService) 已完成。");

    return new SequenceDistributedService(factory, sequenceStorage);
  }
}
