package com.ruoyi.common.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.service.ISysDictTypeService;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author fangk
 * @date 2024/4/22
 * @desc DictI18nUtil 字典国际化工具类
 */
public class DictI18nUtil {

    private static final Map<String, Function<SysDictData, String>> I18N_LAN_MAP = new HashMap<String, Function<SysDictData, String>>() {{
        put("zh", SysDictData::getDictLabel);
        put("en", SysDictData::getDictLabelUS);
        put("es", SysDictData::getDictLabelES);
        put("ru", SysDictData::getDictLabelRU);
    }};


    //Locale locale = LocaleContextHolder.getLocale();
    //String language = locale.getLanguage();

    /**
     * 获取当前系统语言的字典标签
     *
     * @param type 字典类型
     * @return map: key: 字典值, value: 字典标签
     */
    public static Map<String, String> getI18nLabel(String type) {
        String language = LocaleContextHolder.getLocale().getLanguage();
        ISysDictTypeService dictTypeService = SpringUtil.getBean("sysDictTypeServiceImpl", ISysDictTypeService.class);
        List<SysDictData> sysDictData = dictTypeService.selectDictDataByType(type);
        return sysDictData.stream().collect(Collectors.toMap(SysDictData::getDictValue, I18N_LAN_MAP.getOrDefault(language, SysDictData::getDictLabel)));
    }

    /**
     * 获取当前系统语言的字典标签
     *
     * @param type  字典类型
     * @param value 字典值
     * @return 字典标签
     */
    public static String getI18nLabel(String type, String value) {
        String language = LocaleContextHolder.getLocale().getLanguage();
        //SpringUtils.getBean("dictTypeService");
        ISysDictTypeService dictTypeService = SpringUtil.getBean("sysDictTypeServiceImpl", ISysDictTypeService.class);
        List<SysDictData> sysDictData = dictTypeService.selectDictDataByType(type);
        return sysDictData.stream().filter(dictData -> dictData.getDictValue().equals(value)).findFirst().map(I18N_LAN_MAP.get(language)).orElse(null);
    }
}