<template>
  <aside class="sidebar" :class="{ 'is-collapsed': collapsed }">
    <!-- 菜单区域 -->
    <el-menu
      class="sidebar-menu"
      :unique-opened="true"
      :default-active="activeMenu"
      :collapse="collapsed"
      router
      @select="handleSelect"
    >
      <template v-for="menu in menuList" :key="menu.id">
        <!-- 无子菜单 -->
        <el-menu-item v-if="!menu.children || menu.children.length === 0" :index="menu.path || `__invalid_${menu.id}`">
          <el-icon v-if="menu.icon">
            <component :is="iconMap[menu.icon]" />
          </el-icon>
          <template #title>{{ menu.label }}</template>
        </el-menu-item>

        <!-- 有子菜单 -->
        <el-sub-menu v-else :index="menu.path || `__invalid_${menu.id}`">
          <template #title>
            <el-icon v-if="menu.icon">
              <component :is="iconMap[menu.icon]" />
            </el-icon>
            <span>{{ menu.label }}</span>
          </template>
          <el-menu-item
            v-for="subMenu in menu.children"
            :key="subMenu.id"
            :index="subMenu.path || `__invalid_${subMenu.id}`"
          >
            <template #title>{{ subMenu.label }}</template>
          </el-menu-item>
        </el-sub-menu>
      </template>
    </el-menu>
  </aside>
</template>

<script setup lang="ts">
import {
  HomeFilled,
  List,
  UserFilled,
  Platform,
  BellFilled,
  GoodsFilled,
  WarningFilled,
  Tools,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'

defineProps<{
  collapsed?: boolean
}>()

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 计算当前激活的菜单 index
const activeMenu = computed(() => {
  return route.fullPath
})

// 获取完整菜单列表
const menuList = computed(() => {
  return userStore.sideMenu || []
})

// 菜单点击处理：
// el-menu 在 router 模式下会根据 :index 跳路径，但当路径在动态路由表中不存在时，
// 会触发 :pathMatch(.*)* 兑底被重定向到 /dashboard，造成“点了菜单没反应、过一会自动刷新”。
// 这里加一道护栏：路径为空、或者未在已注册路由表中存在时，提示用户并取消跳转。
const handleSelect = (index: string) => {
  if (!index || index.startsWith('__invalid_')) {
    ElMessage.warning('该菜单暂未配置访问路径，请联系管理员')
    return false
  }
  // 检查路由表中是否已存在该路径
  const hasExact = router.getRoutes().some((r) => r.path === index)
  if (!hasExact) {
    ElMessage.warning('该页面路由未加载，请稍后重试')
    return false
  }
  return true
}

// 图标映射表
const iconMap: Record<string, any> = {
  HomeFilled,
  List,
  UserFilled,
  Platform,
  BellFilled,
  GoodsFilled,
  WarningFilled,
  Tools,
}
</script>

<style scoped lang="scss">
.sidebar {
  position: fixed;
  top: 50px;
  left: 0;
  bottom: 0;
  width: 200px;
  background: #fff;
  border-right: 1px solid var(--el-border-color-light);
  overflow-y: auto;
  overflow-x: hidden;
  z-index: 999;
  transition: width 0.3s ease;

  &.is-collapsed {
    width: 64px;

    :deep(.el-menu--collapse) {
      width: 64px;

      .el-sub-menu__title,
      .el-menu-item {
        padding-left: 20px !important;
        padding-right: 20px !important;
      }
    }
  }

  .sidebar-menu {
    height: 100%;
    border: none;
    background: transparent;

    &:not(.el-menu--collapse) {
      width: 200px;
    }

    :deep(.el-menu-item) {
      height: 50px;
      line-height: 50px;

      &.is-active {
        background: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
        border-right: 3px solid var(--el-color-primary);
      }
    }

    :deep(.el-sub-menu) {
      .el-sub-menu__title {
        height: 50px;
        line-height: 50px;
      }

      &.is-active {
        > .el-sub-menu__title {
          color: var(--el-color-primary);
        }
      }
    }
  }
}

// 暗色模式适配
:deep(.dark) {
  .sidebar {
    background: var(--el-bg-color);
    border-right-color: var(--el-border-color-darker);

    .sidebar-menu {
      :deep(.el-menu-item) {
        &.is-active {
          background: var(--el-color-primary-dark-2);
        }
      }
    }
  }
}
</style>
