package com.sunwin.robot2ips.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis 工具类
 * Created by shiwn on 2021/5/11 10:48
 */
@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;

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

    /**
     * @Description: 指定缓存失效时间
     * @Param: [key：键,  expireTime：失效时间（秒）]
     * @Author: shiwn
     * @Date: 2021/5/11 11:29
     */
    public boolean expire(String key, long expireTime) {
        try {
            if (expireTime > 0) {
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 根据key 获取过期时间
     * @Param: [key：键]
     * @Author: shiwn
     * @Return: 时间(秒)，返回0代表为永久有效
     * @Date: 2021/5/11 10:54
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * @Description: 判断key是否存在
     * @Param: [key：键]
     * @Author: shiwn
     * @Date: 2021/5/11 11:31
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 删除缓存
     * @Param: [key：键，可以传一个值或多个]
     * @Author: shiwn
     * @Date: 2021/5/11 11:32
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

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

    /**
     * @Description: 获取缓存值
     * @Param: [key]
     * @Author: shiwn
     * @Date: 2021/5/11 11:38
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * @Description: 写入缓存
     * @Param: [key, value]
     * @Author: shiwn
     * @Date: 2021/5/11 11:38
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 写入缓存，并设置时效时间
     * @Param: [key：键, value：值, expireTime：失效时间（秒）]
     * @Author: shiwn
     * @Date: 2021/5/11 10:52
     */
    public boolean set(final String key, Object value, Long expireTime) {
        try {
            if (expireTime > 0) {
                redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 缓存值递增
     * @Param: [key：键, delta：递增值，要增加几(大于0)]
     * @Author: shiwn
     * @Date: 2021/5/11 11:40
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * @Description: 缓存值递减
     * @Param: [key：键, delta：递增值，要减少几(小于0)]
     * @Author: shiwn
     * @Date: 2021/5/11 11:41
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

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

    /**
     * @Description: HashGet
     * @Param: [key：键（不能为null）, item：项（不能为null）]
     * @Author: shiwn
     * @Date: 2021/5/11 11:43
     */
    public Object hGet(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * @Description: 获取hashKey对应的所有键值
     * @Param: [key：键]
     * @Return 对应的多个键值
     * @Author: shiwn
     * @Date: 2021/5/11 11:44
     */
    public Map<Object, Object> hmGet(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * @Description: HashSet
     * @Param: [key, map]
     * @Author: shiwn
     * @Date: 2021/5/11 11:47
     */
    public boolean hmSet(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: HashSet，并设置失效时间
     * @Param: [key, map, time：失效时间（秒）]
     * @Author: shiwn
     * @Date: 2021/5/11 11:48
     */
    public boolean hmSet(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 向一张hash表中放入数据, 如果不存在将创建
     * @Param: [key：键, item：项, value：值]
     * @Author: shiwn
     * @Date: 2021/5/11 11:49
     */
    public boolean hSet(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 向一张hash表中放入数据, 如果不存在将创建，并设置失效时间。
     * 如果已存在的hash表有失效时间，这里将会替换原有的时间
     * @Param: [key, item, value, time：失效时间（秒）]
     * @Author: shiwn
     * @Date: 2021/5/11 11:50
     */
    public boolean hSet(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 删除hash表中的值
     * @Param: [key：键, item：项（一个或多个，不能为null）]
     * @Author: shiwn
     * @Date: 2021/5/11 11:51
     */
    public void hDel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * @Description: 判断hash表中是否有该项的值
     * @Param: [key：键, item：项]
     * @Author: shiwn
     * @Date: 2021/5/11 11:52
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * @Description: hash递增
     * 如果不存在，就会创建一个 并把新增后的值返回
     * @Param: [key：键, item：项, by：要增加几(大于0)]
     * @Author: shiwn
     * @Date: 2021/5/11 11:52
     */
    public double hIncr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * @Description: hash递减
     * 如果不存在，就会创建一个 并把新增后的值返回
     * @Param: [key：键, item：项, by：要减少记(小于0)]
     * @Author: shiwn
     * @Date: 2021/5/11 11:53
     */
    public double hDecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }


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

    /**
     * @Description: 根据key获取Set中的所有值
     * @Param: [key]
     * @Author: shiwn
     * @Date: 2021/5/11 11:54
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @Description: 根据value从一个set中查询, 是否存在
     * @Param: [key, value]
     * @Author: shiwn
     * @Date: 2021/5/11 11:55
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 将数据放入set缓存
     * @Param: [key, values：值（一个或多个）]
     * @Author: shiwn
     * @Date: 2021/5/11 14:21
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * @Description: 将set数据放入缓存，并设置失效时间
     * @Param: [key, time：失效时间（秒）, values：值（一个或多个）]
     * @Author: shiwn
     * @Date: 2021/5/11 14:21
     */
    public long sSet(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * @Description: 获取set缓存的长度
     * @Param: [key]
     * @Author: shiwn
     * @Date: 2021/5/11 14:22
     */
    public long sGetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * @Description: 移除值为value的
     * @Param: [key, values：值（一个或多个）]
     * @Return 移除的个数
     * @Author: shiwn
     * @Date: 2021/5/11 14:23
     */
    public long sRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


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

    /**
     * @Description: 将list放入缓存
     * @Param: [key, value]
     * @Author: shiwn
     * @Date: 2021/5/11 14:26
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 将list放入缓存
     * @Param: [key, value]
     * @Author: shiwn
     * @Date: 2021/5/11 14:27
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 将list放入缓存，并设置失效时间
     * @Param: [key, value, time：失效时间(秒)]
     * @Author: shiwn
     * @Date: 2021/5/11 14:27
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 将list放入缓存，并设置失效时间
     * @Param: [key, value, time：失效时间(秒]
     * @Author: shiwn
     * @Date: 2021/5/11 14:28
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 获取list缓存的内容
     * start：0，end：-1代表所有值
     * @Param: [key, start：开始索引, end：结束索引]
     * @Author: shiwn
     * @Date: 2021/5/11 14:24
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<? extends Object> lGet(String key) {
        try {
            return redisTemplate.opsForList().range(key, 0, -1);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @Description: 获取list缓存的长度
     * @Param: [key]
     * @Author: shiwn
     * @Date: 2021/5/11 14:25
     */
    public long lGetSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * @Description: 通过索引 获取list中的值
     * @Param: [key, index：索引（index>=0时， 0 表头，1 第二个元素，依次类推；index<0时，-1，表尾，-2倒数第二个元素，依次类推）]
     * @Author: shiwn
     * @Date: 2021/5/11 14:25
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @Description: 根据索引修改list中的某条数据
     * @Param: [key, index：索引, value]
     * @Author: shiwn
     * @Date: 2021/5/11 14:29
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Description: 移除N个值为value的缓存
     * @Param: [key, count：移除数量, value]
     * @Return 移除的个数
     * @Author: shiwn
     * @Date: 2021/5/11 14:29
     */
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
