<!--
 * @Author: Vben
 * @Description: post switching component
-->
<template>
  <Tooltip :title="t('岗位切换')" placement="bottom" :mouseEnterDelay="0.5">
    <Dropdown
      placement="bottom"
      :trigger="['click']"
      :dropMenuList="formInfo.posts"
      :selectedKeys="selectedKeys"
      @menu-event="handleMenuEvent"
      overlayClassName="app-locale-picker-overlay"
    >
      <span class="cursor-pointer flex items-center p-2">
        <IconFontSymbol icon="qiehuangangwei" fontSize="18" />
      </span>
    </Dropdown>
  </Tooltip>
</template>
<script lang="ts" setup>
  import type { DropMenu } from '/@/components/Dropdown';
  import { ref, watchEffect, watch } from 'vue';
  import { Dropdown } from '/@/components/Dropdown';
  import IconFontSymbol from '/@/components/IconFontSymbol/Index.vue';
  import { storeToRefs } from 'pinia';
  import { Tooltip } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { changePost } from '/@/api/system/post';
  import { useI18n } from '/@/hooks/web/useI18n';

  const userStore = useUserStore();
  const { t } = useI18n();
  const { userInfo } = storeToRefs(userStore);
  const formInfo: any = ref({
    posts: [],
    postId: '',
  });
  getDropMenuList();
  watch(
    () => userInfo.value,
    (val) => {
      if (val) getDropMenuList();
    },
  );
  const selectedKeys = ref<string[]>([]);

  watchEffect(() => {
    selectedKeys.value = [formInfo.value.postId];
  });
  function getDropMenuList() {
    if (userInfo.value?.posts) {
      formInfo.value = userInfo.value;
      formInfo.value.posts.forEach((o) => {
        o.text = o.name;
        o.event = o.id;
      });
    }
  }
  async function toggleLocale(lang: string) {
    let res = await changePost(lang);

    selectedKeys.value = [lang as string];
    formInfo.value.departmentId = res.departmentId;
    formInfo.value.departmentName = res.departmentName;
    formInfo.value.postId = res.postId;
    formInfo.value.postName = res.postName;

    userStore.setUserInfo(formInfo.value);
  }

  function handleMenuEvent(menu: DropMenu) {
    if (formInfo.value.postId === menu.event) {
      return;
    }
    toggleLocale(menu.event as string);
  }
</script>

<style lang="less">
  .app-locale-picker-overlay {
    .ant-dropdown-menu-item {
      min-width: 160px;
    }
  }
</style>
