<script lang='ts' setup>
import { onMounted, reactive, ref } from 'vue';
import { Down, Translate } from '@icon-park/vue-next';
import { useI18n } from 'vue-i18n';
import { useGlobalPinia } from '@/pinia/global';
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
import ja from 'element-plus/lib/locale/lang/ja';
import en from 'element-plus/lib/locale/lang/en';
import key from '@/constant/key';
import { useRoutesStore } from '@/pinia/permission';
import Cookies from 'js-cookie';

const props = defineProps(
  {
    // 是否是文字类型
    textType: { type: Boolean, required: true, default: false },
  },
);

type Language = {
  name: string
  value: string
  disabled: boolean
}

const { locale, t } = useI18n();
let routes = useRoutesStore();

const state = reactive({
  languages: [
    { name: 'English (US)', value: 'en', disabled: false },
    { name: '中文 (简体)', value: 'ch', disabled: true },
    { name: '日本語', value: 'jp', disabled: false },
  ] as Array<Language>,
  name: '中文 (简体)',
});

onMounted(() => {
  let language = localStorage.getItem(key.languageKey);
  if (language) {
    handleSetLanguage(language, false, false);
  } else {
    handleSetLanguage('ch', false, false);
  }
});

const dropdown = ref();
const global = useGlobalPinia();

const handleSetLanguage = (lang: string, switchMsg: boolean, ClickEvent: boolean) => {
  locale.value = lang;

  switch (lang) {
    case 'ch':
      global.handleSetLanguage(zhCn);
      break;
    case 'en':
      global.handleSetLanguage(en);
      break;
    case 'jp':
      ja.el.select.placeholder = '選択';
      global.handleSetLanguage(ja);
      break;
  }

  localStorage.setItem(key.languageKey, lang);
  Cookies.set(key.language, lang)

  state.languages.forEach((el: Language) => {
    el.disabled = false;
    if (el.value === lang) {
      state.name = el.name;
      el.disabled = true;
    }
  });

  dropdown.value.handleClose();

  if (ClickEvent === true) {
    document.location.reload();
    routes.handleInitMenu();
  }

  if (!switchMsg) return;
  ElMessage({
    message: t('SwitchLanguageSuccess'),
    type: 'success',
  });

};
</script>


<template>
  <el-dropdown ref='dropdown' hide-on-click trigger='click'>
    <span>
      <div v-if='props.textType === false'>
        <el-tooltip :content="t('language')" effect='dark' placement='bottom'>
          <translate fill='#333' size='24' theme='outline' />
        </el-tooltip>
      </div>
      <div v-else class='flex items-center'>
        <span class='mr-2'>{{ state.name }}</span>
        <down fill='#333333' size='20' theme='outline' />
      </div>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item v-for='item in state.languages' :key='item.value' :disabled='item.disabled'>
          <span @click='handleSetLanguage(item.value, true, true)'>{{ item.name }}</span>
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<style scoped></style>