package com.yunfeiyun.agmp.common.framework.manager;

import com.yunfeiyun.agmp.common.enums.RedisCacheKey;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class RedisCacheManager {
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param redisCacheKeyType 缓存的键类型
     * @param keyId             缓存的key标识
     * @param redisCacheKeyType             缓存的值
     */
    public <T> void setCacheObject(RedisCacheKey redisCacheKeyType, String keyId, T value) {
        redisTemplate.opsForValue().set(redisCacheKeyType.formatter(keyId), value);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param redisCacheKeyType      缓存的键类型
     * @param keyId             缓存的key标识
     * @param redisCacheKeyType    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(RedisCacheKey redisCacheKeyType, String keyId, T value, long timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(redisCacheKeyType.formatter(keyId), value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识                             
     * @param timeout 超时时间
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(RedisCacheKey redisCacheKeyType, String keyId, long timeout) {
        return expire(redisCacheKeyType, keyId, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param redisCacheKeyType   缓存的键类型
     * @param keyId             缓存的key标识
     * @param timeout 超时时间
     * @param unit    时间单位
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(RedisCacheKey redisCacheKeyType, String keyId, long timeout, TimeUnit unit) {
        return redisTemplate.expire(redisCacheKeyType.formatter(keyId), timeout, unit);
    }

    /**
     * 获取有效时间
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     * @return 有效时间
     */
    public long getExpire(RedisCacheKey redisCacheKeyType, String keyId) {
        return redisTemplate.getExpire(redisCacheKeyType.formatter(keyId));
    }

    /**
     * 判断 key是否存在
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     * @return true 存在 false不存在
     */
    public Boolean hasKey(RedisCacheKey redisCacheKeyType, String keyId) {
        return redisTemplate.hasKey(redisCacheKeyType.formatter(keyId));
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(RedisCacheKey redisCacheKeyType, String keyId) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(redisCacheKeyType.formatter(keyId));
    }

    /**
     * 删除单个对象
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     */
    public boolean deleteObject(RedisCacheKey redisCacheKeyType, String keyId) {
        return redisTemplate.delete(redisCacheKeyType.formatter(keyId));
    }

    /**
     * 删除集合对象
     *
     * @param redisCacheKeyListMap 多个对象
     * @return
     */
    public boolean deleteObject(Map<RedisCacheKey, Collection<String>> redisCacheKeyListMap) {
        List<String> keys = new ArrayList<>();
        for (RedisCacheKey redisCacheKeyType : redisCacheKeyListMap.keySet()) {
            Collection<String> redisKeys = redisCacheKeyListMap.get(redisCacheKeyType);
            keys.addAll(redisKeys.stream().map(redisCacheKeyType::formatter).collect(Collectors.toList()));
        }
        return redisTemplate.delete(keys) > 0;
    }

    /**
     * 删除集合对象
     *
     * @param redisCacheKeyListMap 多个对象
     * @return
     */
    public boolean deleteObject(Collection<String> redisCacheKeyListMap) {
        List<String> keys = new ArrayList<>();
        keys.addAll(redisCacheKeyListMap.stream().collect(Collectors.toList()));
        return redisTemplate.delete(keys) > 0;
    }

    /**`
     * 缓存List数据
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     * @param dataList          待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(RedisCacheKey redisCacheKeyType, String keyId, List<T> dataList) {
        Long count = redisTemplate.opsForList().rightPushAll(redisCacheKeyType.formatter(keyId), dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(RedisCacheKey redisCacheKeyType, String keyId) {
        return redisTemplate.opsForList().range(redisCacheKeyType.formatter(keyId), 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(RedisCacheKey redisCacheKeyType, String keyId, Set<T> dataSet) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(redisCacheKeyType.formatter(keyId));
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext()) {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     */
    public <T> Set<T> getCacheSet(RedisCacheKey redisCacheKeyType, String keyId) {
        return redisTemplate.opsForSet().members(redisCacheKeyType.formatter(keyId));
    }

    /**
     * 缓存Map
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     */
    public <T> void setCacheMap(RedisCacheKey redisCacheKeyType, String keyId, Map<String, T> dataMap) {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(redisCacheKeyType.formatter(keyId), dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     * @return
     */
    public <T> Map<String, T> getCacheMap(RedisCacheKey redisCacheKeyType, String keyId) {
        return redisTemplate.opsForHash().entries(redisCacheKeyType.formatter(keyId));
    }

    /**
     * 往Hash中存入数据
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     * @param hKey  Hash键
     * @param value 数据
     */
    public <T> void setCacheMapValue(RedisCacheKey redisCacheKeyType, String keyId, String hKey, T value) {
        redisTemplate.opsForHash().put(redisCacheKeyType.formatter(keyId), hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(RedisCacheKey redisCacheKeyType, String keyId, String hKey) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(redisCacheKeyType.formatter(keyId), hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(RedisCacheKey redisCacheKeyType, String keyId, Collection<Object> hKeys) {
        return redisTemplate.opsForHash().multiGet(redisCacheKeyType.formatter(keyId), hKeys);
    }

    /**
     * 删除Hash中的某条数据
     *
     * @param redisCacheKeyType     缓存的键类型
     * @param keyId             缓存的key标识
     * @param hKey Hash键
     * @return 是否成功
     */
    public boolean deleteCacheMapValue(RedisCacheKey redisCacheKeyType, String keyId, String hKey) {
        return redisTemplate.opsForHash().delete(redisCacheKeyType.formatter(keyId), hKey) > 0;
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    public Long increment(RedisCacheKey redisCacheKey,String keyId){
       return redisTemplate.opsForValue().increment(redisCacheKey.formatter(keyId));
    }

    public <T> Boolean setIfAbsent(RedisCacheKey redisCacheKey, String keyId, T value, Duration timeout){
        return redisTemplate.opsForValue().setIfAbsent(redisCacheKey.formatter(keyId),value,timeout);
    }


    public  <T> Object execute(RedisScript<T> script, Map<RedisCacheKey, Collection<String>> redisCacheKeyListMap, Object... args){
        List<String> keys = new ArrayList<>();
        for (RedisCacheKey redisCacheKeyType : redisCacheKeyListMap.keySet()) {
            Collection<String> redisKeys = redisCacheKeyListMap.get(redisCacheKeyType);
            keys.addAll(redisKeys.stream().map(redisCacheKeyType::formatter).collect(Collectors.toList()));
        }
        return redisTemplate.execute(script,keys,args);
    }
}
