import { createRouter, createWebHistory, RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
import { getStore } from '@/utils/storage'
import addRoutes from './util'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: '登录',
    component: () => import('@/pages/login/index.vue')
  },
  {
    path: '/',
    name: '首页',
    component: () => import('@/pages/index/index.vue'),
    children: [
      {
        path: '/',
        meta: {
          keepAlive: true
        },
        component: () => import('@/pages/home/index.vue')
      },
      {
        path: '/user/info',
        name: '个人中心',
        component: () => import('@/views/upms/user/info/index.vue'),
        children: [
          {
            path: '/user/info',
            name: '个人信息',
            component: () => import('@/views/upms/user/info/info.vue')
          },
          {
            path: '/user/info/password',
            name: '修改密码',
            component: () => import('@/views/upms/user/info/pwd.vue')
          }
        ]
      },
      {
        path: '/404',
        name: '页面未找到',
        component: () => import('@/pages/common/404.vue')
      }
    ]
  },
  { path: '/:pathMatch(.*)*', redirect: '/404' }
]

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

// 赋值标题
router.beforeEach((to: RouteLocationNormalized, from, next) => {
  if (to.name) {
    document.title = `${String(to.meta.name ? to.meta.name : to.name)} - FxBoot`
  } else {
    document.title = 'FxBoot'
  }
  // if (getStore('token') || to.fullPath === '/login') {
  //   next()
  // } else {
  //   next('/login')
  // }
  next()
})
// 若有缓存，直接设置
const menus = getStore('menus')
if (menus) {
  addRoutes(menus, router)
}
export default router
