import {
  createRouter,
  createWebHistory,
  RouteRecordRaw,
  createWebHashHistory,
  Router,
} from 'vue-router'
import Home from '@/views/home2/Home.vue'
// 扩展继承属性
interface extendRoute {
  hidden?: boolean
}

//
import uCardRoute from './modules/uCard'
import userRoute from '@/routers/modules/user'
import systemRoute from '@/routers/modules/system'

/**
 * path ==> 路由路径
 * name ==> 路由名称
 * component ==> 路由组件
 * redirect ==> 路由重定向
 * alwaysShow ==> 如果设置为true，将始终显示根菜单，无论其子路由长度如何
 * hidden ==> 如果“hidden:true”不会显示在侧边栏中（默认值为false）
 * keepAlive ==> 设为true 缓存
 * meta ==> 路由元信息
 * meta.title ==> 路由标题
 * meta.icon ==> 菜单icon
 * meta.affix ==> 如果设置为true将会出现在 标签栏中
 * meta.breadcrumb ==> 如果设置为false，该项将隐藏在breadcrumb中（默认值为true）
 * meta.activeMenu ==> 详情页的时候可以设置菜单高亮 ,高亮菜单的path
 */

export const constantRoutes: Array<RouteRecordRaw & extendRoute> = [
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/errorPages/404.vue'),
    hidden: true,
  },
  {
    path: '/403',
    name: '403',
    component: () => import('@/views/errorPages/403.vue'),
    hidden: true,
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/User.vue'),
    hidden: true,
    children: [
      {
        path: '/signin',
        name: 'SignIn',
        meta: { title: 'login', icon: 'House' },
        component: () => import('@/views/login/index.vue'),
        hidden: true,
      },
      {
        path: '/forget',
        name: 'Forget',
        component: () => import('@/views/login/Forget.vue'),
        hidden: true,
      },
    ],
  },
  {
    path: '/',
    name: '',
    component: Home,
    // redirect: '/card/order',
    meta: {
      OnBreadCrumb: false,
      requiresAuth: true,
    },
    children: [systemRoute, uCardRoute, userRoute],
  },
]

/**
 * notFoundRouter(找不到路由)
 */
export const notFoundRouter = {
  path: '/:pathMatch(.*)',
  name: 'notFound',
  redirect: '/404',
}

const router = createRouter({
  // history: createWebHistory(process.env.BASE_URL), // history
  history: createWebHashHistory(), // hash
  routes: constantRoutes,
})

function loggedIn() {
  // return true
  if (sessionStorage.getItem('user')) {
    return true
  } else {
    return false
  }
}

router.beforeEach((to, from, next) => {
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!loggedIn()) {
      next({
        path: '/signin',
        // query: { redirect: to.fullPath }
      })
    } else {
      if (to.path == '/') {
        next({
          path: '/',
        })
      } else {
        next()
      }
    }
  } else {
    next()
  }
})

export default router
