<script lang="jsx">
import { defineComponent } from 'vue';
import { useRouter } from 'vue-router';
import { NPopover } from 'naive-ui';
import { userApi } from '@/api/user';
import { useUserStore } from '@/stores/modules/userStore'

const RenderUserAvatar = ({ store }) => {
  const router = useRouter();
  const user = store.userInfo;

  const clearLoginStatus = async () => {
    await userApi.postLogout();
    store.clearUserInfo();
    router.push("/login");
  }

  const userMenuOptions = [
    {
      label: '个人中心',
      key: "/user"
    },
    {
      label: '修改密码',
      key: "edit"
    },
    {
      label: '退出登录',
      key: "logout"
    },
  ]

  const handleUserMenuOptions = async ({ key }) => {
    switch (key) {
      case '/user':
        router.push(key)
        return
      case 'edit':
        const userStore = useUserStore();
        userStore.setDialogStatus(true)
        return
      case 'logout':
        clearLoginStatus();
    }
  }

  const slots = {
    default: () => (
      <ul class="
        w-[120px] px-[10px] py-[10px]
        rounded-[4px] bg-white
        text-[12px] text-[#272D35] leading-[30px] text-center
      ">
        {
          userMenuOptions.map(item => (
            <li
              class="h-[30px] rounded-[4px] hover:bg-[#F4F6F8] hover:text-[#2454FF] cursor-pointer"
              key={item.key}
              onClick={() => handleUserMenuOptions(item)}
            >
              {item.label}
            </li>
          ))
        }
      </ul>
    ),
    trigger: () => (
      <div class="flex items-center cursor-pointer">
        <img src={user.avatar} alt="" class="w-[32px] h-[32px] mr-[10px] rounded-[50%]" />
        <span class="text-[#272D35] text-[12px]">{user.nickName}</span>
      </div>
    )
  };

  return (
    <NPopover
      v-slots={slots}
      trigger="hover"
      raw={true}
      show-arrow={false}
      style="box-shadow: 0px 10px 31px 0px #B1B6B933"
    ></NPopover>
  )
}

export default defineComponent({
  setup () {

    const userStore = useUserStore();

    return () => (
      <div >{<RenderUserAvatar store={userStore} />}</div>
    );
  },
});

</script>