package cd.casic.module.terminal.dal.redis;

import cn.orionsec.kit.lang.define.cache.key.CacheKeyDefine;
import cn.orionsec.kit.lang.utils.Strings;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

/**
 * @author: Paul
 * @create: 2025-07-10 15:31
 */
@Repository
public class TerminalRedisDAO {


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取 json
     *
     * @param key    key
     * @param define define
     * @param <T>    T
     * @return T
     */
    public <T> T getJson(String key, CacheKeyDefine define) {
        return (T) getJson(key, define.getType());
    }

    /**
     * 获取 json
     *
     * @param key  key
     * @param type type
     * @param <T>  T
     * @return T
     */
    public <T> T getJson(String key, Class<T> type) {
        String value = redisTemplate.opsForValue().get(key);
        if (value == null) {
            return null;
        }
        return (T) JSON.parseObject(value, type);
    }


    /**
     * 设置值
     *
     * @param define define
     * @param value  value
     */
    public void set(CacheKeyDefine define, Object value) {
        set(define.getKey(), define, value);
    }

    /**
     * 设置值
     *
     * @param key    key
     * @param define define
     * @param value  value
     */
    public void set(String key, CacheKeyDefine define, Object value) {
        if (value == null) {
            value = Strings.EMPTY;
        }
        if (define == null || define.getTimeout() == 0) {
            // 不过期
            redisTemplate.opsForValue().set(key, value.toString());
        } else {
            // 过期
            redisTemplate.opsForValue().set(key, value.toString(),
                    define.getTimeout(),
                    define.getUnit());

        }
    }

    /**
     * 设置 json
     *
     * @param key    key
     * @param define define
     * @param value  value
     */
    public void setJson(String key, CacheKeyDefine define, Object value) {
        if (define == null || define.getTimeout() == 0) {
            // 不过期
            redisTemplate.opsForValue().set(key, JSON.toJSONString(value));
        } else {
            // 过期
            redisTemplate.opsForValue().set(key, JSON.toJSONString(value),
                    define.getTimeout(),
                    define.getUnit());
        }
    }

    /**
     * 删除 key
     *
     * @param key key
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }

}
