package com.zcxk.dict;

import com.zcxk.client.UserCenterClient;
import com.zcxk.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class DictUtil {

    private static final String REDIS_CACHE_KEY_DICTINFO = "dict%s";

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserCenterClient userCenterClient;

    public String getDictName(String code,Integer value) {
        String key = String.format(REDIS_CACHE_KEY_DICTINFO, code);
        String keysValue = (String) redisUtil.getHashValues(key,value+"");
        if (keysValue == null) {
            Map<String,String> keysValues = updateDictInfo(key,code);
            keysValue = keysValues.get(value+"");
        }
        return keysValue;
    };

    private Map<String,String> updateDictInfo(String key,String code) {
        Map<String, String> keysValues = new HashMap<>();
        Dict dict = new Dict();
        dict.setParentDictCode(code);
        List<Dict> dicts = userCenterClient.selectDictList(dict).getData();
        for (Dict item : dicts) {
            keysValues.put(item.getDictCode() + "", item.getDictValue());
        }
        redisUtil.putHashValues(key, keysValues);
        return keysValues;
    }
}
