<template>
  <el-dropdown class="language-switch" :trigger="trigger" @command="handleCommand">
    <span class="language-trigger">
      <i v-if="showIcon" class="el-icon-s-flag" />
      <span class="label">{{ currentLabel }}</span>
      <i class="el-icon-arrow-down el-icon--right" />
    </span>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item
        v-for="item in languageOptions"
        :key="item.value"
        :command="item.value"
        :disabled="item.value === locale"
      >
        <span>{{ item.nativeLabel || item.label }}</span>
        <i v-if="item.value === locale" class="el-icon-check option-check" />
      </el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
import { getLocaleOptions } from '@/lang'

export default {
  name: 'LanguageSwitch',
  props: {
    trigger: {
      type: String,
      default: 'hover'
    },
    showIcon: {
      type: Boolean,
      default: true
    }
  },
  computedLegacy: {
    locale() {
      return this.$store.getters.language
    },
    languageOptions() {
      return [
        { value: 'en', label: 'English' },
        { value: 'zh', label: '中文' }
      ]
    },
    currentLabel() {
      return this.locale === 'zh' ? '中文' : 'English'
    }
  },
  computed: {
    locale() {
      return this.$store.getters.language
    },
    languageOptions() {
      return getLocaleOptions()
    },
    currentOption() {
      return this.languageOptions.find(item => item.value === this.locale) || this.languageOptions[0] || {}
    },
    currentLabel() {
      return this.currentOption.nativeLabel || this.currentOption.label || this.locale
    }
  },
  methods: {
    handleCommand(locale) {
      this.$setLocale(locale)
    }
  }
}
</script>

<style lang="scss" scoped>
.language-switch {
  display: inline-flex;
  align-items: center;
  height: 100%;

  .language-trigger {
    display: inline-flex;
    align-items: center;
    color: #7A5C3F;
    cursor: pointer;
    user-select: none;
  }

  .label {
    margin-left: 6px;
  }

  .option-check {
    margin-left: 8px;
    color: #FF9326;
  }
}
</style>
