import Vue from 'vue'
import VueI18n from 'vue-i18n'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import twLocale from 'element-ui/lib/locale/lang/zh-TW'
import ElementLocale from 'element-ui/lib/locale'

import { getLanguage, getUrlParam } from '@/utils/index'
import Cookies from 'js-cookie'

const localeCookieKey = 'locale'

ElementLocale.i18n((key, value) => VueI18n.instance.t(key, value))

export function getLocale() {
  const locale = Cookies.get(localeCookieKey)
  return getUrlParam('lang') || locale || getLanguage() || 'zh-cn'
}

function loadLocaleMessages() {
  const locales = require.context('./lang', true, /[A-Za-z0-9-_,\s]+\.js$/i)
  const messages = { 'zh-cn': {}}
  locales.keys().forEach((key) => {
    if (key.indexOf('/module/') === -1) {
      const matched = key.match(/([A-Za-z0-9-_]+)\./i)
      if (matched && matched.length > 1) {
        const locale = matched[1]
        messages[locale] = locales(key)['default']
      }
    }
  })
  locales.keys().forEach((key) => {
    if (key.indexOf('/module/') !== -1) {
      const matched = key.match(/([^/\.]+)\./i)
      if (matched && matched.length > 1) {
        messages['zh-cn'][matched[1]] = locales(key)['default']
      }
    }
  })
  messages['zh-cn'] = Object.assign(messages['zh-cn'], zhLocale)
  messages['zh-tw'] = Object.assign({}, twLocale)
  messages['en-us'] = Object.assign({}, enLocale)
  return messages
}
export async function setLocale(locale) {
  if (locale !== 'zh-cn') {
    // const r = await getAppLocale({ 'app_id': 'matchexpo_live', 'locale': locale.replace('-', '_') })
    // if (r.ret === 0) {
    //   let messages = VueI18n.instance.getLocaleMessage(locale)
    //   messages = Object.assign(messages, r.data)
    //   VueI18n.instance.setLocaleMessage(locale, messages)
    // }
  }
  VueI18n.instance.locale = locale
  return Cookies.set(localeCookieKey, locale)
}
export async function initLocale() {
  if (!VueI18n.locateInit) {
    VueI18n.locateInit = true
    const locale = getLocale()
    await setLocale(locale)
  }
}
if (!VueI18n.instance) {
  Vue.use(VueI18n)
  const locale = getLocale()
  if (locale !== 'zh-cn') {
    setLocale(locale).then(v => {})
  }
  console.log('init i18n')
  const i18n = new VueI18n({
    locale: locale,
    fallbackLocale: 'zh-cn',
    messages: loadLocaleMessages(),
    silentFallbackWarn: true
  })
  VueI18n.instance = i18n
  Vue.prototype.$t = (key, text, values) => {
    return i18n.t(key, values)
  }
  Vue.prototype.$tc = (key, text, values) => {
    return i18n.tc(key, values)
  }
}
export default VueI18n.instance
