<template>
  <div class="tap-language-switch">
    <el-menu class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-submenu index="1">
        <template slot="title">{{ show }}</template>
        <template v-for="item in language.arr">
          <template v-for="(v, k) in item">
            <el-menu-item :key="k" :index="k">{{ v }}</el-menu-item>
          </template>
        </template>
      </el-submenu>
    </el-menu>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import language from '@/assets/languages/language'

export default {
  name: 'LanguageSwitch',
  data() {
    const _defaultLocale = 'zh-CN'
    const _lang = Cookies.get('lang') || window.navigator.language || window.navigator.userLanguage || ''
    if (_lang) {
      if (language[_lang]) {
        this.$i18n.locale = _lang
      } else {
        let flag = true
        /* 做一下 兼容性处理 */
        for (const k in language) {
          const reg = new RegExp(k, 'gi')
          if (reg.test(_lang)) {
            this.$i18n.locale = k
            flag = false
            break
          }
        }
        if (flag) {
          /* 当前语言版本 - 不再我们的语言库中，那么默认 en */
          this.$i18n.locale = _defaultLocale
          Cookies.set('lang', _defaultLocale, { expires: 30, domain: '.ezijing.com' })
        }
      }
    } else {
      this.$i18n.locale = _defaultLocale
      Cookies.set('lang', _defaultLocale, { expires: 30, domain: '.ezijing.com' })
    }
    let show = language[this.$i18n.locale].show
    language[this.$i18n.locale].arr.forEach((item, i) => {
      if (item[this.$i18n.locale]) {
        show = item[this.$i18n.locale]
      }
    })
    return {
      show: show,
      language: language[this.$i18n.locale]
    }
  },
  mounted() {},
  methods: {
    handleSelect(key, val) {
      Cookies.set('lang', key, { expires: 30, domain: '.ezijing.com' })
      this.$i18n.locale = key
      /* 刷新页面 */
      this.$router.go(0)
    }
  }
}
</script>

<style lang="scss" scoped>
.tap-language-switch {
  position: absolute;
  top: 5px;
  right: 100px;
  height: 70px;
  .el-menu--horizontal > .el-submenu.is-active .el-submenu__title {
    border: none;
  }
}
</style>
