import i18n from "@/locales/index";
import config from "@/config";
import tools from "@/utils/tools";
import api from "@/api";
import {LANGUAGE_MAP} from "@/locales/languages";

export async function setupI18n(locale: string = null) {
	locale = locale || tools.data.get("APP_LANG") || config.LANG;
	const langConfig = LANGUAGE_MAP[locale];
	// 先从缓存中取
	var messages = tools.data.get("LOCALE:" + locale)
	if (!messages) {
		const res = await api.system.translation.load({locale});
		messages = tools.deepMerge(langConfig.el, langConfig.local, res['data'] || {})
		tools.data.set("LOCALE:" + locale, messages, 86400)
	}
	// 设置语言包内容
	i18n.global.setLocaleMessage(locale, messages);
	// 切换语言
	i18n.global.locale.value = locale;
	return i18n;
}
