import Vue from 'vue'
import VueI18n from 'vue-i18n'
import { Locale } from 'vant'
import { getLang } from '@/utils/auth'
import { I18N_LOCALE, I18N_FALLBACK_LOCALE } from '@/constant'

Vue.use(VueI18n)

function loadLocaleMessages() {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
  const messages = {}
  for (const key of locales.keys()) {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i)
    if (matched && matched.length > 1) {
      const locale = matched[1]
      const localeVant = require(`vant/lib/locale/lang/${locales(key)._element}`)
      messages[locale] = {
        ...locales(key),
        ...localeVant ? localeVant.default : {}
      }
    }
  }
  return messages
}

const messages = loadLocaleMessages()

Vue.prototype.$languages = Object.keys(messages).map(langlage => ({
  label: messages[langlage]._name,
  value: langlage
}))

const i18n = new VueI18n({
  locale: getLang() || I18N_LOCALE,
  fallbackLocale: I18N_FALLBACK_LOCALE,
  messages
})

Locale.use(i18n.locale, messages[i18n.locale])

export default i18n
