<template>
  <div class="admin-layout">
    <!-- 顶部导航栏 -->
    <header class="top-nav">
      <div class="nav-logo" @click="handleMenuClick('/admin/dashboard')" title="返回数据看板">
        <div class="logo-icon">
          <i class="el-icon-s-platform"></i>
        </div>
        <span class="logo-text">总后台管理</span>
        <div class="logo-home-badge">
          <i class="el-icon-s-home"></i>
        </div>
      </div>
      <div class="nav-divider"></div>

      <nav class="nav-menu">
        <div
          v-for="(menu, index) in menuData"
          :key="index"
          class="nav-item"
          :class="{ active: activeTopIndex === index && activeTopIndex !== -1 }"
          @click="switchTopMenu(index)"
        >
          <i :class="menu.icon"></i>
          <span>{{ menu.title }}</span>
        </div>
      </nav>

      <!-- 右侧用户区域 -->
      <div class="user-area">
        <div class="user-info">
          <div class="user-avatar">
            {{ (nickName || 'A').charAt(0).toUpperCase() }}
          </div>
          <span class="user-role">管理员</span>
        </div>
        <el-dropdown @command="handleCommand" trigger="click">
          <div class="nav-user">
            <span class="nav-username">{{ nickName }}</span>
            <i class="el-icon-arrow-down dropdown-arrow"></i>
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="profile">
              <i class="el-icon-user"></i> 个人中心
            </el-dropdown-item>
            <el-dropdown-item command="logout" divided>
              <i class="el-icon-switch-button"></i> 退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </header>

    <!-- 主体区域 -->
    <div class="main-container">
      <!-- 左侧侧边栏 -->
      <aside class="sidebar" :class="{ 'sidebar-dashboard': isDashboard }">
        <!-- Dashboard 快捷入口 -->
        <div v-if="isDashboard" class="dashboard-shortcuts">
          <div class="shortcuts-title">
            <i class="el-icon-s-grid"></i>
            <span>快捷入口</span>
          </div>
          <div
            v-for="(menu, index) in menuData"
            :key="index"
            class="shortcut-item"
            @click="switchTopMenu(index)"
          >
            <i :class="menu.icon"></i>
            <span>{{ menu.title }}</span>
          </div>
        </div>

        <!-- 普通二三级菜单 -->
        <template v-else>
          <div class="sidebar-header">
            <i class="el-icon-menu"></i>
            <span>菜单入口</span>
          </div>
          <el-menu
            :default-active="activeMenu"
            :unique-opened="true"
            background-color="#fafbff"
            text-color="#555"
            active-text-color="#4f46e5"
          >
          <template v-for="item in currentSideMenu">
            <!-- 有子菜单的分组（支持三级：el-submenu 内嵌 el-submenu 或 el-menu-item） -->
            <el-submenu
              v-if="item.children && item.children.length"
              :index="item.title"
              :key="item.title"
            >
              <template slot="title">
                <i v-if="item.icon" :class="item.icon"></i>
                <span>{{ item.title }}</span>
              </template>
              <template v-for="child in item.children">
                <!-- 三级分组（如外呼管理 > 通话接口管理等） -->
                <el-submenu
                  v-if="child.children && child.children.length"
                  :index="child.title"
                  :key="child.title"
                >
                  <template slot="title">
                    <i v-if="child.icon" :class="child.icon"></i>
                    <span>{{ child.title }}</span>
                  </template>
                  <el-menu-item
                    v-for="leaf in child.children"
                    :key="leaf.path"
                    :index="leaf.path"
                    @click="handleMenuClick(leaf.path)"
                  >{{ leaf.title }}</el-menu-item>
                </el-submenu>
                <!-- 普通二级菜单项 -->
                <el-menu-item
                  v-else
                  :key="child.path"
                  :index="child.path"
                  @click="handleMenuClick(child.path)"
                >{{ child.title }}</el-menu-item>
              </template>
            </el-submenu>
            <!-- 无子菜单的直接链接项 -->
            <el-menu-item
              v-else
              :index="item.path"
              :key="item.path"
              @click="handleMenuClick(item.path)"
            >
              <i v-if="item.icon" :class="item.icon"></i>
              <span slot="title">{{ item.title }}</span>
            </el-menu-item>
          </template>
        </el-menu>
        </template>
      </aside>

      <!-- 内容区域 -->
      <main class="content-area">
        <router-view :key="viewKey" />
      </main>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'AdminLayout',
  data() {
    return {
      activeTopIndex: -1,
      viewKey: Date.now()
      // menuData 已改为 computed 属性，从后端动态路由中读取
    }
  },
  computed: {
    ...mapGetters(['nickName', 'avatar']),
    // 从Vuex Store动态路由中读取菜单结构（替代硬编码menuData）
    menuData() {
      const routes = this.$store.state.permission.sidebarRouters || []
      // 优先查找非 hidden 的 /admin 路由（动态路由含完整菜单），
      // 避免 constantRoutes 中的兜底路由（hidden:true，子路由不全）被优先匹配
      const adminRoute = routes.find(r => r.path === '/admin' && !r.hidden)
        || routes.find(r => r.path === '/admin')
      if (!adminRoute || !adminRoute.children) return []

      return adminRoute.children
        .filter(child => child.children && child.children.length > 0)
        .map(group => ({
          title: (group.meta && group.meta.title) || group.name || '',
          icon: (group.meta && group.meta.icon) || '',
          children: this.buildSidebarItems(group.children, group.path ? '/admin/' + group.path : '/admin')
        }))
    },
    // 是否处于数据看板页面
    isDashboard() {
      return this.$route.path === '/admin/dashboard' || this.$route.path === '/admin'
    },
    // 当前顶部菜单对应的侧边栏二三级菜单（dashboard 时返回空）
    currentSideMenu() {
      if (this.activeTopIndex === -1) return []
      return this.menuData[this.activeTopIndex]?.children || []
    },
    // 当前路由高亮
    activeMenu() {
      return this.$route.path
    }
  },
  watch: {
    '$route.path'() {
      this.viewKey = Date.now()
      this.initActiveTop()
    }
  },
  created() {
    // /admin 根路径自动重定向到数据看板
    if (this.$route.path === '/admin') {
      this.$router.replace('/admin/dashboard').catch(() => {})
    }
    this.initActiveTop()
  },
  methods: {
    // 将Vue Router子路由转换为侧边栏菜单项格式
    // parentPath: 父级路径前缀，用于拼接 ParentView 分组的完整路径
    buildSidebarItems(routes, parentPath) {
      if (!routes || !routes.length) return []
      return routes
        .filter(r => !r.hidden)
        .map(r => {
          let fullPath = r.path || ''
          if (!fullPath.startsWith('/')) {
            fullPath = (parentPath ? parentPath + '/' : '/admin/') + fullPath
          }
          const item = {
            title: (r.meta && r.meta.title) || r.name || '',
            path: fullPath,
            icon: (r.meta && r.meta.icon) || ''
          }
          // 如果有子路由且不是叶子菜单，递归构建子菜单
          if (r.children && r.children.length && !r.component) {
            item.children = this.buildSidebarItems(r.children, fullPath)
          }
          return item
        })
    },
    switchTopMenu(index) {
      this.activeTopIndex = index
      // 自动跳转到该分组下第一个可点击的路由
      const firstPath = this.getFirstPath(this.menuData[index].children)
      if (firstPath && this.$route.path !== firstPath) {
        this.$router.push(firstPath).catch(() => {})
      }
    },
    getFirstPath(items) {
      if (!items || !items.length) return null
      for (let i = 0; i < items.length; i++) {
        if (items[i].path) return items[i].path
        if (items[i].children) {
          const found = this.getFirstPath(items[i].children)
          if (found) return found
        }
      }
      return null
    },
    // 根据当前路由自动确定顶部选中项
    initActiveTop() {
      const currentPath = this.$route.path
      // dashboard 是独立首页，不属于任何一级菜单，设为 -1
      if (currentPath === '/admin/dashboard' || currentPath === '/admin') {
        this.activeTopIndex = -1
        return
      }
      for (let i = 0; i < this.menuData.length; i++) {
        if (this.containsPath(this.menuData[i], currentPath)) {
          this.activeTopIndex = i
          return
        }
      }
      // 不匹配任何分组时，回到 dashboard 状态
      this.activeTopIndex = -1
    },
    containsPath(menu, path) {
      if (menu.path === path) return true
      if (menu.children) {
        return menu.children.some(child => this.containsPath(child, path))
      }
      return false
    },
    handleMenuClick(path) {
      if (this.$route.path === path) return
      this.$router.push(path).catch(err => {
        if (err.name !== 'NavigationDuplicated') {
          console.warn('AdminLayout navigation error:', err)
        }
      })
    },
    handleCommand(cmd) {
      if (cmd === 'logout') {
        this.$store.dispatch('LogOut').then(() => {
          this.$router.push('/login')
        })
      } else if (cmd === 'profile') {
        this.$message.info('个人中心功能开发中')
      }
    }
  }
}
</script>

<style scoped>
/* ===== 整体布局 ===== */
.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin: 0 !important;
  padding: 0 !important;
  /* 抵消 sidebar.scss 给 #app 下 .main-container 注入的 margin-left */
  position: relative;
}

/* ===== 顶部导航栏 ===== */
.top-nav {
  height: 50px;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 20px 0 0;
  flex-shrink: 0;
  z-index: 100;
  border-bottom: 1px solid #e8e8e8;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* Logo */
.nav-logo {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  margin-right: 32px;
  flex-shrink: 0;
  text-decoration: none;
  padding: 0 16px;
}

.logo-icon {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #409EFF, #1890ff);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 17px;
  flex-shrink: 0;
}

.logo-text {
  font-size: 17px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
}

.logo-home-badge {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  background: rgba(64, 158, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 4px;
  flex-shrink: 0;
  transition: background 0.2s;
}

.logo-home-badge i {
  font-size: 13px;
  color: #409EFF;
}

.nav-logo:hover .logo-home-badge {
  background: rgba(64, 158, 255, 0.2);
}

.nav-logo:hover .logo-home-badge i {
  color: #1890ff;
}

/* Logo 与一级菜单之间的分隔线 */
.nav-divider {
  width: 1px;
  height: 24px;
  background: #e8e8e8;
  margin-right: 8px;
  flex-shrink: 0;
}

/* 顶部菜单 */
.nav-menu {
  display: flex;
  align-items: center;
  flex: 1;
  overflow: hidden;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 0 18px;
  height: 50px;
  line-height: 50px;
  cursor: pointer;
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
  transition: all 0.3s;
  position: relative;
  flex-shrink: 0;
  border-bottom: 2px solid transparent;
}

.nav-item:hover {
  color: #409EFF;
}

.nav-item.active {
  color: #409EFF;
  border-bottom-color: #409EFF;
  font-weight: 500;
}

.nav-item i {
  font-size: 16px;
  flex-shrink: 0;
}

/* 右侧用户区域 */
.user-area {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: auto;
  flex-shrink: 0;
  padding-left: 20px;
  color: #606266;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-avatar {
  width: 30px;
  height: 30px;
  border-radius: 8px;
  background: linear-gradient(135deg, #409EFF, #1890ff);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  font-weight: 600;
  flex-shrink: 0;
}

.user-role {
  font-size: 13px;
  color: #909399;
  white-space: nowrap;
}

.nav-user {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 6px;
  transition: background 0.2s;
}

.nav-user:hover {
  background: rgba(64, 158, 255, 0.08);
}

.nav-username {
  font-size: 14px;
  color: #303133;
  white-space: nowrap;
}

.dropdown-arrow {
  color: #909399;
  font-size: 12px;
}

/* ===== 主体区域 ===== */
/* 强制覆盖 sidebar.scss 中 #app .main-container { margin-left: 200px } 的全局规则 */
.main-container {
  flex: 1;
  display: flex;
  overflow: hidden;
  margin: 0 !important;
  padding: 0 !important;
}

/* ===== 左侧侧边栏 ===== */
.sidebar {
  width: 200px;
  flex-shrink: 0;
  background: #fff;
  border-right: 1px solid #e8e8e8;
  overflow-y: auto;
  overflow-x: hidden;
  /* 覆盖全局 aside 样式 */
  padding: 0 !important;
  margin: 0 !important;
}

/* Dashboard 快捷入口侧边栏 */
.sidebar-dashboard {
  background: #fafbff;
}

.dashboard-shortcuts {
  padding: 16px 12px;
}

.shortcuts-title {
  display: flex;
  align-items: center;
  gap: 7px;
  font-size: 12px;
  font-weight: 600;
  color: #999;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  padding: 0 4px 10px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 8px;
}

.shortcuts-title i {
  font-size: 14px;
  color: #bbb;
}

.shortcut-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 12px;
  border-radius: 8px;
  cursor: pointer;
  color: #555;
  font-size: 14px;
  transition: all 0.2s;
  margin-bottom: 2px;
}

.shortcut-item:hover {
  background: #ede9fe;
  color: #4f46e5;
}

.shortcut-item i {
  font-size: 16px;
  flex-shrink: 0;
  color: #8b5cf6;
}

/* 覆盖 el-menu 默认样式 */
.sidebar >>> .el-menu {
  border-right: none;
  width: 200px;
  padding: 8px 12px;
  background-color: #fafbff !important;
}

/* 菜单入口 header */
.sidebar-header {
  display: flex;
  align-items: center;
  gap: 7px;
  font-size: 12px;
  font-weight: 600;
  color: #999;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  padding: 16px 16px 10px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 0;
  background: #fafbff;
}

.sidebar-header i {
  font-size: 14px;
  color: #bbb;
}

.sidebar >>> .el-menu-item {
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  padding-left: 24px !important;
  color: #555 !important;
  border-radius: 8px;
  margin-bottom: 2px;
  transition: all 0.2s;
}

.sidebar >>> .el-submenu__title {
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  font-weight: 500;
  color: #555 !important;
  border-radius: 8px;
  margin-bottom: 2px;
  transition: all 0.2s;
}

.sidebar >>> .el-menu-item i,
.sidebar >>> .el-submenu__title i {
  margin-right: 8px;
  color: #8b5cf6;
}

.sidebar >>> .el-submenu .el-menu-item {
  padding-left: 24px !important;
  height: 46px;
  line-height: 46px;
  font-size: 13px;
  min-width: 200px;
  color: #555 !important;
  border-radius: 8px;
  margin-bottom: 2px;
  transition: all 0.2s;
}

.sidebar >>> .el-submenu .el-menu-item i {
  color: #8b5cf6;
}

.sidebar >>> .el-menu-item.is-active {
  background-color: #ede9fe !important;
  color: #4f46e5 !important;
  font-weight: 600;
  border-right: none !important;
  border-left: 3px solid #4f46e5 !important;
  padding-left: 21px !important;
}

.sidebar >>> .el-menu-item:hover,
.sidebar >>> .el-submenu__title:hover {
  background-color: #ede9fe !important;
  color: #4f46e5 !important;
}

.sidebar >>> .el-submenu .el-menu-item:hover {
  background-color: #ede9fe !important;
  color: #4f46e5 !important;
}

/* ===== 内容区域 ===== */
.content-area {
  flex: 1;
  overflow-y: auto;
  background: #f5f6fa;
  padding: 16px 24px 24px;
  min-width: 0;
}
</style>
