import { createI18n } from 'vue-i18n';
import pinia from '/@/stores/index';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { info } from '/@/api/admin/i18n';

// element plus 自带国际化
import enLocale from 'element-plus/es/locale/lang/en';
import zhcnLocale from 'element-plus/es/locale/lang/zh-cn';

import zhCN from './zh-CN/index.json';
import enUS from './en-US/index.json';

// 语言代码映射（兼容旧格式）
const localeMap: Record<string, 'zh-CN' | 'en-US'> = {
	'zh-cn': 'zh-CN',
	'zh-CN': 'zh-CN',
	en: 'en-US',
	'en-US': 'en-US',
};

const messages = {
	'zh-CN': {
		name: 'zh-CN',
		el: zhcnLocale.el,
		...zhCN,
	},
	'en-US': {
		name: 'en-US',
		el: enLocale.el,
		...enUS,
	},
};

// 读取 pinia 默认语言
const stores = useThemeConfig(pinia);
const { themeConfig } = storeToRefs(stores);

// 获取并标准化语言代码
const getLocale = (locale: string): 'zh-CN' | 'en-US' => localeMap[locale] || 'zh-CN';
const defaultLocale = getLocale(localStorage.getItem('locale') || themeConfig.value.globalI18n || 'zh-CN');

// 导出语言国际化
export const i18n = createI18n({
	legacy: false,
	silentTranslationWarn: true,
	missingWarn: false,
	silentFallbackWarn: true,
	fallbackWarn: false,
	locale: defaultLocale,
	fallbackLocale: 'zh-CN',
	messages,
	globalInjection: true,
});

// 初始化时设置 data-locale 属性
if (typeof document !== 'undefined') {
	document.querySelector('html')?.setAttribute('lang', defaultLocale);
	document.querySelector('html')?.setAttribute('data-locale', defaultLocale);
}

await fetchI18n();

// 远程获取i18n
async function fetchI18n() {
	const infoI18n = await info();
	const messageLocal: Record<string, any> = {};
	const itemizeLocal: Record<string, any[]> = { 'en-US': [], 'zh-CN': [] };
	itemizeLocal['zh-CN'].push(...(infoI18n.data.data['zh-cn'] || []));
	itemizeLocal['en-US'].push(...(infoI18n.data.data.en || []));

	for (const key in itemizeLocal) {
		messageLocal[key] = {
			name: key,
			...mergeArrObj(itemizeLocal, key),
		};
	}

	i18n.global.mergeLocaleMessage('zh-CN', messageLocal['zh-CN']);
	i18n.global.mergeLocaleMessage('en-US', messageLocal['en-US']);
	i18n.global.locale.value = getLocale(themeConfig.value.globalI18n);
}

// 合并数组对象
function mergeArrObj<T extends Record<string, any[]>>(list: T, key: string) {
	let obj: Record<string, any> = {};
	list[key].forEach((i: Record<string, any>) => {
		obj = Object.assign({}, obj, i);
	});
	return obj;
}

export default i18n;

// 导出语言代码映射函数
export { getLocale };

// 导出语言切换函数
export function setLanguage(locale: string) {
	const normalizedLocale = getLocale(locale);
	i18n.global.locale.value = normalizedLocale;
	localStorage.setItem('locale', normalizedLocale);
	document.querySelector('html')?.setAttribute('lang', normalizedLocale);
	// 设置 data-locale 属性用于样式适配
	document.querySelector('html')?.setAttribute('data-locale', normalizedLocale);
}

// 导出当前语言
export function getCurrentLanguage() {
	return i18n.global.locale.value;
}
