<template>
  <div class="layout-container">
    <!-- 顶部导航栏 -->
    <header class="layout-header">
      <div class="header-left">
        <div 
          v-if="isMobile" 
          class="mobile-menu-btn"
          @click="toggleSidebar"
        >
          <el-icon :size="24">
            <component :is="sidebarVisible ? 'Fold' : 'Expand'" />
          </el-icon>
        </div>
        <div class="logo">
          <el-icon :size="28" color="#667eea">
            <Notebook />
          </el-icon>
          <span v-if="!isMobile" class="logo-text">考培练系统</span>
        </div>
      </div>
      
      <div class="header-right">
        <el-space :size="20">
          <!-- 通知铃铛组件 -->
          <NotificationBell />
          
          <el-dropdown trigger="click">
            <el-button link class="header-btn user-btn">
              <el-avatar :size="32" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
              <span v-if="!isMobile" class="username">{{ headerName }}</span>
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="goToProfile">
                  <el-icon><User /></el-icon>
                  个人中心
                </el-dropdown-item>
                <el-dropdown-item @click="goToSettings">
                  <el-icon><Setting /></el-icon>
                  系统设置
                </el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-space>
      </div>
    </header>

    <div class="layout-body">
      <!-- 移动端遵罩层 -->
      <div 
        v-if="isMobile && sidebarVisible" 
        class="sidebar-overlay" 
        @click="sidebarVisible = false"
      ></div>
      
      <!-- 侧边栏 -->
      <aside 
        class="layout-sidebar" 
        :class="{ 
          collapsed: isCollapsed,
          mobile: isMobile,
          'mobile-visible': isMobile && sidebarVisible
        }"
      >
        <el-menu
          :default-active="activeMenu"
          router
          :collapse="isCollapsed && !isMobile"
          :collapse-transition="false"
          class="sidebar-menu"
          @select="handleMenuSelect"
        >
          <template v-for="route in menuRoutes" :key="route.path">
            <!-- 有子菜单的情况 -->
            <el-sub-menu v-if="route.children && route.children.length > 1" :index="route.path">
              <template #title>
                <el-icon><component :is="route.icon" /></el-icon>
                <span>{{ route.title }}</span>
              </template>
              <el-menu-item
                v-for="child in route.children"
                :key="child.path"
                :index="child.path"
              >
                <el-icon><component :is="child.icon" /></el-icon>
                <span>{{ child.title }}</span>
              </el-menu-item>
            </el-sub-menu>
            
            <!-- 单个菜单的情况 -->
            <el-menu-item
              v-else-if="route.children && route.children.length === 1"
              :index="route.children[0].path"
            >
              <el-icon><component :is="route.children[0].icon" /></el-icon>
              <span>{{ route.children[0].title }}</span>
            </el-menu-item>
            
            <!-- 无子菜单的情况 -->
            <el-menu-item
              v-else
              :index="route.path"
            >
              <el-icon><component :is="route.icon" /></el-icon>
              <span>{{ route.title }}</span>
            </el-menu-item>
          </template>
        </el-menu>
        
        <!-- 折叠按钮 -->
        <div class="collapse-btn" @click="toggleSidebar">
          <el-icon :size="16">
            <component :is="isCollapsed ? 'Expand' : 'Fold'" />
          </el-icon>
        </div>
      </aside>

      <!-- 主内容区 -->
      <main class="layout-main">
        <div class="main-container">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </div>
      </main>
    </div>

    <!-- 移动端底部导航栏 -->
    <nav v-if="isMobile" class="mobile-tab-bar">
      <div 
        class="tab-item" 
        :class="{ active: activeMenu === '/dashboard' }"
        @click="router.push('/dashboard')"
      >
        <el-icon><Monitor /></el-icon>
        <span>首页</span>
      </div>
      
      <div 
        class="tab-item" 
        :class="{ active: activeMenu.startsWith('/trainee/course-center') }"
        @click="router.push('/trainee/course-center')"
      >
        <el-icon><Collection /></el-icon>
        <span>课程</span>
      </div>
      
      <div 
        class="tab-item" 
        :class="{ active: activeMenu.startsWith('/trainee/ai-practice') }"
        @click="router.push('/trainee/ai-practice-center')"
      >
        <el-icon><ChatLineRound /></el-icon>
        <span>陪练</span>
      </div>
      
      <div 
        class="tab-item" 
        :class="{ active: activeMenu.startsWith('/user') }"
        @click="router.push('/user/profile')"
      >
        <el-icon><User /></el-icon>
        <span>我的</span>
      </div>

      <div 
        class="tab-item menu-trigger" 
        :class="{ active: sidebarVisible }"
        @click="toggleSidebar"
      >
        <el-icon><Grid /></el-icon>
        <span>更多</span>
      </div>
    </nav>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { authManager } from '@/utils/auth'
import NotificationBell from '@/components/NotificationBell.vue'

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

// 顶部名称显示：优先 full_name/name，回退 username
const headerName = computed(() => {
  const user = authManager.getCurrentUser()
  return (user as any)?.full_name || (user as any)?.name || (user as any)?.username || ''
})

// 侧边栏折叠状态
const isCollapsed = ref(false)

// 移动端检测
const isMobile = ref(false)

// 侧边栏显示状态（移动端使用）
const sidebarVisible = ref(false)

// 当前激活的菜单
const activeMenu = computed(() => {
  const { path } = route
  return path
})

// 菜单配置 - 按照导航栏规划文件
const menuConfig = [
  {
    path: '/dashboard',
    title: '首页',
    icon: 'Monitor',
    children: []
  },
  {
    path: '/trainee',
    title: '学员中心',
    icon: 'Reading',
    children: [
      {
        path: '/trainee/growth-path',
        title: '成长路径',
        icon: 'TrendCharts'
      },
      {
        path: '/trainee/course-center',
        title: '课程中心',
        icon: 'Collection'
      },
      {
        path: '/trainee/ai-practice-center',
        title: '陪练中心',
        icon: 'ChatLineRound'
      },
      {
        path: '/trainee/score-report',
        title: '成绩报告',
        icon: 'Document'
      },
      {
        path: '/trainee/mistakes',
        title: '错题分析',
        icon: 'Warning'
      },
      {
        path: '/trainee/practice-records',
        title: '陪练记录',
        icon: 'DocumentCopy'
      }
    ]
  },
  {
    path: '/analysis',
    title: '数据分析',
    icon: 'DataAnalysis',
    children: [
      {
        path: '/analysis/statistics',
        title: '统计分析',
        icon: 'Histogram'
      }
    ]
  },
  {
    path: '/manager',
    title: '管理者中心',
    icon: 'UserFilled',
    children: [
      {
        path: '/manager/team-dashboard',
        title: '团队看板',
        icon: 'DataBoard'
      },
      {
        path: '/manager/team-management',
        title: '团队管理',
        icon: 'Coordinate'
      },
      {
        path: '/manager/assignment-center',
        title: '任务中心',
        icon: 'Tickets'
      },
      {
        path: '/manager/course-management',
        title: '课程管理',
        icon: 'Notebook'
      },
      {
        path: '/manager/growth-path-management',
        title: '成长路径管理',
        icon: 'Finished'
      },
      {
        path: '/manager/practice-scene-management',
        title: '陪练场景管理',
        icon: 'Microphone'
      },
      {
        path: '/manager/student-scores',
        title: '学员考试成绩',
        icon: 'DataAnalysis'
      },
      {
        path: '/manager/student-practice',
        title: '学员陪练记录',
        icon: 'ChatLineRound'
      }
    ]
  },
  {
    path: '/admin',
    title: '系统管理',
    icon: 'Setting',
    children: [
      {
        path: '/admin/dashboard',
        title: '管理员仪表盘',
        icon: 'DataAnalysis'
      },
      {
        path: '/admin/user-management',
        title: '用户管理',
        icon: 'User'
      },
      {
        path: '/admin/position-management',
        title: '岗位管理',
        icon: 'OfficeBuilding'
      },
      {
        path: '/admin/logs',
        title: '系统日志',
        icon: 'Files'
      }
    ]
  },
  {
    path: '/user',
    title: '个人中心',
    icon: 'User',
    children: [
      {
        path: '/user/profile',
        title: '个人信息',
        icon: 'Avatar'
      },
      {
        path: '/user/settings',
        title: '系统设置',
        icon: 'Tools'
      }
    ]
  }
]

// 获取菜单路由
const menuRoutes = computed(() => {
  // 仅保留当前用户可访问的菜单项
  const filterChildren = (children: any[] = []) =>
    children.filter((child: any) => authManager.canAccessRoute(child.path))

  return menuConfig
    .map((route: any) => {
      const next = { ...route }
      if (route.children && route.children.length > 0) {
        next.children = filterChildren(route.children)
      }
      return next
    })
    .filter((route: any) => {
      // 有子菜单且至少一个可访问
      if (route.children && route.children.length > 0) return true
      // 无子菜单时检查自身路径
      return authManager.canAccessRoute(route.path)
    })
})

/**
 * 切换侧边栏折叠状态
 */
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

/**
 * 跳转到个人中心
 */
const goToProfile = () => {
  router.push('/user/profile')
}

/**
 * 跳转到系统设置
 */
const goToSettings = () => {
  router.push('/user/settings')
}

/**
 * 退出登录
 * - 调用后端登出接口
 * - 清理本地令牌与用户信息
 * - 跳转到登录页
 */
const handleLogout = async () => {
  try {
    await authManager.logout()
    ElMessage.success('退出登录成功')
  } catch (e) {
    // 保底提示，logout 内部已做异常容错
  } finally {
    router.push('/login')
  }
}

/**
 * 菜单选择处理
 */
const handleMenuSelect = (_path: string) => {
  // 移动端点击菜单后自动收起侧边栏
  if (isMobile.value) {
    sidebarVisible.value = false
  }
}

/**
 * 检测是否为移动端
 */
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

/**
 * 处理窗口大小改变
 */
const handleResize = () => {
  checkMobile()
}

/**
 * 切换侧边栏显示状态（移动端）
 */
const toggleSidebar = () => {
  if (isMobile.value) {
    sidebarVisible.value = !sidebarVisible.value
  } else {
    toggleCollapse()
  }
}

// 组件挂载时检测移动端
onMounted(() => {
  checkMobile()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
// 移动端底部导航栏样式
.mobile-tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: calc(56px + env(safe-area-inset-bottom));
  padding-bottom: env(safe-area-inset-bottom);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-around;
  align-items: center;
  z-index: 2000;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03);

  .tab-item {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 4px;
    color: #909399;
    transition: all 0.3s ease;
    cursor: pointer;
    
    .el-icon {
      font-size: 22px;
      transition: all 0.3s;
    }
    
    span {
      font-size: 10px;
      font-weight: 500;
      transform: scale(0.9);
    }
    
    &.active {
      color: #667eea;
      
      .el-icon {
        transform: translateY(-2px);
      }
    }
    
    &:active {
      background-color: rgba(0, 0, 0, 0.02);
    }
  }
}

.layout-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

// 顶部导航栏样式
.layout-header {
  height: 60px;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  position: relative;
  z-index: 100;

  .header-left {
    display: flex;
    align-items: center;

    .mobile-menu-btn {
      display: flex;
      align-items: center;
      margin-right: 12px;
      cursor: pointer;
      color: #606266;
      display: none !important; // 强制隐藏，由底部导航栏接管
      
      &:hover {
        color: #667eea;
      }
    }

    .logo {
      display: flex;
      align-items: center;
      gap: 12px;
      font-size: 20px;
      font-weight: 600;
      color: #333;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        transform: translateX(3px);
      }

      .logo-text {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    }
  }

  .header-right {
    display: flex;
    align-items: center;

    .header-btn {
      position: relative;
      padding: 8px;
      border-radius: 8px;
      transition: all 0.3s;

      &:hover {
        background-color: #f5f7fa;
      }

      .badge {
        position: absolute;
        top: 5px;
        right: 5px;
      }
    }

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

      .username {
        font-size: 14px;
        color: #333;
      }
    }
  }
}

// 主体布局
.layout-body {
  flex: 1;
  display: flex;
  overflow: hidden;
}

// 侧边栏样式
.layout-sidebar {
  width: 220px;
  background: #fff;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
  position: relative;

  &.collapsed {
    width: 64px;
  }

  .sidebar-menu {
    flex: 1;
    border: none;
    overflow-y: auto;
    overflow-x: hidden;

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

    :deep(.el-menu-item),
    :deep(.el-sub-menu__title) {
      height: 48px;
      line-height: 48px;
      transition: all 0.3s;

      &:hover {
        background-color: #f5f7fa;
      }

      &.is-active {
        background: linear-gradient(90deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
        color: #667eea;
        font-weight: 500;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 0;
          height: 100%;
          width: 3px;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
      }
    }

    :deep(.el-sub-menu) {
      .el-menu-item {
        padding-left: 50px !important;
      }
    }
  }

  .collapse-btn {
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-top: 1px solid #ebeef5;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background-color: #f5f7fa;
      color: #667eea;
    }
  }
}

// 主内容区样式
.layout-main {
  flex: 1;
  overflow: hidden;
  background-color: #f5f7fa;

  .main-container {
    height: 100%;
    padding: 24px;
    overflow-y: auto;
  }
}

// 响应式适配
@media (max-width: 768px) {
  .layout-sidebar {
    position: fixed;
    left: 0;
    top: 60px;
    height: calc(100vh - 60px);
    z-index: 99;
    transform: translateX(-100%);
    transition: transform 0.3s;
  }

  .layout-main {
    margin-left: 0;
  }
}

// 移动端遵罩层
.sidebar-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

// 移动端侧边栏样式
.layout-sidebar {
  &.mobile {
    position: fixed;
    top: 60px;
    left: 0;
    height: calc(100vh - 60px);
    width: 200px;
    z-index: 1000;
    transform: translateX(-100%);
    transition: transform 0.3s ease;
    
    &.mobile-visible {
      transform: translateX(0);
    }
    
    .collapse-btn {
      display: none;
    }
  }
}
</style>