package com.td.boss.common.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.td.boss.common.pojo.ComConfig;
import com.td.boss.common.repository.ComConfigRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ComConfigServiceImpl implements ComConfigService {

    private String redisKey = "data:com:config";
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ComConfigRepository repository;

    private List<ComConfig> list() {
        List<ComConfig> list = null;
        String s = redisTemplate.opsForValue().get(redisKey);
        if (StrUtil.isBlank(s)) {
            list = repository.list();
            redisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(list));
        } else {
            list = JSONUtil.toList(s, ComConfig.class);
        }
        return list;
    }

    @Override
    public String selectByKey(String key) {
        List<ComConfig> list = list();
        return list.stream().filter(a -> a.getConfigKey().equals(key)).map(a -> a.getConfigValue()).findFirst().orElse("");
    }
}
