package com.xueyi.common.redis.utils;

import com.alibaba.fastjson2.JSONObject;
import com.xueyi.common.core.utils.core.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author yk
 * @description
 * @date 2023-09-21 13:57
 */
public class RedisUtil {

    private static RedisTemplate<String, Serializable> redisTemplate;

    @Autowired
    RedisTemplate<String, Serializable> redisTemplate2;

    @PostConstruct
    public void init() {
        redisTemplate = redisTemplate2;
    }

    public static Integer getNumberVal(String key) {
        return NumberUtil.getNumber((Integer) redisTemplate.opsForValue().get(key));
    }

    public static void expire(String key, int seconds) {
        redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }

    public static List<JSONObject> getJsonList(String key) {
        return redisTemplate.opsForList().range(key, 0, 10).stream().map(json-> JSONObject.parseObject(json.toString())).collect(Collectors.toList());
    }

    public static List<Serializable> getList(String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    public static List<String> getBytesList(String key) {
        List<Serializable> sers = redisTemplate.opsForList().range(key, 0, -1);
        return sers.stream().map(ser-> (String) ser).collect(Collectors.toList());
    }

    public static void setBytesList(String key, byte[] bytes) {
        redisTemplate.opsForList().leftPush(key, bytes);
    }

    public static Long getListCount(String key) {
        return  redisTemplate.opsForList().size(key);
    }

    public static Boolean existed(String key){
        return  redisTemplate.hasKey(key);
    }

    public static void setVal(String key, Serializable value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public static void setVal(String key, Serializable value, int seconds) {
        redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
    }

    public static Serializable getVal(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public static void increment(String key){
        increment(key, 1L);
    }

    public static void increment(String key, long increment){
        redisTemplate
                .opsForValue()
                .increment(key, increment);
    }

    public static void decrement(String key){
        decrement(key, 1L);
    }

    public static void decrement(String key, long decrement){
        redisTemplate
                .opsForValue()
                .decrement(key, decrement);
    }


}
