import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from 'vue-router';
import NProgress from 'nprogress';
import { useUserStore } from '@/store';
import { clear } from '@/utils/tool';
import 'nprogress/nprogress.css';

import routes from './routes';

const title = import.meta.env.VITE_APP_TITLE;
const defaultRoutePath = '/';
const whiteRoutes = ['Login'];

const { VITE_HASH_ROUTE = 'N' } = import.meta.env;

const router = createRouter({
  // history: createWebHashHistory(),
  history:
    VITE_HASH_ROUTE === 'Y' ? createWebHashHistory() : createWebHistory(),
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const userStore = useUserStore();
  const toTitle = to.meta.title ? to.meta.title : to.name;
  document.title = `${toTitle} - ${title}`;
  // const token = local.get(import.meta.env.VITE_APP_TOKEN_PREFIX);
  if (whiteRoutes.includes(to.name)) {
    if (to.name === 'Login') {
      clear();
      userStore.resetUserInfo();
    }
    next();
    return;
  }
  // 登录状态下
  if (userStore.user) {
    // if (to.name === 'Login') {
    //   next({ path: defaultRoutePath });
    //   return;
    // }
    if (!userStore.routers) {
      const data = await userStore.requestUserMenu();
      if (!data) {
        clear();
        next(
          to.fullPath === '/'
            ? { name: 'Login' }
            : { name: 'Login', query: { redirect: to.fullPath } }
        );
      } else {
        next({ path: to.path, query: to.query });
      }
    } else {
      next();
    }
  } else {
    next(
      to.fullPath === '/'
        ? { name: 'Login' }
        : { name: 'Login', query: { redirect: to.fullPath } }
    );
  }
});

router.afterEach((to, from) => {
  NProgress.done();
});

router.onError((error) => {
  console.log(error);
  NProgress.done();
});

export default router;
