/*
 * @Author: wfl
 * @LastEditors: wfl
 * @description:
 * @updateInfo:
 * @Date: 2022-08-12 18:42:51
 * @LastEditTime: 2022-10-08 14:15:58
 */
import type { RouteLocationRaw, Router } from 'vue-router';

import { PageEnum } from '@/global/enums/pageEnum';
import { ikStore, paramType } from 'iking-utils';
import { unref } from 'vue';

import { REDIRECT_NAME } from '@/mainApp/router/constant';
import { useRouter } from 'vue-router';

export type RouteLocationRawEx = Omit<RouteLocationRaw, 'path'> & { path: PageEnum };

function handleError(e: Error) {
  console.error(e);
}

// page switch
export function useGo(_router?: Router) {
  let router;
  if (!_router) {
    router = useRouter();
  }
  const { push, replace } = _router || router;
  async function go(
    opt: PageEnum | RouteLocationRawEx | string = PageEnum.BASE_HOME,
    isReplace = false,
  ) {
    if (!opt) {
      return;
    }
    const menus: any = (await ikStore.forage.getItem('menu')) || [];
    const me = menus?.find((m) => [m.__nodekey, m.path].includes(opt));
    if (!me) {
      push(opt).catch(handleError);
      return;
    }
    if (paramType.isString(me?.path)) {
      isReplace ? replace(me?.path).catch(handleError) : push(me.path).catch(handleError);
    } else {
      const o = me?.path as RouteLocationRaw;
      isReplace ? replace(o).catch(handleError) : push(o).catch(handleError);
    }
  }
  return go;
}

/**
 * @description: redo current page
 */
export const useRedo = (_router?: Router) => {
  const { push, currentRoute } = _router || useRouter();
  const { query, params = {}, name, fullPath } = unref(currentRoute.value);
  function redo(): Promise<boolean> {
    return new Promise((resolve) => {
      if (name === REDIRECT_NAME) {
        resolve(false);
        return;
      }
      if (name && Object.keys(params).length > 0) {
        params['_redirect_type'] = 'name';
        params['path'] = String(name);
      } else {
        params['_redirect_type'] = 'path';
        params['path'] = fullPath;
      }
      push({ name: REDIRECT_NAME, params, query }).then(() => resolve(true));
    });
  }
  return redo;
};
