<template>
  <el-card class="user-menu" :class="{ 'w-[20rem]': !isCollapse }" shadow="never">
    <div class="text-md font-semibold leading-6">{{ title }}</div>
    <el-menu
      ref="menuRef"
      :collapse="isCollapse"
      :default-active="activeMenu"
      :collapse-transition="false"
      :router="props.router"
      @select="handleMenuSelect"
    >
      <el-menu-item index="basic">
        <el-icon :size="20"><User /></el-icon>
        <span>基本信息</span>
      </el-menu-item>
      <el-menu-item index="logout" class="justify-center">
        <el-icon v-if="isCollapse" :size="20"><SwitchButton /></el-icon>
        <span class="font-normal">退出登录</span>
      </el-menu-item>
    </el-menu>
  </el-card>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useUserStore } from '~/stores/user'
import { User, SwitchButton } from '@element-plus/icons-vue'
import { useWindowSize } from '@vueuse/core'

const props = withDefaults(
  defineProps<{
    title?: string
    activeMenu?: string
    router?: boolean
  }>(),
  {
    title: '',
    activeMenu: 'basic',
    router: false
  }
)
const menuRef = ref()
const router = useRouter()
const userStore = useUserStore()
const { width } = useWindowSize()
const isCollapse = computed(() => width.value <= 1024 && window.innerWidth >= 768)

// 处理菜单选择
const handleMenuSelect = (key: string) => {
  if (key === 'logout') {
    menuRef.value?.updateActiveIndex(props.activeMenu)
    ElMessageBox.confirm('确定退出登录吗？', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        userStore.logout()
        router.push('/login')
      })
      .catch(() => {})
  }
}
</script>

<style lang="scss" scoped>
.user-menu {
  @apply rounded-[1rem];
  background: var(--el-bg-color-overlay);
  --el-card-padding: 1.5rem;

  :deep(.el-menu) {
    @apply w-full mt-6;
    border: none;
    background: transparent;

    .el-menu-item {
      @apply text-md leading-6 rounded-lg mt-4 font-semibold;
      border: 1px solid var(--menu-br-color);
      border-left-width: 1px;
      background: var(--menu-bg-color);
      color: var(--menu-text-color);

      &:first-child {
        @apply mt-0;
      }

      &:hover {
        border-color: var(--menu-hover-br-color);
        background: var(--menu-hover-bg-color);
      }

      &.is-active {
        @apply lg:border-l-4;
        border-color: var(--menu-active-br-color);
        background: var(--menu-active-bg-color);
      }
    }
  }

  @media screen and (max-width: 768px) {
    @apply w-full;
    --el-card-padding: 1rem;

    :deep(.el-menu) {
      @apply mt-4 flex gap-4;

      .el-menu-item {
        @apply mt-0;
        width: calc(100% - 0.5rem);
      }
    }
  }
}
</style>
