import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.ccp.admin.common.mapper.CodeDictMapper;
import com.ccp.common.component.BeanContext;
import com.ccp.common.entity.common.CodeDict;
import com.ccp.common.redis.RedisUtil;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class DictUtils {
private static CodeDictMapper dictDao = BeanContext.getBean(CodeDictMapper.class);
private static RedisUtil redisUtil = (RedisUtil) BeanContext.getBean("redisUtil");
public static final String CACHE_DICT_MAP = "dictMap";
public static String getDictLabel(Integer value, String type, String defaultValue){
if (value != null){
for (CodeDict dict : getDictList(type)){
if (type.equals(dict.getDictType()) && value.equals(dict.getDictCode())){
return dict.getDictName();
}
}
}
return defaultValue;
}
public static String getDictLabels(String values, String type, String defaultValue){
if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(values)){
List<String> valueList = Lists.newArrayList();
for (String value : StringUtils.split(values, ",")){
valueList.add(getDictLabel(Integer.valueOf(value), type, defaultValue));
}
return StringUtils.join(valueList, ",");
}
return defaultValue;
}
public static String getDictValue(String label, String type, String defaultLabel){
if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)){
for (CodeDict dict : getDictList(type)){
if (type.equals(dict.getDictType()) && label.equals(dict.getDictCode())){
return dict.getDictName();
}
}
}
return defaultLabel;
}
public static List<CodeDict> getDictList(String type){
@SuppressWarnings("unchecked")
Map<String, List<CodeDict>> dictMap = (Map<String, List<CodeDict>>) redisUtil.get(CACHE_DICT_MAP);
if (dictMap==null||dictMap.isEmpty()){
dictMap = Maps.newHashMap();
for (CodeDict dict : dictDao.findAllList()){
List<CodeDict> dictList = dictMap.get(dict.getDictType());
if (dictList != null){
dictList.add(dict);
}else{
dictMap.put(dict.getDictType(), Lists.newArrayList(dict));
}
}
redisUtil.set(CACHE_DICT_MAP, dictMap);
}
List<CodeDict> dictList = dictMap.get(type);
if (dictList == null){
dictList = Lists.newArrayList();
}
return dictList;
}
/**
* 返回字典列表(JSON)
* @param type
* @return
*/
public static String getDictListJson(String type){
return JSON.toJSONString(getDictList(type));
}
}