import type { RouteRecordRaw } from 'vue-router';
import type { MenuDataItem } from '@/router/typing';
import type { RouteProps } from '@/components/base-layouts/typing';
import RouteView from '@/layouts/route-view.vue';
import { h, defineAsyncComponent } from 'vue';

export const filterMenu = (routes: MenuDataItem[]): RouteRecordRaw[] => {
  return routes.find(item => item.name === 'index')?.children || [];
};

const staticRoutes: Record<string, any> = {};

export function loadStaticRoutes(routers: RouteRecordRaw[] = []) {
  routers.forEach(route => {
    staticRoutes[route.path] = route;
  });
}

export function getRouteComponent(filePath = '') {
  return staticRoutes[filePath.toLowerCase()]?.component;
}

export const changeMenu = (originRoutes: any) => {
  if (Array.isArray(originRoutes)) {
    const routes: MenuDataItem[] = [];
    for (let i = 0; i < originRoutes.length; i++) {
      const item = originRoutes[i];
      const { children: _, ...iItem } = item;
      if (item.path == null) {
        continue;
      }

      // 获取filePath
      let filePath = item.filePath;
      // filePath没配置的时候如果有pageId则取固定页面，没有的话取path
      if (!filePath) {
        if (item.eventModal == 'page') {
          // 设置器解析地址
          filePath = '/page/page';
        } else if (item.eventModal == 'link') {
          // 微前端地址
          filePath = '/page/wujie';
        } else {
          filePath = item.path;
        }
      }
      // 如果是非末级的菜单，不引入页面，否则会报错
      if (item.children && item.children?.length > 0) {
        filePath = '';
      }
      const fItem: MenuDataItem = {
        name: item.name,
        path: item.path,
        redirect: item.redirect,
        meta: {
          id: item.id,
          // icon: 'hoteam-plus',
          // iconColor: '#f00',
          icon: item.iconName || '',
          iconColor: item.iconColor || '',
          title: item.text || '',
          keepAlive: item.keepalive,
          projectCode: item.projectCode || '',
          appId: item.appId || '',
          appCode: item.appCode || '',
          pageId: item.pageId || '',
          userId: item.userId || '', // getSchema需要用的用户id
          dsName: item.dsName || '',
          version: item.version || '',
          url: item.link || '',
        },
        extra: { ...iItem },
        component: item.redirect
          ? undefined
          : getRouteComponent(filePath)
          ? getRouteComponent(filePath)
          : getRouteComponent('/platform/NotFount/Index'),
        // item.parentId == undefined
        //   ? item.children && item.children.length > 0
        //     ? RouteView
        //     : // : h(RouteView, null, () => h(getRouteComponent(item.path)))
        //       h(
        //         RouteView,
        //         null,
        //         () => h(defineAsyncComponent(getRouteComponent(filePath))), //importPath ? importPath : item.path
        //       )
        //   : getRouteComponent(filePath),
      };
      //针对于隐藏子路由的逻辑处理
      fItem.meta.hideChildrenInMenu = item['hideChildren'] || false;
      fItem.meta.hideInMenu = item['hidden'] || false;
      if (item.children && item.children.length > 0) {
        const cRoutes = changeMenu(item.children);
        fItem['children'] = cRoutes;
      }
      routes.push(fItem);
    }
    return routes;
  } else {
    const routes: MenuDataItem[] = [];
    // 获取filePath
    let filePath = originRoutes.filePath;
    // filePath没配置的时候如果有pageId则取固定页面，没有的话取path
    if (!filePath) {
      if (originRoutes.pageId) {
        // 设置器解析地址
        filePath = '/page/page';
      } else if (originRoutes.link) {
        // 微前端地址
        filePath = '/page/wujie';
      } else {
        filePath = originRoutes.path;
      }
    }
    const { children: _, ...iItem } = originRoutes;
    const fItem: MenuDataItem = {
      id: originRoutes.id,
      name: originRoutes.name,
      path: originRoutes.path,
      redirect: originRoutes.redirect,
      meta: {
        // icon: originRoutes.iconName || '',
        title: originRoutes.text,
        keepAlive: false,
        pageId: originRoutes.pageId || '',
        userId: originRoutes.userId || '', // getSchema需要用的用户id
        url: originRoutes.link || '',
      },
      extra: { ...iItem },
      component: originRoutes.redirect
        ? undefined
        : getRouteComponent(filePath)
        ? getRouteComponent(filePath)
        : getRouteComponent('/platform/NotFount/Index'),
      // originRoutes.parentId == undefined
      //   ? originRoutes.children && originRoutes.children.length > 0
      //     ? RouteView
      //     : h(RouteView, null, () => h(defineAsyncComponent(getRouteComponent(filePath))))
      //   : getRouteComponent(filePath),
    };
    //针对于隐藏子路由的逻辑处理
    fItem.meta.hideChildrenInMenu = originRoutes['hideChildren'] || false;
    fItem.meta.hideInMenu = originRoutes['hidden'] || false;
    if (originRoutes.children && originRoutes.children.length > 0) {
      const cRoutes = changeMenu(originRoutes.children);
      fItem['children'] = cRoutes;
    }
    routes.push(fItem);
    return routes;
  }
};

interface MenuMap {
  parentKeys?: string[];
}
type MenuKeyMap = Record<string, MenuMap>;
interface MenuInfo {
  menus: RouteProps[];
  menuKeyMap: MenuKeyMap;
}
export const genMenuInfo = (routes: RouteRecordRaw[]): MenuInfo => {
  const menuKeyMap: MenuKeyMap = {};
  const getMenuInfo = (routes: RouteRecordRaw[], parentKeys: string[] = []): RouteProps[] => {
    return routes.map(route => {
      const currentRouter: RouteProps = {
        ...route,
      };
      menuKeyMap[currentRouter.path] = { parentKeys: parentKeys };
      if (route.meta?.hideChildrenInMenu) {
        route.children &&
          route.children
            .map(item => item.path)
            .forEach(
              value => (menuKeyMap[value] = { parentKeys: [...parentKeys, currentRouter.path] }),
            );
      }
      // 是否有子菜单，并递归处理
      if (route.children && route.children.length > 0 && !route.meta?.hideChildrenInMenu) {
        // Recursion
        currentRouter.children = getMenuInfo(route.children, [...parentKeys, currentRouter.path]);
      } else {
        currentRouter.children = undefined;
      }

      return currentRouter;
    });
  };
  const menus = getMenuInfo(routes);
  return {
    menus,
    menuKeyMap,
  };
};

export const getMenuFirstChildren = (menus: RouteProps[]) => {
  return menus.map(menu => {
    // eslint-disable-next-line
    const { children: _children, ...rest } = menu;
    return rest;
  });
};

export const findMenuChildren = (
  menus: RouteProps[] | undefined,
  key: string | symbol | undefined,
) => {
  return (menus && menus.find(item => item.name === key)?.children) || [];
};

export const getActiveId = (route: string[], path: string) => {
  for (let i = 0; i < route.length; i++) {
    if (route[i]?.path == path) {
      return route[i];
    }
    if (route[i]?.children && route[i]?.children.length) {
      const val = getActiveId(route[i].children, path);
      if (val) return val;
    }
  }
};
