import NProgress from 'accessible-nprogress'; // progress bar
import 'accessible-nprogress/dist/accessible-nprogress.min.css'; // 页面顶部进度条
import { notHeadRoute } from './router';
import router from '@/router/router';

/**
 * 注册路由守卫
 */
export function useRouterGuard(): void {
  NProgress.configure({ showSpinner: false });

  // 前置守卫
  router.beforeEach((to) => {
    if (import.meta.env.DEV) {
      if (to.path.toLowerCase() !== to.path) {
        console.warn(`${to.path}路径包含大写建议改为小写`);
      }
    }
    // 显示顶部进度条
    // oxlint-disable-next-line no-unused-expressions
    !notHeadRoute.includes(to.path) && NProgress.start();
    // 设置title
    document.title = getPageTitle(String(to.meta?.title || ''));
    return true;
  });

  // 后置守卫
  router.afterEach(() => {
    NProgress.done();
  });

  // 版本更新后自动刷新
  router.onError((error) => {
    console.error('error====', error);
    const isChunkLoadFailed = error.message.match(/Loading chunk (\d)+ failed/g);
    if (isChunkLoadFailed) {
      window.location.reload();
    }
  });
}

/**
 * 得到页面的标题
 */
export function getPageTitle(title: string) {
  if (title) {
    return `${title} - 行知云校`;
  }
  return `行知云校`;
}
