import { useRouter } from 'vue-router';
import type { RouteLocationRaw } from 'vue-router';
import type { RouteKey } from '@elegant-router/types';
import { router as globalRouter } from '@/router';

/**
 * Router push
 *
 * Jump to the specified route, it can replace function router.push
 *
 * @param inSetup Whether is in vue script setup
 */
export function useRouterPush(inSetup = true) {
  const router = inSetup ? useRouter() : globalRouter;
  const route = globalRouter.currentRoute;

  const routerPush = router.push;

  const routerBack = router.back;

  interface RouterPushOptions {
    query?: Record<string, string>;
    params?: Record<string, string>;
  }

  async function routerPushByKey(key: RouteKey, options?: RouterPushOptions) {
    const { query, params } = options || {};

    const routeLocation: RouteLocationRaw = {
      name: key
    };

    if (Object.keys(query || {}).length) {
      routeLocation.query = query;
    }

    if (Object.keys(params || {}).length) {
      routeLocation.params = params;
    }

    return routerPush(routeLocation);
  }

  function routerPushByKeyWithMetaQuery(key: RouteKey) {

    const allRoutes = router.getRoutes();

    // 获取所有路由
    const routes = router.getRoutes();

    // 查找并拷贝目标路由对象
    // eslint-disable-next-line @typescript-eslint/no-shadow
    const targetRoute = routes.find(route => route.name === key);
    let newRoute = null;

    if (targetRoute) {
      newRoute = { ...targetRoute }; // 浅拷贝旧路由对象

      // // 修改目标字段
      // newRoute.meta.requiresAuth = true; // 修改 meta.requiresAuth 字段
      // newRoute.props.default.url = 'www.baidu.com';       // 修改 path 字段
    }

    // 移除旧的路由并添加修改后的路由
    if (targetRoute) {
      // router.removeRoute(targetRoute.name); // 移除旧路由
    }

    if (newRoute) {
      // router.addRoute(newRoute); // 添加修改后的路由
    }
    const meta = allRoutes.find(item => item.name === key)?.meta || null;
    // console.log('routerPushByKeyWithMetaQuery1', router);
    // console.log('routerPushByKeyWithMetaQuery', route);
    const query: Record<string, string> = {};

    meta?.query?.forEach(item => {
      query[item.key] = item.value;
    });

    return routerPushByKey(key, { query });
  }

  async function toHome() {
    return routerPushByKey('root');
  }

  /**
   * Navigate to login page
   *
   * @param loginModule The login module
   * @param redirectUrl The redirect url, if not specified, it will be the current route fullPath
   */
  async function toLogin(loginModule?: UnionKey.LoginModule, redirectUrl?: string) {
    const module = loginModule || 'pwd-login';

    const options: RouterPushOptions = {
      params: {
        module
      }
    };

    const redirect = redirectUrl || route.value.fullPath;

    options.query = {
      redirect
    };

    return routerPushByKey('login', options);
  }

  /**
   * Toggle login module
   *
   * @param module
   */
  async function toggleLoginModule(module: UnionKey.LoginModule) {
    const query = route.value.query as Record<string, string>;

    return routerPushByKey('login', { query, params: { module } });
  }

  /** Redirect from login */
  async function redirectFromLogin() {
    const redirect = route.value.query?.redirect as string;

    if (redirect) {
      routerPush(redirect);
    } else {
      toHome();
    }
  }

  return {
    routerPush,
    routerBack,
    routerPushByKey,
    routerPushByKeyWithMetaQuery,
    toLogin,
    toggleLoginModule,
    redirectFromLogin
  };
}
