import Vue from 'vue'
import VueI18n from 'vue-i18n'
import ElementLocale from 'element-ui/lib/locale'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import enLocale from 'element-ui/lib/locale/lang/en'
import ruLocale from 'element-ui/lib/locale/lang/ru-RU'
import messages from './messages'

Vue.use(VueI18n)

// 合并ElementUI的语言包
const mergedMessages = {
  zh: {
    ...messages.zh,
    ...zhLocale
  },
  en: {
    ...messages.en,
    ...enLocale
  },
  ru: {
    ...messages.ru,
    ...ruLocale
  }
}

const i18n = new VueI18n({
  locale: localStorage.getItem('language') || 'en', // 从localStorage获取语言设置，默认英文
  fallbackLocale: 'zh', // 回退语言
  messages: mergedMessages
})

// 同步ElementUI的语言设置
ElementLocale.i18n((key, value) => i18n.t(key, value))

// 监听语言变化，保存到localStorage
i18n.vm.$watch('locale', (newLocale) => {
  localStorage.setItem('language', newLocale)
})

// 监听localStorage中language值的变化
function watchLanguageChange() {
  let intervalId = null
  let currentLanguage = localStorage.getItem('language') || 'en'
  
  // 使用storage事件监听localStorage变化（跨标签页）
  const storageHandler = (e) => {
    if (e.key === 'language' && e.newValue && e.newValue !== i18n.locale) {
      currentLanguage = e.newValue
      i18n.locale = e.newValue
    }
  }
  window.addEventListener('storage', storageHandler)
  
  // 定期检查localStorage中的language值（同页面内变化）
  intervalId = setInterval(() => {
    const newLanguage = localStorage.getItem('language') || 'en'
    if (newLanguage !== currentLanguage && newLanguage !== i18n.locale) {
      currentLanguage = newLanguage
      i18n.locale = newLanguage
    }
  }, 300) // 每300ms检查一次，降低频率
  
  // 返回清理函数
  return () => {
    if (intervalId) {
      clearInterval(intervalId)
      intervalId = null
    }
    window.removeEventListener('storage', storageHandler)
  }
}

// 启动监听
const cleanupLanguageWatch = watchLanguageChange()

// 在页面卸载时清理资源
window.addEventListener('beforeunload', () => {
  if (cleanupLanguageWatch) {
    cleanupLanguageWatch()
  }
})

export default i18n