import { createRouter, createWebHistory } from 'vue-router'
import { usePermissionStore } from '@/stores/permission'

export const constantRoutes  = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/components/layouts/defaultLayout.vue'),
    meta: { 
      requiresAuth: true,
      title: '首页',
      icon: 'House'
    },
  },
  // {
  //   path: '/personnePostPhysicalExamination',
  //   name: 'personnePostPhysicalExamination',
  //   meta: { 
  //     requiresAuth: true,
  //     title: '人员岗前体检',
  //     icon: 'User'
  //   },
  //   component: () => import('@/components/layouts/defaultLayout.vue')
  // },
  // {
  //   path: '/personnelHealthMonitoring',
  //   name: 'personnelHealthMonitoring',
  //   meta: { 
  //     requiresAuth: true,
  //     title: '人员岗前体检',
  //     icon: 'User'
  //   },
  //   component: () => import('@/components/layouts/defaultLayout.vue')
  // },
  {
    path: '/404',
    name: '404',
    meta: {
      title: '404',
      hidden: true,
      noTab: true
    },
    component: () => import('@/views/error/404.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404',
    hidden: true
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
})

export function resetRouter() {
  const newRouter = createRouter({
    history: createWebHistory(),
    routes: constantRoutes
  })
  router.matcher = newRouter.matcher
}



// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = sessionStorage.getItem('token')
  if (!token) {
    window.open(import.meta.env.VITE_HOME_URL, '_self');
    return false
  }

  // 获取权限store
  const permissionStore = usePermissionStore()
  //permissionStore.generateRoutes()

  // 如果路由还没有生成，先生成路由
  if (!permissionStore.isRoutesGenerated) {
    try {
      await permissionStore.generateRoutes()
      // 重新进入当前路由
      if (to.path === '/404') {
        next('/home')
      } else {
        next({ ...to, replace: true })
      }
      return
    } catch (error) {
      console.error('Failed to generate routes:', error)
      next('/404')
      return
    }
  }

  // 检查路由是否存在
  if (to.matched.length === 0 && to.path !== '/404') {
    next('/404')
    return
  }

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (token) {
      next()
    } else {
      window.open(import.meta.env.VITE_HOME_URL, '_self');
    }
  } else {
    next()
  }
})

export default router
