package com.ruoyi.framework.config;

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.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;

/**
 * redis配置
 * 
 * @author ruoyi
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{
    @Value("${spring.redis.keyPrefix}")
    private String keyPrefix;

    @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);

        Supplier<RedisSerializer<?>> keySerializer = () -> {
            return new PrefixStringRedisSerializer(keyPrefix);
            //return new StringRedisSerializer();
        };
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(keySerializer.get());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(keySerializer.get());
        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);";
    }

    @Component
    public static class PrefixStringRedisSerializer extends StringRedisSerializer
    {
        private final String keyPrefix;
        private final Charset charset;

        public PrefixStringRedisSerializer() {
            this(StandardCharsets.UTF_8);
        }

        public PrefixStringRedisSerializer(Charset charset) {
            Assert.notNull(charset, "Charset must not be null!");
            this.charset = charset;
            keyPrefix = null;
        }

        public PrefixStringRedisSerializer(String keyPrefix) {
            this(keyPrefix, StandardCharsets.UTF_8);
        }

        public PrefixStringRedisSerializer(String keyPrefix, Charset charset) {
            Assert.notNull(charset, "Charset must not be null!");
            this.charset = charset;
            this.keyPrefix = keyPrefix;
        }

        private boolean keyPrefixEnabled()
        {
            return null != keyPrefix && !keyPrefix.isEmpty();
        }

        public String deserialize(@Nullable byte[] bytes) {
            if(null == bytes)
                return null;
            String key = new String(bytes, this.charset);
            if(keyPrefixEnabled())
            {
                Assert.isTrue(key.startsWith(keyPrefix), "Redis key must start with '" + keyPrefix + "'!");
                return key.substring(keyPrefix.length());
            }
            else
                return key;
        }

        public byte[] serialize(@Nullable String string) {
            if(null == string)
                return null;
            if(keyPrefixEnabled())
                string = keyPrefix + ':' + string;
            return string.getBytes(this.charset);
        }
    }
}
