288 lines
8.2 KiB
TypeScript
288 lines
8.2 KiB
TypeScript
import { createI18n } from 'vue-i18n'
|
|
import Cookies from 'js-cookie'
|
|
import elementEnLocale from 'element-plus/es/locale/lang/en'
|
|
import elementZhLocale from 'element-plus/es/locale/lang/zh-cn'
|
|
import localEnUS from './en-US.ts'
|
|
import localZhCN from './zh-CN.ts'
|
|
import * as indexApi from '@/api/index/index'
|
|
|
|
// ==================== 配置 ====================
|
|
const CONFIG = {
|
|
API_BASE: import.meta.env.VITE_APP_BASE_API || '/api',
|
|
PROJECT: import.meta.env.VITE_APP_PROJECT_NAME || 'vue-admin',
|
|
AUTO_REPORT: true, // 是否自动上报新键值
|
|
REPORT_DELAY: 3000, // 上报延迟(毫秒)
|
|
CACHE_KEY: 'i18n_collected_keys' // 本地缓存键名
|
|
}
|
|
|
|
/** 合并服务端语言包后仍强制使用前端的菜单译名(避免后台词条未同步时被覆盖) */
|
|
const FORCE_MENU_LABELS: Record<string, Record<string, string>> = {
|
|
'zh-CN': { basicManagement: '仓库设置' },
|
|
en: { basicManagement: 'Warehouse Settings' }
|
|
}
|
|
|
|
// ==================== 状态管理 ====================
|
|
const state = {
|
|
serverMessages: {} as Record<string, any>, // 服务器加载的翻译
|
|
collectedKeys: new Set<string>(), // 已采集的键值
|
|
pendingKeys: new Map<string, any>(), // 待上报的键值
|
|
isReporting: false, // 是否正在上报
|
|
isLoaded: false // 服务器翻译是否已加载
|
|
}
|
|
|
|
const messages = {
|
|
'en': {
|
|
...localEnUS,
|
|
...elementEnLocale
|
|
},
|
|
'zh-CN': {
|
|
...localZhCN,
|
|
...elementZhLocale
|
|
}
|
|
}
|
|
|
|
export function getLanguage() {
|
|
const chooseLanguage = Cookies.get('language')
|
|
if (chooseLanguage) return chooseLanguage
|
|
|
|
const language = (navigator.language || (navigator.languages && navigator.languages[0]) || 'zh-CN').toLowerCase()
|
|
const locales = Object.keys(messages)
|
|
for (const locale of locales) {
|
|
if (language.indexOf(locale.toLowerCase()) > -1) {
|
|
return locale
|
|
}
|
|
}
|
|
return 'zh-CN'
|
|
}
|
|
|
|
// ==================== 核心函数 ====================
|
|
|
|
/**
|
|
* 4. 加载本地缓存的键值
|
|
*/
|
|
function loadCollectedKeys() {
|
|
try {
|
|
const saved = localStorage.getItem(CONFIG.CACHE_KEY)
|
|
if (saved) {
|
|
state.collectedKeys = new Set(JSON.parse(saved))
|
|
// console.log(`📦 加载 ${state.collectedKeys.size} 个已采集键值`)
|
|
}
|
|
} catch (e) {
|
|
console.warn('加载缓存键值失败:', e)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 5. 保存到本地缓存
|
|
*/
|
|
function saveCollectedKeys() {
|
|
try {
|
|
localStorage.setItem(
|
|
CONFIG.CACHE_KEY,
|
|
JSON.stringify(Array.from(state.collectedKeys))
|
|
)
|
|
} catch (e) {
|
|
console.warn('保存缓存键值失败:', e)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 7. 获取调用上下文(帮助定位键值位置)
|
|
*/
|
|
function getCallContext() {
|
|
try {
|
|
const stack = new Error().stack
|
|
// @ts-ignore
|
|
const lines = stack.split('\n').slice(3, 6) // 获取调用堆栈
|
|
|
|
return {
|
|
stack: lines.join('\n'),
|
|
url: window.location.href,
|
|
userAgent: navigator.userAgent,
|
|
timestamp: new Date().toISOString()
|
|
}
|
|
} catch {
|
|
return {}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 9. 上报键值到服务器
|
|
*/
|
|
async function reportKeysToServer() {
|
|
if (state.isReporting || state.pendingKeys.size === 0) return
|
|
|
|
state.isReporting = true
|
|
const keysToReport = Array.from(state.pendingKeys.values())
|
|
|
|
try {
|
|
console.log(`📤 上报 ${keysToReport.length} 个新键值到服务器...`)
|
|
// @ts-ignore
|
|
const response = await indexApi.putI18nCollect({
|
|
project: 'wms',
|
|
locale: i18n.global.locale.value,
|
|
keys: keysToReport,
|
|
source: 'frontend-auto-collect'
|
|
});
|
|
|
|
if (response.data && response.data.success) {
|
|
// 清空已上报的
|
|
keysToReport.forEach(item => state.pendingKeys.delete(item.key))
|
|
console.log(`✅ 上报成功,服务器已处理 ${response.data.processed} 个键值`)
|
|
|
|
// 重新加载服务器翻译(获取新生成的翻译)
|
|
await loadServerMessages()
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('❌ 上报失败:', error)
|
|
} finally {
|
|
state.isReporting = false
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 8. 防抖上报
|
|
*/
|
|
let reportTimer: any = null
|
|
function debounceReport() {
|
|
clearTimeout(reportTimer)
|
|
reportTimer = setTimeout(() => {
|
|
if (state.pendingKeys.size > 0 && !state.isReporting) {
|
|
reportKeysToServer()
|
|
}
|
|
}, CONFIG.REPORT_DELAY)
|
|
}
|
|
|
|
/**
|
|
* 6. 采集新键值
|
|
*/
|
|
function collectKey(key: string, value: string | null = null) {
|
|
// 跳过已采集的
|
|
if (state.collectedKeys.has(key)) return
|
|
|
|
// 获取调用上下文(用于定位)
|
|
// const context = getCallContext()
|
|
|
|
state.collectedKeys.add(key)
|
|
saveCollectedKeys()
|
|
|
|
// 添加到待上报队列
|
|
state.pendingKeys.set(key, {
|
|
key,
|
|
value: value || key,
|
|
timestamp: Date.now(),
|
|
visitedCount: 1
|
|
})
|
|
|
|
// 触发上报
|
|
if (CONFIG.AUTO_REPORT) {
|
|
debounceReport()
|
|
}
|
|
}
|
|
|
|
const i18n = createI18n({
|
|
legacy: false, // Use Composition API
|
|
locale: getLanguage(),
|
|
fallbackLocale: 'zh-CN',
|
|
globalInjection: true,
|
|
messages,
|
|
missing: (locale, key) => {
|
|
// 采集这个新键值
|
|
if (CONFIG.AUTO_REPORT) {
|
|
collectKey(key)
|
|
}
|
|
// Return key as fallback
|
|
return key
|
|
}
|
|
})
|
|
|
|
/**
|
|
* 递归深度合并对象
|
|
*/
|
|
function deepMerge(target: any, source: any, parentKey: string = '') {
|
|
if (!source) return target
|
|
|
|
Object.keys(source).forEach(key => {
|
|
const sourceValue = source[key]
|
|
const targetValue = target[key]
|
|
const fullKey = parentKey ? `${parentKey}.${key}` : key
|
|
|
|
if (sourceValue && typeof sourceValue === 'object' && !Array.isArray(sourceValue)) {
|
|
if (!targetValue || typeof targetValue !== 'object') {
|
|
target[key] = {}
|
|
}
|
|
deepMerge(target[key], sourceValue, fullKey)
|
|
} else {
|
|
// 只有当源对象有值时才尝试合并
|
|
if (sourceValue !== null && sourceValue !== undefined && sourceValue !== '') {
|
|
// 判断 sourceValue 是否是占位符 (例如 "dashboard.view" 这种 key 形式的字符串)
|
|
// 增加不区分大小写的比较,并处理 "prefix.key" 格式的匹配
|
|
const sourceLower = typeof sourceValue === 'string' ? sourceValue.toLowerCase() : '';
|
|
const fullKeyLower = fullKey.toLowerCase();
|
|
const keyLower = key.toLowerCase();
|
|
|
|
// 占位符判断:
|
|
// 1. 值完全等于当前的 fullKey (不区分大小写)
|
|
// 2. 值完全等于当前的 key (不区分大小写)
|
|
// 3. 值是 "xxx.key" 格式且等于 fullKey (不区分大小写)
|
|
const isPlaceholder = typeof sourceValue === 'string' &&
|
|
(sourceLower === fullKeyLower || sourceLower === keyLower);
|
|
|
|
// 如果不是占位符,或者目标对象还没有该翻译,则采用服务器提供的翻译
|
|
if (!isPlaceholder || !targetValue) {
|
|
target[key] = sourceValue
|
|
}
|
|
}
|
|
}
|
|
})
|
|
return target
|
|
}
|
|
|
|
/**
|
|
* 从服务器加载翻译
|
|
*/
|
|
export async function loadServerMessages(language: string | null = null) {
|
|
const targetLanguage = language || i18n.global.locale.value;
|
|
|
|
try {
|
|
console.log(`🌐 从服务器加载国际化翻译 (${targetLanguage})...`)
|
|
|
|
const response = await indexApi.getI18nMessage({
|
|
language: targetLanguage
|
|
});
|
|
|
|
if (response.data) {
|
|
const newMessages = response.data.messages || response.data;
|
|
// @ts-ignore
|
|
state.serverMessages[targetLanguage] = newMessages;
|
|
state.isLoaded = true;
|
|
|
|
// 深度合并到 i18n 实例,确保本地新增的键值不被服务器返回的同名父级对象覆盖
|
|
// @ts-ignore
|
|
const currentMessages = JSON.parse(JSON.stringify(i18n.global.getLocaleMessage(targetLanguage)))
|
|
const mergedMessages = deepMerge(currentMessages, newMessages)
|
|
|
|
// @ts-ignore
|
|
i18n.global.setLocaleMessage(targetLanguage, mergedMessages)
|
|
|
|
const forced = FORCE_MENU_LABELS[targetLanguage]
|
|
if (forced && mergedMessages.menu && typeof mergedMessages.menu === 'object') {
|
|
Object.assign(mergedMessages.menu, forced)
|
|
// @ts-ignore
|
|
i18n.global.setLocaleMessage(targetLanguage, mergedMessages)
|
|
}
|
|
|
|
// console.log('整合后的语言包:', mergedMessages)
|
|
console.log(`✅ 服务器翻译加载并深度合并成功 (${targetLanguage})`);
|
|
}
|
|
} catch (error) {
|
|
console.warn(`⚠️ 服务器翻译加载失败 (${targetLanguage}),使用本地翻译`, error);
|
|
}
|
|
}
|
|
|
|
// 初始化加载
|
|
loadCollectedKeys()
|
|
|
|
export default i18n
|