import type { AppRouteRecordRaw, AppRouteModule } from '@/router/types';

import { PAGE_NOT_FOUND_ROUTE, REDIRECT_ROUTE } from '@/router/routes/basic';
import { LAYOUT } from '@/router/constant';

import { mainOutRoutes } from './mainOut';
import { PageEnum } from '@/enums/pageEnum';
import { t } from '@/hooks/web/useI18n';
import { projectRoutes, chartRoutes, previewRoutes, editRoutes } from '@/router/disposition/index';
import { router } from '@/router';
import { usePermissionStore } from '@/store/modules/permission';
import { getMainPage } from '@/api/path/project.api';

// import.meta.glob() 直接引入所有的模块 Vite 独有的功能
const modules = import.meta.glob('./modules/**/*.ts', { eager: true });
const routeModuleList: AppRouteModule[] = [];

// 加入到路由集合中
Object.keys(modules).forEach((key) => {
  const mod = (modules as Recordable)[key].default || {};
  if (mod.meta) {
    const modList = Array.isArray(mod) ? [...mod] : [mod];
    routeModuleList.push(...modList);
  }
});

export const asyncRoutes = [
  PAGE_NOT_FOUND_ROUTE,
  ...routeModuleList,
  projectRoutes,
  chartRoutes,
  previewRoutes,
  editRoutes,
];

// 根路由
export const RootRoute: AppRouteRecordRaw = {
  path: '/',
  name: 'Root',
  redirect: PageEnum.BASE_HOME,
  meta: {
    title: 'Root',
  },
  // beforeEnter: async (to, from, next) => {
  //   const mainPage = await getMainPage();
  //   console.log('to', to);
  //   console.log('from', from);
  //   if (to.fullPath == '/') {
  //     console.log('进入重定向');
  //     if (mainPage) {
  //       console.log('设置了主页');
  //       console.log('mainPage', mainPage);
  //       // window.open(
  //       //   'http://192.168.10.120:5173/#/chart/preview/f0adeb4b-8f11-4cbb-84e3-7e03de472a7b',
  //       //   '_self',
  //       // );
  //       window.location.replace(
  //         'http://192.168.10.120:5173/#/chart/preview/f0adeb4b-8f11-4cbb-84e3-7e03de472a7b',
  //       );
  //       // window.location.href = mainPage;
  //     } else {
  //       next();
  //     }
  //   } else {
  //     next();
  //   }
  // },
};

export const LoginRoute: AppRouteRecordRaw = {
  path: '/login',
  name: 'Login',
  // component: () => import('@/views/sys/login/Login.vue'),
  component: () => import('@/views/sys/login/Login.vue'),
  meta: {
    title: t('routes.basic.login'),
  },
};
// Basic routing without permission
// 未经许可的基本路由
export const basicRoutes = [
  LoginRoute,
  RootRoute,
  ...mainOutRoutes,
  REDIRECT_ROUTE,
  PAGE_NOT_FOUND_ROUTE,
];
