import { findRouteName } from 't-comm/lib/router/find-route-name';

import { getGuruNamespace } from './namespace';
import { getAllRoutes, isInGuru } from './routes';

import type { IRouter, IGuruItem } from './types';


export function interceptRouterInMp({
  router,

  guruList,
  defaultNamespace = 'convert-cross',
}: {
  router: IRouter;

  guruList: Array<IGuruItem>;
  defaultNamespace?: string;
}) {
  if (!isInGuru()) {
    return;
  }

  hookRouterInMp({
    router,
    method: 'push',
    type: 'navigateTo',

    guruList,
    defaultNamespace,
  });

  hookRouterInMp({
    router,
    method: 'replace',
    type: 'redirectTo',

    guruList,
    defaultNamespace,
  });
}


function hookRouterInMp({
  router,
  method,
  type,

  guruList,
  defaultNamespace,
}: {
  router: IRouter;
  method: string;
  type: 'navigateTo' | 'redirectTo';

  guruList: Array<IGuruItem>;
  defaultNamespace?: string;
}) {
  const routes = getAllRoutes();
  let pushing = false;

  router[method] = function (...args: any) {
    console.log('.... pushing', args);
    const { path: rawPath, other } = getRouterFuncPath(args[0]);
    if (pushing) return;
    pushing = true;

    console.log('rawPath', rawPath, other);

    const query = other?.query || {};


    const queryStr = Object.keys(query || {})
      .map(key => `${key}=${encodeURIComponent(query[key])}`)
      .join('&');

    if (rawPath) {
      const option = findRouteName(rawPath, routes);
      console.log('findRouteName.option', option);

      if (!option?.path) {
        (wx[type] as any)({
          url: `${rawPath}${queryStr ? `${rawPath.includes('?') ? '&' : '?'}${queryStr}` : ''}`,
          fail(res: any) {
            console.error('navigateToFail: ', res);
            pushing = false;
          },
          success() {
            pushing = false;
          },
        });
        return;
      }

      const namespace = getGuruNamespace({
        path: option.path,
        guruList,
        defaultNamespace,
      });
      console.log('namespace', namespace);

      const optionPath = option.path;

      (wx[type] as any)({
        url: `/${namespace}${optionPath.startsWith('/') ? optionPath
          : `/${optionPath}`}${queryStr ? `?${queryStr}` : ''}`,
        fail(res: any) {
          console.error('navigateToFail: ', res);
          pushing = false;
        },
        success() {
          pushing = false;
        },
      });
      return;
    }

    pushing = false;
    console.error('路由解析失败，请使用 path、query 模式');
  };
}


function getRouterFuncPath(route: any) {
  let rawPath;
  let rawOther: Record<string, any> = {};

  if (typeof route === 'object' && route.path) {
    rawPath = route.path;
    const { path, ...other } = route;
    rawOther = other;
  } else if (typeof route === 'string') {
    rawPath = route;
  }

  return {
    path: rawPath,
    other: rawOther,
  };
}


