import { createRouter, createWebHistory } from 'vue-router';
import Cookies from 'js-cookie';
import AuthPage from '../components/authentication/AuthPage.vue';
import MainPage from '../views/mainpage/index.vue';
import UutReport from '../views/uut/Report.vue';
import UutHistory from '../views/uut/History.vue';
import DashboardTest from '../views/dashboard/test.vue';
import Profile from '../views/user/Profile.vue';
import Testers from '../views/equipment/Testers.vue';

// 登录状态检查工具函数
const checkLoginStatus = () => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
  const hasUserInfo = !!localStorage.getItem('userInfo');
  const hasToken = !!Cookies.get('access_token');
  return isLoggedIn && hasUserInfo && hasToken;
};

// 清除登录状态方法
const clearLoginState = () => {
  localStorage.removeItem('isLoggedIn');
  localStorage.removeItem('userInfo');
  localStorage.removeItem('rememberedUser');
  Cookies.remove('access_token');
};

// 路由守卫：需要登录的路由
const requireAuth = (to, from, next) => {
  if (checkLoginStatus()) {
    next();
  } else {
    clearLoginState();
    next('/auth');
  }
};

// 路由配置
const routes = [
  {
    path: '/auth',
    name: 'Auth',
    component: AuthPage,
    beforeEnter: (to, from, next) => {
      if (checkLoginStatus()) {
        next('/');
      } else {
        next();
      }
    }
  },
  {
    path: '/',
    name: 'Main',
    component: MainPage,
    beforeEnter: requireAuth,
    children: [
      { path: '', redirect: '/dashboard' },
      { path: 'dashboard', name: 'Dashboard', component: DashboardTest },
      { path: 'uut/report', name: 'UutReport', component: UutReport },
      { path: 'uut/history', name: 'UutHistory', component: UutHistory },
      { path: 'profile', component: Profile },
      { path: 'testers', component: Testers }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    redirect: (to) => checkLoginStatus() ? '/' : '/auth'
  }
];

const router = createRouter({
  history: createWebHistory('/sbu4i4/'),
  routes,
  scrollBehavior(to, from, savedPosition) {
    return savedPosition || { top: 0 };
  }
});

// 全局路由守卫
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.beforeEnter === requireAuth)) {
    requireAuth(to, from, next);
  } else {
    next();
  }
});

// 导出路由和工具函数
export { router as default, clearLoginState, checkLoginStatus };
