<template>
  <n-dropdown
    placement="bottom-end"
    :options="[
      {
        label: '个人中心',
        key: 'personal-center',
        icon: () => h(IconUser),
      },
      {
        type: 'divider',
      },
      {
        label: '退出登录',
        key: 'logout',
        icon: () => h(IconLogout),
      },
    ]"
    @select="(key) => {
      if (key === 'personal-center') {
        handlePersonalCenter()
      }
      else if (key === 'logout') {
        handleLogout()
      }
    }"
  >
    <div class="flex items-center gap-2 cursor-pointer hover:bg-gray-50 hover:bg-opacity-80 rounded-lg px-3 py-2 transition-colors">
      <!-- 用户头像 -->
      <n-avatar
        :size="32"
        :src="avatar"
        fallback-src=""
        round
        class="border border-gray-200"
      >
        <template #placeholder>
          <icon-park-outline-user class="text-lg" />
        </template>
      </n-avatar>

      <!-- 用户名称 -->
      <span class="text-sm font-medium text-gray-700 max-w-20 truncate">
        {{ displayName }}
      </span>

      <!-- 下拉箭头 -->
      <icon-park-outline-down class="text-xs text-gray-500" />
    </div>
  </n-dropdown>
</template>

<script setup lang="ts">
import { computed, h } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { coiMsgBox } from '@/utils/coi'
import IconUser from '~icons/icon-park-outline/user'
import IconLogout from '~icons/icon-park-outline/logout'

const authStore = useAuthStore()
const router = useRouter()

// 获取用户信息
const userInfo = computed(() => authStore.userInfo)

// 获取用户显示名称
const displayName = computed(() => {
  if (!userInfo.value)
    return '未知用户'
  return userInfo.value.userName || '未知用户'
})

// 获取用户头像
const avatar = computed(() => {
  if (!userInfo.value?.avatar)
    return ''
  return userInfo.value.avatar
})

// 处理个人中心点击
function handlePersonalCenter() {
  router.push('/personal-center/index')
}

// 处理退出登录
function handleLogout() {
  coiMsgBox('确定要退出登录吗？', '退出确认').then(() => {
    authStore.logout()
  }).catch(() => {
    // 取消操作
  })
}
</script>

<style scoped>
.dark .hover\:bg-gray-50:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.dark .text-gray-700 {
  color: #e5e7eb;
}

.dark .text-gray-500 {
  color: #9ca3af;
}

.dark .border-gray-200 {
  border-color: #374151;
}
</style>
