import { Link } from "react-router-dom";

// 菜单是否显示
// 没有 meta 或者 meta.title 为空, 或者 meta.hideInMenu = true 的 都不显示
const isShow = (item) => item.meta && item.meta.title && !item.meta.hideInMenu;

const hasChildren = (list) => {
  if (!list || list.length < 1) return false;

  // 如果子元素全部都是不显示的, 说明子菜单不需要显示
  return list.filter((it) => !isShow(it)).length !== list.length;
};

const getPath = (parent, current = "") => {
  if (current.startsWith("/") || current.startsWith("http")) return current;
  return `${parent}/${current}`.replace(/\/\//g, "/");
};

export const getMenuItems = (routes = [], fullPath = "/") => {
  return routes
    .map((route) => {
      const path = getPath(fullPath, route.path);

      //
      if (!isShow(route)) return false;

      const children = hasChildren(route.children)
        ? getMenuItems(route.children, path)
        : false;

      const { target, title, menuType, ...left } = route.meta || {};
      // // const label = path.startsWith('http')
      // //   ? <a href={path} target="_blank">{title}</a>
      // //   : <Link to={path} target={target}>{title}</Link>;

      // // 坑爹 react-router v6 不支持 hash 路由的 target 跳转
      // const label =
      //   target === "_blank" ? (
      //     <a href={`${window.location.pathname}#${path}`} target={target}>
      //       {title}
      //     </a>
      //   ) : path.indexOf("http") === 0 ? (
      //     <a href={path} target="_blank">
      //       {title}
      //     </a>
      //   ) : (
      //     <Link to={path} target={target}>
      //       {title}
      //     </Link>
      //   );

      return Object.assign(
        {
          key: path,
          label:title,
          title,
          type: menuType,
          ...left,
        },
        children && { children }
      );
    })
    .filter(Boolean);
};
