package com.ssj.framework.core.util;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;


@Configuration
@EnableCaching
public class CachingConfig extends CachingConfigurerSupport {

    //学校版本key
    private static final String  keyCode_Banben="CACH_SERVICE:Banben:";

    //练习册key
    private static final String  keyCode_ExerciseBook="CACH_SERVICE:ExerciseBook:";

    //科目版本
    private static final String  keyCode_SubjectVersions="CACH_SERVICE:SubjectVersion:";

    //答案
    private static final String  keyCode_ExerciseQuestion="CACH_SERVICE:ExerciseQuestion:";

    //当前学期
    private static final String  keyCode_ConfigSemester="CACH_SERVICE:ConfigSemester:";


    //学生服务
    private static final String  keyCode_ChildDerverService="CACH_SERVICE:ChildDerverService:";
    private static final String  keyCode_ChildServiceList="CACH_SERVICE:ChildServiceList:";




    /*
     *  自定义缓存数据 key 生成策略的bean 包名+类名+方法名+所有参数
     */
    @Bean
    public KeyGenerator keyGenerator_Banben() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method,
                                   Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(keyCode_Banben);
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj!=null ? obj.toString() : "null" );
                }
                return sb.toString();
            }
        };
    }


    @Bean
    public KeyGenerator keyGenerator_getChildDerverService() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method,
                                   Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(keyCode_ChildDerverService);
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj!=null ? obj.toString() : "null" );
                }
                return sb.toString();
            }
        };
    }
    @Bean
    public KeyGenerator keyGenerator_getChildServiceList() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method,
                                   Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(keyCode_ChildServiceList);
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj!=null ? obj.toString() : "null" );
                }
                return sb.toString();
            }
        };
    }

    @Bean
    public KeyGenerator keyGenerator_ExerciseBook() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method,
                                   Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(keyCode_ExerciseBook);
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj!=null ? obj.toString() : "null" );
                }
                return sb.toString();
            }
        };
    }


    @Bean
    public KeyGenerator keyGenerator_SubjectVersions() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method,
                                   Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(keyCode_SubjectVersions);
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj!=null ? obj.toString() : "null" );
                }
                return sb.toString();
            }
        };
    }


    @Bean
    public KeyGenerator keyGenerator_ExerciseQuestion() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method,
                                   Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(keyCode_ExerciseQuestion);
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj!=null ? obj.toString() : "null" );
                }
                return sb.toString();
            }
        };
    }


    @Bean
    public KeyGenerator keyGenerator_keyCode_ConfigSemester() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method,
                                   Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(keyCode_ConfigSemester);
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj!=null ? obj.toString() : "null" );
                }
                return sb.toString();
            }
        };
    }







    @Bean
    @Primary
    public CacheManager cacheManager(
            @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        RedisCacheManager rm = new RedisCacheManager(redisTemplate);
        //设置默认的一个小时的过期时间(以秒为单位)
        rm.setDefaultExpiration(2*3600);
        //Map<String, Long> expMap=new HashMap<String,Long>();
        //rm.setExpires(expMap);//设置缓存区域(按key)的过期时间(以秒为单位)
        return rm;
    }

    @Bean
    public CacheManager cacheServiceManager(
            @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        RedisCacheManager rm = new RedisCacheManager(redisTemplate);
        //设置默认的6个小时的过期时间(以秒为单位)
        //rm.setDefaultExpiration(6*3600);

        //设置当天0点过期
        LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight);
        rm.setDefaultExpiration(seconds);

        //Map<String, Long> expMap=new HashMap<String,Long>();
        //rm.setExpires(expMap);//设置缓存区域(按key)的过期时间(以秒为单位)
        return rm;
    }




    //1.项目启动时此方法先被注册成bean被spring管理,如果没有这个bean，则redis可视化工具中的中文内容（key或者value）都会以二进制存储，不易检查。
    @Bean
    public RedisTemplate<String, String> redisTemplate(
            RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        @SuppressWarnings({ "rawtypes", "unchecked" })
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(
                Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}
