package com.bonus.material.utils;

import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;

@Component
public class CacheHelper {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public <T> void putList(String cacheName, String key, List<T> data, Duration ttl) {
        String fullKey = cacheName + "::" + key;
        redisTemplate.opsForValue().set(fullKey, JSONUtil.toJsonStr(data), ttl);
    }

    public <T> List<T> getList(String cacheName, String key, Class<T> clazz) {
        String fullKey = cacheName + "::" + key;
        Object value = redisTemplate.opsForValue().get(fullKey);
        if (value == null) return Collections.emptyList();

        // 保证无论是字符串还是对象都能转回来
        String json = (value instanceof String) ? (String) value : JSONUtil.toJsonStr(value);
        return JSONUtil.toList(json, clazz);
    }

    /**
     * 获取单对象
     */
    public <T> T getBean(String cacheName, String key, Class<T> clazz) {
        String fullKey = cacheName + "::" + key;
        Object value = redisTemplate.opsForValue().get(fullKey);
        if (value == null) {
            return null;
        }
        String json = (value instanceof String) ? (String) value : JSONUtil.toJsonStr(value);
        return JSONUtil.toBean(json, clazz);
    }

    /**
     * 写入缓存
     */
    public void put(String cacheName, String key, Object data, Duration ttl) {
        String fullKey = cacheName + "::" + key;
        redisTemplate.opsForValue().set(fullKey, JSONUtil.toJsonStr(data), ttl);
    }

    /**
     * 删除缓存
     */
    public void del(String cacheName, String key) {
        redisTemplate.delete(cacheName + "::" + key);
    }
}
