import { createRouter, createWebHistory } from 'vue-router';
import Login from '../components/Login.vue';
import Register from '../components/Register.vue';
import PostDetail from '@/views/PostDetail.vue';
import MainPage from '@/views/MainPage.vue';
import UserPage from '@/views/UserPage.vue';
import NotificationList from '@/views/NotificationList.vue';
import ChangeInformation from '@/views/ChangeInformation.vue';
import FeedBack from '@/views/FeedBack.vue';
import PostPublish from '@/views/PostPublish.vue';
import { useUserStore } from '@/stores/user.js';
import { checkLoginStatus } from '@/utils/auth';
import { ElMessage } from 'element-plus';

const routes = [
  {
    path: '/',
    name: 'MainPage',
    component: MainPage
  },
  {
    path: '/user/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/user/register',
    name: 'Register',
    component: Register
  },
  { 
    path: '/post/:id', 
    name: 'PostDetail', 
    component: PostDetail 
  },
  {
    path: '/user/:userId',
    name: 'UserPage',
    component: UserPage,
    meta: { requiresAuth: true }
  },
  {//通知页面
    path: '/notificationlist',
    name: 'NotificationList',
    component: NotificationList,
    meta: { requiresAuth: true }
  },
  {//详细通知页面
    path: '/notification/:id', 
    name: 'NotificationDetail',
    component: () => import('@/views/NotificationDetail.vue'),
    props: true,
    meta: { requiresAuth: true }
  },
    {//反馈页面
    path: '/feedback',
    name: 'FeedBack',
    component: FeedBack
  },
  {
    //修改个人信息界面
    path:'/changeinformation',
    name:'ChangeInformation',
    component:ChangeInformation,
    meta: { requiresAuth: true }
  },
  {
    // 发布帖子页面
    path: '/postpublish',
    name: 'PostPublish',
    component: PostPublish,
    meta: { requiresAuth: true }
  },
  {
    // 管理员页面
    path: '/admin',
    name: 'Admin',
    component: () => import('@/views/admin/AdminDashboard.vue'),
    children: [
      {
        path: '',
        name: 'AdminOverview',
        component: () => import('@/views/admin/AdminOverview.vue')
      },
      {
        path: 'posts',
        name: 'AdminPosts',
        component: () => import('@/views/admin/AdminPosts.vue')
      },
      {
        path: 'users',
        name: 'AdminUsers',
        component: () => import('@/views/admin/AdminUsers.vue')
      },
      {
        path: 'comments',
        name: 'AdminComments',
        component: () => import('@/views/admin/AdminComments.vue')
      },
      {
        path: 'categories',
        name: 'AdminCategories',
        component: () => import('@/views/admin/AdminCategories.vue')
      }
    ],
    meta: { requiresAdmin: true, requiresAuth: true }
  }
];

const router = createRouter({
  history: createWebHistory(/*process.env.BASE_URL*/),
  routes
});

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  
  // 检查路由是否需要登录
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 如果用户未登录，先尝试从localStorage恢复登录状态
    if (!userStore.isLoggedIn) {
      console.log('访问需要登录的页面，但用户未登录，尝试恢复登录状态...');
      
      // 尝试从localStorage恢复用户状态
      const userId = localStorage.getItem('userId');
      const username = localStorage.getItem('username');
      const accessToken = localStorage.getItem('accessToken');
      const refreshToken = localStorage.getItem('refreshToken');
      const avatar = localStorage.getItem('avatar');
      const role = localStorage.getItem('role');
      
      // 如果localStorage中有用户信息，先恢复登录状态
      if (userId && username && accessToken && refreshToken) {
        userStore.login({
          userid: userId,
          userName: username,
          avatar: avatar || '',
          role: role || 1,
          accessToken,
          refreshToken
        });
        console.log('从localStorage恢复用户登录状态:', username);
        
        // 异步验证token有效性，但不阻塞导航
        setTimeout(() => {
          checkLoginStatus().catch(err => {
            console.error('Token验证失败，但不影响当前导航:', err);
          });
        }, 100);
        
        // 继续导航
        next();
        return;
      }
      
      // 如果localStorage中没有用户信息，尝试通过token验证登录状态
      try {
        console.log('尝试通过API验证登录状态...');
        const isLoggedIn = await checkLoginStatus();
        if (!isLoggedIn) {
          ElMessage.warning('请先登录');
          next({ path: '/' });
          return;
        }
      } catch (error) {
        console.error('登录状态验证失败:', error);
        ElMessage.warning('登录状态验证失败，请重新登录');
        next({ path: '/' });
        return;
      }
    }
  }
  
  // 检查路由是否需要管理员权限
  if (to.matched.some(record => record.meta.requiresAdmin)) {
    // 检查用户是否登录且是否有管理员权限
    if (!userStore.isLoggedIn) {
      ElMessage.error('请先登录');
      next({ path: '/' });
      return;
    }
    
    // 检查用户是否有管理员权限
    const role = parseInt(userStore.userInfo.role || localStorage.getItem('role') || 1);
    if (!(role === 2 || role === 3)) {
      ElMessage.error('您没有管理员权限');
      next({ path: '/' });
      return;
    }
  }
  
  // 继续导航
  next();
});

export default router; 