import { createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { useLoginStore } from '@/stores'
import service from '@/services'
import Page from '@mobile/components/layouts/page/index.vue'
import animateRouter from './animateRouter'

const { getToken } = useLoginStore()

const routes: Array<RouteRecordRaw> = [
  {
    path: '/:pathMatch(.*)*',
    name: 'error',
    component: () => import('../views/error/404.vue')
  },
  {
    path: '/boot',
    name: 'boot',
    component: () => import('../views/boot/index.vue')
  },
  {
    path: '/',
    component: Page,
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('../views/home/index.vue'),
        meta: {
          requireAuth: true,
        },
      }
    ]
  },
  {
    path: '/login',
    component: Page,
    children: [
      {
        path: '',
        name: 'login',
        component: () => import('../views/sign/login/index.vue'),
      }
    ]
  },
  {
    path: '/order',
    component: Page,
    children: [
      {
        path: '',
        name: 'order',
        component: () => import('../views/order/index/index.vue'),
      },
      {
        path: 'detail',
        name: 'orderDetail',
        component: () => import('../views/order/detail/index.vue'),
      }
    ]
  },
]

const router = animateRouter.create({
  history: createWebHashHistory(),
  routes
})

// 路由跳转拦截
router.beforeEach((to, from, next) => {
  // 判断服务是否加载完成
  if (service.isReady) {
    if (to.meta.requireAuth && !getToken()) {
      next({
        name: 'login',
        query: { redirect: to.fullPath },
      });
    } else {
      next();
    }
  } else {
    if (to.name === 'boot') {
      next();
    } else {
      next({
        name: 'boot',
        query: { redirect: to.fullPath },
      });
    }
  }
})

export default router
