package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.system.domain.SysDictData;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.i18n.LocaleContextHolder;

/**
 * 字典工具类
 *
 * @author ruoyi
 */
public class DictUtils {

    /**
     * 分隔符
     */
    public static final String SEPARATOR = ",";

    private static final Map<String, List<SysDictData>> LOCAL_EXCEL_DICT_CACHE = new ConcurrentHashMap<>();


    /**
     * 设置字典缓存
     *
     * @param key       参数键
     * @param dictDatas 字典数据列表
     */
    public static void setDictCache(String key, List<SysDictData> dictDatas) {
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), dictDatas);
    }

    /**
     * 获取字典缓存
     *
     * @param key 参数键
     * @return dictDatas 字典数据列表
     */
    public static List<SysDictData> getDictCache(String key) {
        JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
        if (StringUtils.isNotNull(arrayCache)) {
            return arrayCache.toList(SysDictData.class);
        }
        return null;
    }

    /**
     * 根据字典类型和字典值获取字典标签
     *
     * @param dictType  字典类型
     * @param dictValue 字典值
     * @return 字典标签
     */
    public static String getDictLabel(String dictType, String dictValue) {
        return getDictLabel(dictType, dictValue, SEPARATOR);
    }

    /**
     * 根据字典类型和字典标签获取字典值
     *
     * @param dictType  字典类型
     * @param dictLabel 字典标签
     * @return 字典值
     */
    public static String getDictValue(String dictType, String dictLabel) {
        return getDictValue(dictType, dictLabel, SEPARATOR);
    }

    /**
     * 根据字典类型和字典值获取字典标签
     *
     * @param dictType  字典类型
     * @param dictValue 字典值
     * @param separator 分隔符
     * @return 字典标签
     */
    public static String getDictLabel(String dictType, String dictValue, String separator) {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictData> datas = getDictCache(dictType);

        if (StringUtils.isNotEmpty(datas)) {
            if (StringUtils.containsAny(separator, dictValue)) {
                for (SysDictData dict : datas) {
                    for (String value : dictValue.split(separator)) {
                        if (value.equals(dict.getDictValue())) {
                            // propertyString.append(dict.getDictLabel()).append(separator);
                            propertyString.append(LocalUtils.localDictLabelFun().apply(dict)).append(separator);
                            break;
                        }
                    }
                }
            } else {
                for (SysDictData dict : datas) {
                    if (Objects.equals(dictValue, dict.getDictValue())) {
                        return LocalUtils.localDictLabelFun().apply(dict);
                    }
                }
            }
        }
        return StringUtils.stripEnd(propertyString.toString(), separator);
    }
    /**
     * 根据字典类型和字典值获取字典标签
     *
     * @param dictType  字典类型
     * @param dictValue 字典值
     * @param separator 分隔符
     * @return 字典标签
     * 
     * TODO LOCAL_EXCEL_DICT_CACHE 缓存 SysDictData 应该可以减少很多缓存很多数据？
     */
    public static String getDictLabelWithCache(String dictType, String dictValue, String separator) {

        if (StringUtils.containsAny(separator, dictValue)) {
            String sepKey = dictType + dictValue + separator;
            if (!LOCAL_EXCEL_DICT_CACHE.containsKey(sepKey)) {
                List<SysDictData> dictList = getDictCache(dictType);
                if (CollectionUtils.isEmpty(dictList)) {
                    return StringUtils.EMPTY;
                }
                // 提前拆分 dictValue 并存入 Set 中
                Set<String> valueSet = new HashSet<>(Arrays.asList(dictValue.split(separator)));

                // 使用 Stream 处理并拼接结果字符串
                List<SysDictData> collect = dictList.stream()
                        .filter(dict -> valueSet.contains(dict.getDictValue()))
                        .collect(Collectors.toList());

                LOCAL_EXCEL_DICT_CACHE.put(sepKey, collect);
            }

            List<SysDictData> collect = LOCAL_EXCEL_DICT_CACHE.get(sepKey);
            if (CollectionUtils.isNotEmpty(collect)) {
                return collect.stream().map(LocalUtils.localDictLabelFun()).collect(Collectors.joining(separator));
            }
           
        } else {
            String key = dictType + dictValue;
            if (!LOCAL_EXCEL_DICT_CACHE.containsKey(key)) {
                List<SysDictData> dictList = getDictCache(dictType);
                if (CollectionUtils.isEmpty(dictList)) {
                    return StringUtils.EMPTY;
                }

                for (SysDictData dict : dictList) {
                    if (dictValue.equals(dict.getDictValue())) {
                        LOCAL_EXCEL_DICT_CACHE.put(key, Collections.singletonList(dict));
                        break;
                    }
                }
            }
            List<SysDictData> collect = LOCAL_EXCEL_DICT_CACHE.get(key);
            if (CollectionUtils.isNotEmpty(collect)) {
                return LocalUtils.localDictLabelFun().apply(collect.get(0));
            }

        }
        return StringUtils.EMPTY;
    }

    /**
     * 根据字典类型和字典标签获取字典值
     *
     * @param dictType  字典类型
     * @param dictLabel 字典标签
     * @param separator 分隔符
     * @return 字典值
     */
    public static String getDictValue(String dictType, String dictLabel, String separator) {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictData> datas = getDictCache(dictType);

        if (StringUtils.containsAny(separator, dictLabel) && StringUtils.isNotEmpty(datas)) {
            for (SysDictData dict : datas) {
                for (String label : dictLabel.split(separator)) {
                    if (label.equals(dict.getDictLabel())) {
                        propertyString.append(dict.getDictValue()).append(separator);
                        break;
                    }
                }
            }
        } else {
            for (SysDictData dict : datas) {
                if (dict.getDictLabel().equals(dictLabel)) {
                    return dict.getDictValue();
                }
            }
        }
        return StringUtils.stripEnd(propertyString.toString(), separator);
    }

    /**
     * 删除指定字典缓存
     *
     * @param key 字典键
     */
    public static void removeDictCache(String key) {
        SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(key));
    }

    /**
     * 清空字典缓存
     */
    public static void clearDictCache() {
        Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(CacheConstants.SYS_DICT_KEY + "*");
        SpringUtils.getBean(RedisCache.class).deleteObject(keys);

        LOCAL_EXCEL_DICT_CACHE.clear();
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getCacheKey(String configKey) {
        return CacheConstants.SYS_DICT_KEY + configKey;
    }

    public static String getInternationalDictLabel(String dictType, String dictValue) {
        if (StringUtils.isAnyBlank(dictValue, dictType)) {
            return "";
        }
        return getInternationalDictLabel(dictType, dictValue, SEPARATOR);
    }

    public static String getInternationalDictLabel(String dictType, String dictValue, String separator) {
        StringBuilder propertyString = new StringBuilder();
        List<SysDictData> datas = getDictCache(dictType);

        if (StringUtils.isNotNull(datas)) {
            if (StringUtils.containsAny(separator, dictValue)) {
                for (SysDictData dict : datas) {
                    for (String value : dictValue.split(separator)) {
                        if (value.equals(dict.getDictValue())) {
                            switch (LocaleContextHolder.getLocale().getCountry()) {
                                case Constants.US:
                                    propertyString.append(dict.getDictLabelUS()).append(separator);
                                    break;
                                case Constants.ES:
                                    propertyString.append(dict.getDictLabelES()).append(separator);
                                    break;
                                case Constants.RU:
                                    propertyString.append(dict.getDictLabelRU()).append(separator);
                                    break;
                                default:
                                    propertyString.append(dict.getDictLabel()).append(separator);
                                    break;
                            }
                        }
                    }
                }
            } else {
                for (SysDictData dict : datas) {
                    if (dict.getDictValue().equals(dictValue)) {
                        switch (LocaleContextHolder.getLocale().getCountry()) {
                            case Constants.US:
                                return dict.getDictLabelUS();
                            case Constants.ES:
                                return dict.getDictLabelES();
                            case Constants.RU:
                                return dict.getDictLabelRU();
                            default:
                                return dict.getDictLabel();
                        }
                    }
                }
            }
        }
        return StringUtils.stripEnd(propertyString.toString(), separator);
    }
}
