import type { RouteRecordRaw } from 'vue-router';
import type { App } from 'vue';

import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
import { basicRoutes } from './routes';

// 白名单应该包含基本静态路由
const WHITE_NAME_LIST: string[] = [];
const getRouteNames = (array: any[]) =>
  array.forEach((item) => {
    WHITE_NAME_LIST.push(item.name);
    getRouteNames(item.children || []);
  });
getRouteNames(basicRoutes);

// app router
export const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  routes: basicRoutes as unknown as RouteRecordRaw[],
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

// TODO 【QQYUN-4517】【表单设计器】记录分享路由守卫测试
router.beforeEach(async (to, from, next) => {
  let title = '默认标题'; // 默认标题
  // 根据域名设置不同标题
  if (window.location.hostname.includes('sohoeb2b')) {
    title = '苏豪通';
  } else {
    title = 'AdWeb V3';
  }

  // 如果路由配置中有自定义标题，优先使用路由配置的标题
  if (to.meta && to.meta.title) {
    title = to.meta.title;
  }

  // 修改页面标题
  document.title = title;

  // 动态设置 Open Graph 标签
  const setMetaTag = (property, content) => {
    let meta = document.querySelector(`meta[property="${property}"]`);
    if (!meta) {
      meta = document.createElement('meta');
      meta.setAttribute('property', property);
      document.head.appendChild(meta);
    }
    meta.setAttribute('content', content);
  };

  setMetaTag('og:title', title);
  setMetaTag('og:description', `${title}是一个强大的企业管理平台`);
  setMetaTag('og:image', 'https://v3.sohoeb2b.com/logo.png');
  setMetaTag('og:url', window.location.href);
  next();
});

// reset router
export function resetRouter() {
  router.getRoutes().forEach((route) => {
    const { name } = route;
    if (name && !WHITE_NAME_LIST.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name);
    }
  });
}

// config router
export function setupRouter(app: App<Element>) {
  app.use(router);
}
