import useMainStore from '@/store/useMainStore';
import {
  createRouter,
  createWebHashHistory,
  RouteLocation,
  RouteRecordRaw,
} from 'vue-router';
import NProgress from 'nprogress';
import { BaseLoginUrl } from '@/constants/constants';

const BaseLayout = () =>
  import(/* webpackChunkName: "BaseLayout" */ '@/layout/BaseLayout');

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Home',
    component: BaseLayout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: () =>
          import(/* webpackChunkName: "home.page" */ '@/views/HomePage'),
        name: '首页',
        meta: { title: '首页' },
      },
      {
        path: 'incidentDetail',
        component: () =>
          import(/* webpackChunkName: "home.page" */ '@/views/IncidentDetail'),
        name: '事件详情',
        meta: { title: '事件详情' },
      },
    ],
  },

  {
    path: '/:pathMatch(.*)*',
    name: 'All',
    redirect: (to: RouteLocation) => {
      return { path: '/404', query: { from: to.path } };
    },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 };
  },
});

router.beforeEach(() => {
  NProgress.start();
  const main = useMainStore();
  main.clearReqToken();
});
router.beforeEach(async (to, from) => {
  NProgress.start();

  const main = useMainStore();

  if (!to.query.ticket && !window.localStorage.getItem('Authorization')) {
    window.location.href = BaseLoginUrl;
    return false;
  }
  if (to.query.ticket) { 
    main.removeToken();
    return await main.getUserInfo(to.query.ticket as string);
  }
  if (to.query.ticket && !window.localStorage.getItem('Authorization')) {
      return await main.getUserInfo(to.query.ticket as string);
  }

  main.clearReqToken();
  return true;
});
router.afterEach((to) => {
  NProgress.done();
  document!.title = to.meta.title
    ? to?.meta?.title + ' - 交通运输应急指挥系统'
    : '交通运输应急指挥系统';
});

export default router;
