import Vue from 'vue'
import VueI18n from 'vue-i18n'
import moment from 'moment'
import { loadLangData } from '@/api/lang'
import {LANAGUAGE_DATA} from '@/store/mutation-types'
import storage from 'store'

// 语言包从服务器获取时从 store 状态机导入
// default lang
// import zhCN from './lang/zh-CN'

Vue.use(VueI18n)

export const defaultLang = 'zh-CN'

const messages = {}

const i18n = new VueI18n({
  silentTranslationWarn: true,
  //locale: defaultLang,
  locale: "",
  fallbackLocale: defaultLang,
  messages
})

Vue.prototype.$lang = function(param) {
  const { lang } = this.$store.getters
  const { menuId } = this.$route.meta
  const langData = this.$i18n.getLocaleMessage(lang)

  /* 存在菜单id 拼接匹配 */
  let key = menuId ? `${menuId}.${param}` : param
  let text = langData[key] ? langData[key] : param

  /* 存在菜单id却又有全局配置时，全局配置优先 */
  /* langData[`${menuId}.${param}`] == langData[globalKey]此时会有冲突 */

  // if (langData[`${menuId}.${param}`] == langData[globalKey]) {
  //   console.warn(`全局配置和菜单${menuId}下的国际化配置[${langData[globalKey]}]冲突！`)
  // }

  if (menuId && langData[param]) {
    text = langData[param]
  }

  return text
}

// Vue.prototype.$bak = function(param) {
//   const { menuId } = this.$route.meta
//   const langData = this.$i18n.getLocaleMessage(this.$store.getters.lang)
//   let text = ''
//   let key = `${menuId}.${param}`
//   if (langData[menuId]) {
//     let value = langData[menuId][param]
//     text = value ? value : param
//   } else {
//     text = param
//   }
//   return text
// }

//const loadedLanguages = [defaultLang]
const loadedLanguages = []

function setI18nLanguage(lang) {
  i18n.locale = lang
  // request.headers['Accept-Language'] = lang
  document.querySelector('html').setAttribute('lang', lang)
  return lang
}

function getLangDataFromStorage(lang){
  var data = storage.get(LANAGUAGE_DATA, {})
  return data[lang];
}

function setLangDataFromStorage(lang,langData){
  var data = storage.get(LANAGUAGE_DATA, {})
  data[lang] = langData
  storage.set(LANAGUAGE_DATA,data);
}


export function loadLanguageAsync(lang = defaultLang) {
    // 缓存语言设置
   // if (i18n.locale == lang) {
      import(`./lang/${lang}`).then(msg => {
        const locale = msg.default
        moment.updateLocale(locale.momentName, locale.momentLocale)
      })

     // console.log("loadedLanguages",loadedLanguages)
      if (!loadedLanguages.includes(lang)) {
        var langData = getLangDataFromStorage(lang);
        if(langData){
          i18n.setLocaleMessage(lang, langData)
          loadedLanguages.push(lang)
          return setI18nLanguage(lang)
        }else{
          return loadLangData({ lag: lang })
            .then(res => {
              const locale = res.data
              i18n.setLocaleMessage(lang, locale)
              loadedLanguages.push(lang)
              setLangDataFromStorage(lang,locale)
              // moment.updateLocale(locale.momentName, locale.momentLocale)
              return setI18nLanguage(lang)
            })
            .catch(error => {
              console.log(error)
            })
        }
      }
      setI18nLanguage(lang)
   // }
}

export function loadLanguageFormMem(lang = defaultLang) {
  // 缓存语言设置
  if (i18n.locale !== lang) {
    import(`./lang/${lang}`).then(msg => {
      const locale = msg.default
      moment.updateLocale(locale.momentName, locale.momentLocale)
    })
    if (!loadedLanguages.includes(lang)) {
      var langData = getLangDataFromStorage(lang);
      if(langData){
        i18n.setLocaleMessage(lang, langData)
        loadedLanguages.push(lang)
        return setI18nLanguage(lang)
      }
    }
    setI18nLanguage(lang)
  }
}

export function i18nRender(key) {
  return i18n.t(`${key}`)
}

export function i18nFnRender(key) {
  const { lang } = this.$store.getters
  const langData = this.$i18n.getLocaleMessage(lang)
  return langData[key] || key
}

export default i18n
