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 com.td.boss.game.complayersattri.vo.ComPlayersLuckyLandLevelUpVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
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;
        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("");
    }

    /**
     * 获取种植土地级别配置
     *
     * @return
     */
    @Override
    public List<ComPlayersLuckyLandLevelUpVo> selectLandLevel() {
        String land_tools = selectByKey("land_level");
        if (StrUtil.isBlank(land_tools)) {
            return new ArrayList<>();
        } else {
            return JSONUtil.toList(land_tools, ComPlayersLuckyLandLevelUpVo.class);
        }
    }

    @Override
    public <T> List<T> selectByKey(String key, Class<T> clazz) {
        String json = selectByKey(key);
        if (StrUtil.isBlank(json)) {
            return new ArrayList<>();
        } else {
            return JSONUtil.toList(json, clazz);
        }
    }
}
