<template>
  <div class="item" v-if="i18nEnabled && languageSettings.length > 1">
    <el-dropdown class="lang-box" trigger="click">
      <span class="el-dropdown-link">
        <i class="iconfont icon-duoyuyan"></i
        ><i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown" class="lang-box-pup">
        <el-dropdown-item
          v-for="(item, index) in languageSettings"
          :key="index"
          :command="item.languageCode"
          @click.native="changeLanguage(item.languageCode)"
          :class="{ cur: currentName == item.languageName }"
          >{{ $t1(item.languageName) }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>

<script>
import settingConfig from "@/settings";

export default {
  name: "langTool",
  data() {
    return {
      languageSettings: [],
      languageSettingMap: {},
      i18nEnabled: settingConfig.i18nEnabled,
    };
  },
  computed: {
    currentName() {
      return this.languageSettingMap[this.$i18n.locale];
    },
  },
  mounted() {
    this.initLanguageSetting();
  },
  methods: {
    changeLanguage(command) {
      if (this.$i18n.locale != command) {
        this.$http({
          url: USER_PREFIX + `/auth/switchLanguage`,
          method: `post`,
          data: {
            stringOne: command,
          },
          isLoading: true,
          modalStrictly: true,
          loadingTarget: document.body,
          success: (res) => {
            this.$i18n.locale = command; // 设置给本地的i18n插件
            localStorage.setItem("i18n-lang", command);
            this.$message.success("切换多语言成功");
            location.reload();
          },
        });
      }
    },
    initLanguageSetting() {
      if (settingConfig.i18nEnabled !== true) return;
      let languageSettings = [];
      languageSettings.push(...this.$store.state.user.languageSettings);
      let map = {};
      languageSettings.forEach((item) => {
        map[item.languageCode] = item.languageName;
      });
      this.languageSettingMap = map;
      this.languageSettings = languageSettings;
    },
  },
};
</script>
<style scoped lang="scss">
/*多语言*/
.lang-box {
  border-right: solid 1px #ffffff24;
  padding-right: 7px;
  height: 18px;
  line-height: 18px;
  vertical-align: middle;
  color: #fff;
  font-size: 12px;
  margin-left: 5px;
  .el-icon--right {
    margin-left: 3px;
  }

  .el-dropdown-link {
    color: #fff;

    .name {
      display: inline-block;
      width: 28px;
      height: 19px;
      overflow: hidden;
      vertical-align: middle;
      font-size: 12px;
      line-height: 19px;
    }

    i {
      zoom: 0.7;
      margin-left: 3px;
      opacity: 0.8;

      &.iconfont {
        font-size: 24px;
        vertical-align: middle;
        margin-right: 2px;
      }
    }
  }
}

.lang-box-pup .el-dropdown-menu__item.cur {
  background-color: #eaf0f4;
  color: #5583a9;
}
</style>
