package lingtao.net.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil implements ApplicationContextAware {

    private static RedisTemplate redisTemplate;
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
        redisTemplate = (RedisTemplate) applicationContext.getBean("redisTemplate");
    }

    /**
     * 设置缓存
     *
     * @param key   键
     * @param value 值
     */
    public static void set(String key, Object value) {
        if (redisTemplate != null) {
            redisTemplate.opsForValue().set(key, value);
        }
    }

    /**
     * 设置缓存（带过期时间）
     *
     * @param key        键
     * @param value      值
     * @param expireTime 过期时间（秒）
     */
    public static void set(String key, Object value, long expireTime) {
        if (redisTemplate != null) {
            redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS);
        }
    }

    /**
     * 获取缓存
     *
     * @param key 键
     * @return 值
     */
    public static Object get(String key) {
        if (redisTemplate != null) {
            return redisTemplate.opsForValue().get(key);
        }
        return null;
    }

    /**
     * 删除缓存
     *
     * @param key 键
     */
    public static void delete(String key) {
        if (redisTemplate != null) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 检查键是否存在
     *
     * @param key 键
     * @return 是否存在
     */
    public static boolean exists(String key) {
        if (redisTemplate != null) {
            return redisTemplate.hasKey(key);
        }
        return false;
    }

    /**
     * 设置过期时间
     *
     * @param key        键
     * @param expireTime 过期时间（秒）
     * @return 是否成功
     */
    public static boolean expire(String key, long expireTime) {
        if (redisTemplate != null) {
            return redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
        }
        return false;
    }

    /**
     * 获取剩余过期时间
     *
     * @param key 键
     * @return 剩余过期时间（秒）
     */
    public static long getExpire(String key) {
        if (redisTemplate != null) {
            return redisTemplate.getExpire(key, TimeUnit.SECONDS);
        }
        return -1;
    }

}
