package com.usky.common.security.utils;

import com.usky.common.core.constants.Constants;
import com.usky.common.core.util.SpringContextUtils;
import com.usky.common.core.util.StringUtils;
import com.usky.common.redis.core.RedisHelper;
import com.usky.system.domain.SysDictDataVO;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 字典工具类
 * 
 * @author ruoyi
 */
public class DictUtils
{
    /**
     * 设置字典缓存
     * 
     * @param key 参数键
     * @param dictDatas 字典数据列表
     */
    public static void setDictCache(String key, List<SysDictDataVO> dictDatas)
    {
        SpringContextUtils.getBean(RedisHelper.class).set(getCacheKey(key), dictDatas);
    }

    /**
     * 获取字典缓存
     * 
     * @param key 参数键
     * @return dictDatas 字典数据列表
     */
    public static List<SysDictDataVO> getDictCache(String key)
    {
        Object cacheObj = SpringContextUtils.getBean(RedisHelper.class).get(getCacheKey(key));
        if (Objects.nonNull(cacheObj))
        {
            return StringUtils.cast(cacheObj);
        }
        return null;
    }

    /**
     * 删除指定字典缓存
     * 
     * @param key 字典键
     */
    public static void removeDictCache(String key)
    {
        SpringContextUtils.getBean(RedisHelper.class).delete(getCacheKey(key));
    }

    /**
     * 清空字典缓存
     */
    public static void clearDictCache()
    {
        Collection<String> keys = SpringContextUtils.getBean(RedisHelper.class).keys(Constants.SYS_DICT_KEY + "*");
        SpringContextUtils.getBean(RedisHelper.class).delete(keys);
    }

    /**
     * 设置cache key
     * 
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getCacheKey(String configKey)
    {
        return Constants.SYS_DICT_KEY + configKey;
    }
}
