package com.sunyard.ssp.redis;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

@Slf4j
@Configuration
public class JedisClusterConfig extends CachingConfigurerSupport {

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.cluster.nodes}")
    private String redisNodes;

    @Value("${spring.redis.isJq}")
    private Boolean isJq;

    @Value("${spring.redis.host}")
    private String host2;

    @Value("${spring.redis.port}")
    private int port2;

    private int connectionTimeout = 6000;

    private int soTimeout = 2000;

    private int maxAttempts = 10;

    private int maxTotal = 800;

    private int minIdle = 50;

    private int maxIdle = 200;

    private int maxWaitMillis = 3000;

    /**
     * JedisPoolConfig 连接池
     * @return
     */
    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大空闲数
        jedisPoolConfig.setMaxIdle(maxIdle);
        // 连接池的最大数据库连接数
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setTestOnBorrow(false);
        // 逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
        return jedisPoolConfig;
    }

    @Bean
    public RedisClusterConfiguration redisClusterConfiguration(){
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
        //Set<RedisNode> clusterNodes
        String[] serverArray = redisNodes.split(",");

        Set<RedisNode> nodes = new HashSet<RedisNode>();

        for(String ipPort:serverArray){
            String[] ipAndPort = ipPort.split(":");
            nodes.add(new RedisNode(ipAndPort[0].trim(),Integer.valueOf(ipAndPort[1])));
        }

        redisClusterConfiguration.setClusterNodes(nodes);

        return redisClusterConfiguration;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig, RedisClusterConfiguration redisClusterConfiguration){

        log.info("jedisConnectionFactory isJq = {}", isJq);
        log.info("jedisConnectionFactory host2 = {}", host2);
        log.info("jedisConnectionFactory port2 = {}", port2);
        log.info("jedisConnectionFactory password = {}", password);
        log.info("jedisConnectionFactory redisNodes = {}", redisNodes);




        //是否开启集群模式
        if(isJq){
            JedisConnectionFactory JedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration,jedisPoolConfig);
            JedisConnectionFactory.setPassword(password);
            return JedisConnectionFactory;
        }else{
            JedisConnectionFactory JedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig);
            //连接池
            JedisConnectionFactory.setPoolConfig(jedisPoolConfig);
            //IP地址
            JedisConnectionFactory.setHostName(host2);
            //端口号
            JedisConnectionFactory.setPort(port2);
            //如果Redis设置有密码
            JedisConnectionFactory.setPassword(password);
            return JedisConnectionFactory;
        }
    }


//    @Bean
//    public JedisPool redisPoolFactory(){
//        JSONObject node = Config.global.messenger.redisCluster.getJSONObject("node");
//        String password = Config.global.messenger.redisCluster.getString("password");
//        String host = node.getString("ip");
//        Integer port = node.getInteger("port");
//        //调试的时候的配置
//        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
//        //连接池中的最大空闲连接
//        jedisPoolConfig.setMaxTotal(10);
//        jedisPoolConfig.setMinIdle(3);
//        jedisPoolConfig.setMaxIdle(250);
//        jedisPoolConfig.setMinIdle(100);
//        jedisPoolConfig.setMaxWaitMillis(10 * 1000);
//        // 是否启用pool的jmx管理功能, 默认true
//        //jedisPoolConfig.setJmxEnabled(true);
//        JedisPool jedisPool = new JedisPool(jedisPoolConfig,host,port,10000,password);
//        return  jedisPool;
//    }


    @Bean
    public JedisPool redisPoolFactory(){
//        JSONObject node = Config.global.messenger.redisCluster.getJSONObject("node");
//        String password = Config.global.messenger.redisCluster.getString("password");
//        String host = node.getString("ip");
//        Integer port = node.getInteger("port");

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(10);
        jedisPoolConfig.setMinIdle(3);
        jedisPoolConfig.setMaxIdle(250);
        jedisPoolConfig.setMinIdle(100);
        jedisPoolConfig.setMaxWaitMillis(10 * 1000);
        jedisPoolConfig.setTestWhileIdle(true);
        jedisPoolConfig.setMinEvictableIdleTimeMillis(60000);
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30000);
        jedisPoolConfig.setTestOnBorrow(true);
        jedisPoolConfig.setTestOnReturn(true);

        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host2, port2, 10000, password);
        return jedisPool;
    }

    @Bean
    public JedisCluster jedisCluster() {
        Set<HostAndPort> hostAndPorts = new HashSet<HostAndPort>();
        String nodes[] = redisNodes.split(",");
        for(String item : nodes){
            String host = item.split(":")[0];
            Integer port = Integer.valueOf(item.split(":")[1]);
            hostAndPorts.add(new HostAndPort(host,port));
        }

        JedisCluster jedisCluster = null;
        //if (!hostAndPorts.isEmpty() && isJq){
        if (!hostAndPorts.isEmpty() ){
            GenericObjectPoolConfig pool = new GenericObjectPoolConfig();
            pool.setMaxTotal(maxTotal);
            pool.setMinIdle(minIdle);
            pool.setMaxIdle(maxIdle);
            pool.setMaxWaitMillis(maxWaitMillis);
            jedisCluster = new JedisCluster(hostAndPorts, connectionTimeout, soTimeout, maxAttempts, password, pool);
        }
        return jedisCluster;
    }

}
