package com.liquidnet.common.cache.redis.util;

import com.liquidnet.common.cache.redis.config.AbstractRedisConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author AnJiabin <jiabin.an@lightnet.io>
 * @version V1.0
 * @Description: Redis工具类
 * @class: RedisUtil
 * @Package com.liquidnet.stellar.utils
 * @Copyright: LightNet @ Copyright (c) 2020
 * @date 2020/8/26 13:11
 */
public abstract class AbstractRedisUtil {
    /**
     * 补全KEY前缀
     */
    public abstract String fillingKey(String key);

    /**
     * 获取redis初始化信息
     */
    public abstract int getDbs();

    /**
     * 设置redis数据源
     *
     * @return
     */
    abstract AbstractRedisConfig getRedisConfig();

    /**
     * 获取redis队列
     */
    public StringRedisTemplate getStringRedisTemplate() {
        return this.getRedisConfig().getStringRedisTemplate();
    }

    // =============================common============================

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public boolean expireSet(String key, long time) {
        return expire(this.fillingKey(key), time);
    }

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    private boolean expire(String key, long time) {
        if (time > 0) {

            return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).expire(key, time, TimeUnit.SECONDS);

        }
        return false;
    }


    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).getExpire(key, TimeUnit.SECONDS);
    }


    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).hasKey(key);
    }

    /**
     * 根据前缀模糊删除
     *
     * @param prefix Key前缀
     */
    public void delKeysByPrefix(String prefix) {
        prefix = this.fillingKey(prefix);

        if (null != prefix && prefix.trim().length() > 0) {
            for (Integer key : this.getRedisConfig().redisTemplateMap.keySet()) {
                Set<String> keys = this.getRedisConfig().getRedisTemplateByDb(key).keys(prefix.concat("*"));

                if (!CollectionUtils.isEmpty(keys)) {
                    this.getRedisConfig().getRedisTemplateByDb(key).delete(keys);
                }
            }
        }
    }

    /**
     * 删除缓存(多db情况需要单独实现批量删除-该方法慎重使用)
     *
     * @param key 可以传一个值 或多个
     */
    public void del(String... key) {

        if (key != null && key.length > 0) {

            if (key.length == 1) {
                String keyStr = this.fillingKey(key[0]);

                this.getRedisConfig().getRedisTemplateByDb(this.getIndex(keyStr)).delete(keyStr);
            } else {

//                redisTemplate.delete(CollectionUtils.arrayToList(key));
                for (String keyStr : key) {
                    keyStr = this.fillingKey(keyStr);

                    this.getRedisConfig().getRedisTemplateByDb(this.getIndex(keyStr)).delete(keyStr);
                }
            }

        }

    }

    private static final ArrayList<String> STRING_ARRAY_LIST = new ArrayList<>();
    private static final HashMap<Integer, ArrayList<String>> INTEGER_ARRAY_LIST_HASH_MAP = new HashMap();

    public static ArrayList<String> arrayListString() {
        return (ArrayList<String>) STRING_ARRAY_LIST.clone();
    }

    public static HashMap<Integer, ArrayList<String>> hashMapIntegerArrayList() {
        return (HashMap<Integer, ArrayList<String>>) INTEGER_ARRAY_LIST_HASH_MAP.clone();
    }

    public void delList(List<String> key) {
        HashMap<Integer, ArrayList<String>> hashMap;
        if (key != null && key.size() > 0) {
            hashMap = hashMapIntegerArrayList();
            //构建 需要删除的Redis HashMapDBKey
            for (String keyStr : key) {
                keyStr = this.fillingKey(keyStr);
                Integer dbPosition = this.getIndex(keyStr);
                ArrayList<String> dbArray;
                if (hashMap.containsKey(dbPosition)) {
                    dbArray = hashMap.get(dbPosition);
                } else {
                    dbArray = arrayListString();
                }
                dbArray.add(keyStr);
                hashMap.put(dbPosition, dbArray);
            }

            //删除Redis
            for (Integer redisDb : hashMap.keySet()) {
                ArrayList<String> delRedisKeyList = hashMap.get(redisDb);
                this.getRedisConfig().getRedisTemplateByDb(redisDb).delete(delRedisKeyList);
            }
        }
    }

    // ============================String=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */

    public Object get(String key) {
        if (null == key) {
            return null;
        }

        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForValue().get(key);
    }


    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */

    public boolean set(String key, Object value) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForValue().set(key, value);

        return true;
    }


    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */

    public boolean set(String key, Object value, long time) {

        if (time > 0) {
            key = this.fillingKey(key);
            RedisTemplate<String, Object> redisTemplate = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key));
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        } else {

            set(key, value);

        }

        return true;
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta) {

        if (delta < 0) {

            throw new RuntimeException("递增因子必须大于0");

        }

        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForValue().increment(key, delta);
    }


    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     * @return
     */

    public long decr(String key, long delta) {

        if (delta < 0) {

            throw new RuntimeException("递减因子必须大于0");

        }

        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForValue().increment(key, -delta);
    }


    // ================================Map=================================

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().get(key, item);
    }

    public Object hkeys(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().keys(key);
    }


    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */

    public Map<Object, Object> hmget(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().entries(key);
    }


    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */

    public boolean hmset(String key, Map<String, Object> map) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().putAll(key, map);

        return true;
    }


    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */

    public boolean hmset(String key, Map<String, Object> map, long time) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().putAll(key, map);

        if (time > 0) {

            expire(key, time);

        }
        return true;
    }


    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */

    public boolean hset(String key, String item, Object value) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().put(key, item, value);

        return true;
    }


    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */

    public boolean hset(String key, String item, Object value, long time) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().put(key, item, value);

        if (time > 0) {

            expire(key, time);

        }

        return true;
    }


    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */

    public void hdel(String key, Object... item) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().delete(key, item);
    }


    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */

    public boolean hHasKey(String key, String item) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().hasKey(key, item);
    }


    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     * @return
     */

    public double hincr(String key, String item, double by) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().increment(key, item, by);
    }


    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return
     */

    public double hdecr(String key, String item, double by) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().increment(key, item, -by);
    }


    // ============================set=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */

    public Set<Object> sGet(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().members(key);
    }


    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */

    public boolean sHasKey(String key, Object value) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().isMember(key, value);
    }


    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */

    public long sSet(String key, Object... values) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().add(key, values);
    }


    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */

    public long sSetAndTime(String key, long time, Object... values) {
        key = this.fillingKey(key);

        Long count = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().add(key, values);

        if (time > 0)

            expire(key, time);

        return count;
    }


    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return
     */
    public long sGetSetSize(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().size(key);
    }


    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(String key, Object... values) {
        key = this.fillingKey(key);

        Long count = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().remove(key, values);

        return count;
    }

    // ===============================list=================================


    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     * @return
     */

    public List<Object> lGet(String key, long start, long end) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().range(key, start, end);
    }


    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return
     */

    public long lGetListSize(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().size(key);
    }


    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时， 0 表头，1 第二个元素，依次类推；index<0时，-1，表尾，-2倒数第二个元素，依次类推
     * @return
     */

    public Object lGetIndex(String key, long index) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().index(key, index);
    }


    /**
     * 将list放入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean lSet(String key, Object value) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().rightPush(key, value);

        return true;
    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */

    public boolean lSet(String key, Object value, long time) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().rightPush(key, value);

        if (time > 0)

            expire(key, time);

        return true;
    }


    /**
     * 将list放入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().rightPushAll(key, value);

        return true;
    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */

    public boolean lSet(String key, List<Object> value, long time) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().rightPushAll(key, value);

        if (time > 0)

            expire(key, time);

        return true;
    }


    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */

    public boolean lUpdateIndex(String key, long index, Object value) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().set(key, index, value);

        return true;
    }


    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(String key, long count, Object value) {
        key = this.fillingKey(key);

        Long remove = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().remove(key, count, value);

        return remove;
    }

    public RedisTemplate<String, Object> getRedisTemplateByDb(int db) {
        return this.getRedisConfig().getRedisTemplateByDb(db);
    }


    public Object getDB15RedisHGet(String redisKey, String item) {
        redisKey = this.fillingKey(redisKey);

        return this.getRedisConfig().getRedisTemplateByDb(15).opsForHash().get(redisKey, item);
    }

    public Object getDB15RedisGet(String redisKey) {
        redisKey = this.fillingKey(redisKey);

        return this.getRedisConfig().getRedisTemplateByDb(15).opsForValue().get(redisKey);
    }

    public boolean getDB15RedisHasKey(String redisKey, String item) {
        redisKey = this.fillingKey(redisKey);

        return this.getRedisConfig().getRedisTemplateByDb(15).opsForSet().isMember(redisKey, item);
    }

    /**
     * 创建锁
     * @param key         锁的Key
     * @param value       值(随便写毫无意义)
     * @param releaseTime 锁过期时间 防止死锁
     * @return
     */
    public boolean lock(String key, int value, long releaseTime) {
        key = this.fillingKey(key);

        // 尝试获取锁
        RedisTemplate<String, Object> redisTemplate = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key));
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
        // 判断结果
        return boo != null && boo;
    }

    /**
     ** 根据key删除锁
     ** @param key
     */
    public void uLock(String key) {
        key = this.fillingKey(key);
        // 删除key即可释放锁
        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).delete(key);
    }


    public static void main(String[] args) {
        String[] keys = {
                "kylin:order:id:302739831268147207565446"
        };
        for (String key : keys) {
            long value = key.hashCode();
            int idx = ((int) (value ^ (value >>> 32)) % 250);
            System.out.printf("\n[%s] - idx:%s", key, idx);
        }
    }

    private int getIndex(String key) {
        return MathUtil.getIndex(key, this.getRedisConfig().defaultDb, this.getRedisConfig().totalDbs);
    }

}
