package org.jeecg.modules.system.service.impl;

import org.jeecg.modules.system.entity.SysDictItem;
import org.jeecg.modules.system.mapper.SysDictItemMapper;
import org.jeecg.modules.system.service.ISysDictItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @Author zhangweijian
 * @since 2018-12-28
 */
@Service
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements ISysDictItemService {

    @Autowired
    private SysDictItemMapper sysDictItemMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<SysDictItem> selectItemsByMainId(String mainId) {
        return sysDictItemMapper.selectItemsByMainId(mainId);
    }

    @Override
    public Map<String,String> selectItemsByDictCode(String dictCode){
        return getDictFromCache(dictCode);
    }

    /**
     * 从 Redis 缓存中获取字典
     */
    private Map<String, String> getDictFromCache(String dictCode) {
        String cacheKey = "dictCacheKey:" + dictCode; // 缓存键
        // 尝试从缓存中获取
        Map<String, String> dictMap = (Map<String, String>) redisTemplate.opsForValue().get(cacheKey);
        if (dictMap != null) {
            return dictMap; // 缓存命中
        }

        // 缓存未命中，从数据库查询并存入缓存
        List<SysDictItem> dictItems = sysDictItemMapper.selectItemsByDictCode(dictCode);
        dictMap = dictItems.stream().collect(Collectors.toMap(SysDictItem::getItemValue,SysDictItem::getItemText));
        redisTemplate.opsForValue().set(cacheKey, dictMap, 12, TimeUnit.HOURS); // 缓存 12 小时
        return dictMap;
    }
}
