<template>
  <el-dropdown v-if="isToken && userInfo.avatar" @command="handleCommand">
    <div class="flex items-center gap-2">
      <el-avatar :size="40" :src="userInfo.avatar" />
      <span class="text-md font-semibold">{{ userInfo.nickname }}</span>
      <el-icon><ArrowDown /></el-icon>
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="user">用户中心</el-dropdown-item>
        <el-dropdown-item command="logout">退出登录</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <NuxtLink v-else to="/login">
    <el-button class="w-[96px]" type="primary">会员中心</el-button>
  </NuxtLink>
</template>

<script setup lang="ts">
import { ArrowDown } from '@element-plus/icons-vue'
import { useUserStore } from '~/stores/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const isToken = computed(() => !!userStore.token)
const userInfo = computed(() => userStore.userInfo)

const handleCommand = async (command: string) => {
  switch (command) {
    case 'user':
      router.push('/user')
      break
    case 'logout':
      ElMessageBox.confirm('确定退出登录吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          userStore.logout()
        })
        .catch(() => {})
  }
}
</script>
