import { createWebHistory, createRouter } from 'vue-router'
// 导入视图组件
import ArticleList from '../views/aericlelist.vue'
import HomePage from '../views/home.vue'
import NonsensePage from '../views/nonsense.vue'
import MessageBoardPage from '../views/messageboard.vue'
import AboutMePage from '../views/aboutme.vue'
import ArticleContentPage from '../views/articlecontents.vue'
import ArticleSavePage from '../views/articlesave.vue'
import LoginPage from '../views/login.vue'
// 导入Element Plus消息组件
import { ElMessage } from 'element-plus'

/**
 * 路由配置数组
 * 定义了应用的所有路由路径和对应的组件
 */
const routes = [
  {
    path: '/',
    redirect: '/home' // 默认跳转到首页，显示所有文章
  },
  {
    path: '/home',
    name: 'home',
    component: HomePage,
    meta: { title: '首页' },
    children: [
      {
        path: 'aericleattribute',
        name: 'homeByAttribute',
        component: HomePage
      },
      {
        path: 'aericlecategory',
        name: 'homeByCategory',
        component: HomePage
      },

      {
        path: 'aericletitle',
        name: 'homeByTitle',
        component: HomePage
      },
      {
        path: 'aericlestatus',
        name: 'homeByStatus',
        component: HomePage
      }
      
    ]
  },
  {
    path: '/articlelist',
    name: 'articleList',
    component: ArticleList,
    meta: {
      title: '文章目录'
    }
  },
  {
    path: '/nonsense',
    name: 'nonsense',
    component: NonsensePage,
    meta: {
      title: '随笔'
    }
  },
  {
    path: '/message',
    name: 'messageBoard',
    component: MessageBoardPage,
    meta: {
      title: '留言板'
    }
  },
  {
    path: '/about',
    name: 'aboutMe',
    component: AboutMePage,
    meta: {
      title: '关于我'
    }
  },
  {
    path: '/article',
    name: 'articleContent',
    component: ArticleContentPage,
    meta: {
      title: '文章详情'
    }
  },
  {
    path: '/login',
    name: 'login',
    component: LoginPage,
    meta: {
      title: '登录'
    }
  },
  {
    path: '/articlesave',
    name: 'articlesave',
    component: ArticleSavePage,
    meta: {
      title: '保存文章',
      requiresAuth: true // 需要登录才能访问
    }
  }
]

/**
 * 创建路由实例
 */
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    // 路由切换时滚动到页面顶部
    return { top: 0 }
  }
})

/**
 * 检查token是否过期的工具函数
 * @param {string} token - JWT token字符串
 * @returns {boolean} - token是否已过期
 */
const isTokenExpired = (token) => {
  try {
    const payload = JSON.parse(atob(token.split('.')[1]))
    const exp = payload.exp * 1000 // 转换为毫秒
    return Date.now() > exp
  } catch (error) {
    return true // 解析失败视为过期
  }
}

/**
 * 全局路由守卫 - 处理页面标题和认证
 */
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title + ' - 个人博客'
  } else {
    document.title = '个人博客'
  }
  
  // 从localStorage获取token和登录状态
  const token = localStorage.getItem('token')
  const savedSpecificData = localStorage.getItem('globalStoreSpecificData')
  const initialSpecificData = savedSpecificData ? JSON.parse(savedSpecificData) : {}
  
  // 检查token是否有效
  const isTokenValid = token && !isTokenExpired(token)
  
  // 如果有token但已过期，清除token和登录状态
  if (token && isTokenExpired(token)) {
    localStorage.removeItem('token')
    // 直接更新localStorage中的登录状态
    initialSpecificData.Login = false
    localStorage.setItem('globalStoreSpecificData', JSON.stringify(initialSpecificData))
    ElMessage.error('登录已过期，请重新登录')
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    // 如果token有效，允许访问
    if (isTokenValid) {
      next()
    } else {
      // 未登录或token已过期，重定向到登录页
      ElMessage.warning('请先登录')
      next('/login')
    }
  } else {
    // 不需要认证的路由，直接允许访问
    next()
  }
})

export default router;