package com.artfess.base.util;

import com.alibaba.fastjson.JSON;
import com.artfess.base.cache.CacheManager;
import com.artfess.base.cache.ICache;
import com.artfess.base.cache.setting.CacheSetting;
import com.artfess.base.constants.CacheKeyConst;
import com.artfess.base.vo.DictionaryDetailVo;
import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author : min.wu
 * @Date: 2024/11/06 15:52
 */
public class DictionaryUtils {

    private static final CacheSetting cacheSetting = CacheSetting.buildDefault("字典缓存");

    public static DictionaryDetailVo getDictInfo(String dictKey, String dictName) {
        if(!StringUtils.isNotEmpty(dictName)) {
            return new DictionaryDetailVo();
        }
        //获取字典服务类
        CacheManager cacheManager = AppUtil.getBean(CacheManager.class);
        ICache cache = cacheManager.getCache("", cacheSetting);
        String key = CacheKeyConst.SYS_DICTIONARY_KEY + ":" + dictKey.toUpperCase() + ":";
        Object o = cache.get(key);
        if (null == o) {
            return new DictionaryDetailVo();
        }

        //将excel中name转换成 字典中的value
        List<DictionaryDetailVo> dictionaryDetails = JSON.parseArray(o.toString(), DictionaryDetailVo.class);
        AtomicReference<DictionaryDetailVo> value = new AtomicReference<>();
        dictionaryDetails.forEach(dictionaryDetail -> {
            String name = dictionaryDetail.getName();
            if (dictName.equals(name)) {
                value.set(dictionaryDetail);
                return;
            }
        });
        return value.get();
    }

    public static DictionaryDetailVo findByDictValue(String dictKey, String dictValue) {
        if(!StringUtils.isNotEmpty(dictValue)) {
            return new DictionaryDetailVo();
        }
        //获取字典服务类
        CacheManager cacheManager = AppUtil.getBean(CacheManager.class);
        ICache cache = cacheManager.getCache("", cacheSetting);
        String key = CacheKeyConst.SYS_DICTIONARY_KEY + ":" + dictKey.toUpperCase() + ":";
        Object o = cache.get(key);
        if (null == o) {
            return new DictionaryDetailVo();
        }

        //将excel中name转换成 字典中的value
        List<DictionaryDetailVo> dictionaryDetails = JSON.parseArray(o.toString(), DictionaryDetailVo.class);
        AtomicReference<DictionaryDetailVo> value = new AtomicReference<>();
        dictionaryDetails.forEach(dictionaryDetail -> {
            String dictionaryDetailValue = dictionaryDetail.getValue();
            if (dictValue.equals(dictionaryDetailValue)) {
                value.set(dictionaryDetail);
                return;
            }
        });
        return value.get();
    }
}
