import { createRouter, createWebHashHistory } from 'vue-router';
import LayoutView from '../layout/index.vue';
import LoginView from '../login/index.vue';
import { getToken } from '@/utils/storage/sessionToken';

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: LayoutView,
      redirect: '/project',
      children: [
        {
          path: '/project',
          component: () => import('@/views/project/index.vue'),
        },
        {
          path: '/certificate',
          component: () => import('@/views/certificate/index.vue'),
        },
        {
          path: '/scheme',
          component: () => import('@/views/scheme/index.vue'),
        },
        {
          path: '/equipment',
          component: () => import('@/views/equipment/index.vue'),
        },
        {
          path: '/data_source',
          component: () => import('@/views/data/source/index.vue'),
        },
        {
          path: '/data_edit',
          component: () => import('@/views/data/edit/index.vue'),
        },
        {
          path: '/data_checkout',
          component: () => import('@/views/data/checkout/index.vue'),
        },
        {
          path: '/report_create',
          component: () => import('@/views/report/create/index.vue'),
        },
        {
          path: '/report_audit',
          component: () => import('@/views/report/audit/index.vue'),
        },
      ],
    },
    {
      path: '/login',
      component: LoginView,
    },
  ],
});

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  const token = getToken();
  if (!token) {
    if (to.path === '/login') {
      next();
    } else {
      next('/login');
    }
  } else {
    if (to.path === '/login') {
      next('/');
    } else {
      next();
    }
  }
});

export default router;
