// =============================================================================
// 企微IT智能服务台 — 管理后台路由配置
// =============================================================================
// 说明：定义管理后台页面路由映射，包含 admin 权限路由守卫

import { createRouter, createWebHistory } from 'vue-router'

// --------------------------------------------------------------------------
// 路由配置
// --------------------------------------------------------------------------
const routes = [
  {
    // 登录页面
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '管理员登录', requiresAuth: false },
  },
  {
    // 管理后台主布局（需要认证）
    path: '/',
    component: () => import('@/layouts/AdminLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        // 根路径重定向到仪表盘
        path: '',
        redirect: '/dashboard',
      },
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '运营总览', requiresAuth: true },
      },
      {
        path: 'configs',
        name: 'Configs',
        component: () => import('@/views/Configs.vue'),
        meta: { title: '功能开关', requiresAuth: true },
      },
      {
        path: 'agents',
        name: 'Agents',
        component: () => import('@/views/Agents.vue'),
        meta: { title: '坐席管理', requiresAuth: true },
      },
      {
        path: 'roles',
        name: 'Roles',
        component: () => import('@/views/Roles.vue'),
        meta: { title: '角色管理', requiresAuth: true },
      },
      {
        path: 'integrations',
        name: 'Integrations',
        component: () => import('@/views/Integrations.vue'),
        meta: { title: '系统集成', requiresAuth: true },
      },
      {
        path: 'terminal-security',
        name: 'TerminalSecurity',
        component: () => import('@/views/TerminalSecurity.vue'),
        meta: { title: '终端安全', requiresAuth: true },
      },
      {
        path: 'quick-replies',
        name: 'QuickReplies',
        component: () => import('@/views/QuickReplies.vue'),
        meta: { title: '快速回复', requiresAuth: true },
      },
      {
        path: 'assignment-mode',
        name: 'AssignmentMode',
        component: () => import('@/views/AssignmentMode.vue'),
        meta: { title: '分配模式', requiresAuth: true },
      },
      {
        path: 'monitor',
        name: 'Monitor',
        component: () => import('@/views/Monitor.vue'),
        meta: { title: '会话监控', requiresAuth: true },
      },
      {
        path: 'flowcharts',
        name: 'Flowcharts',
        component: () => import('@/views/Flowcharts.vue'),
        meta: { title: '排查流程图', requiresAuth: true },
      },
      {
        path: 'session-audit',
        name: 'SessionAudit',
        component: () => import('@/views/SessionAudit.vue'),
        meta: { title: '会话审计', requiresAuth: true },
      },
      {
        path: 'agent-performance',
        name: 'AgentPerformance',
        component: () => import('@/views/AgentPerformance.vue'),
        meta: { title: '坐席绩效', requiresAuth: true },
      },
      {
        path: 'system-logs',
        name: 'SystemLogs',
        component: () => import('@/views/SystemLogs.vue'),
        meta: { title: '系统日志', requiresAuth: true },
      },
      {
        // P2 占位页：主题模板
        path: 'themes',
        name: 'Themes',
        component: () => import('@/views/Placeholder.vue'),
        meta: { title: '主题模板', requiresAuth: true, comingSoon: true },
      },
      {
        // P2 占位页：数据看板
        path: 'reports',
        name: 'Reports',
        component: () => import('@/views/Placeholder.vue'),
        meta: { title: '数据看板', requiresAuth: true, comingSoon: true },
      },
      {
        // P2 占位页：知识库管理
        path: 'knowledge',
        name: 'Knowledge',
        component: () => import('@/views/Placeholder.vue'),
        meta: { title: '知识库管理', requiresAuth: true, comingSoon: true },
      },
    ],
  },
  {
    // 404 页面：捕获所有未匹配路由
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/Placeholder.vue'),
    meta: { title: '页面未找到' },
  },
]

// --------------------------------------------------------------------------
// 创建路由实例
// --------------------------------------------------------------------------
// createWebHistory: 使用 HTML5 History 模式，基础路径 /itadmin/（与IT数据平台共享域名）
const router = createRouter({
  history: createWebHistory('/itadmin/'),
  routes,
})

// --------------------------------------------------------------------------
// 路由守卫 — 检查管理员登录状态
// --------------------------------------------------------------------------
router.beforeEach((to, _from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - IT智能服务台管理后台`
  }

  // ===== 新增：处理 URL 中的 token 参数（从 Portal 跳转过来时） =====
  const urlParams = new URLSearchParams(window.location.search)
  const urlToken = urlParams.get('token')
  if (urlToken) {
    // 保存 token 到 localStorage
    localStorage.setItem('admin_token', urlToken)
    // 清除 URL 中的 token 参数，保持 URL 干净
    window.history.replaceState({}, '', window.location.pathname)
  }
  // ===== token 处理结束 =====

  // 检查是否需要认证
  const requiresAuth = to.meta.requiresAuth !== false
  const token = localStorage.getItem('admin_token')

  if (requiresAuth && !token) {
    // 需要认证但没有 token，跳转到登录页
    next({ path: '/login', query: { redirect: to.fullPath } })
  } else if (to.path === '/login' && token) {
    // 已登录用户访问登录页，跳转到仪表盘
    next({ path: '/dashboard' })
  } else {
    next()
  }
})

export default router
