import component, { childThirdRoutes } from "@/config/component";

/* eslint-disable */
const getRouteItem = (arrList, queryItem) => {
  let result;
  if (Array.isArray(arrList)) {
    result = arrList.find(
      (item) => item.path === queryItem || getRouteItem(item.children, queryItem),
    );
  }
  return result;
};

const getRouteList = (result, arrList, queryItem) => {
  if (Array.isArray(arrList)) {
    arrList.forEach((item) => {
      if (item.path === queryItem) {
        result.push({
          path: item.path,
          key: item.key,
          name: item.meta.title,
          isSubMenu: item.isSubMenu,
        });
      } else {
        result.push({
          path: item.path,
          key: item.key,
          name: item.meta.title,
          isSubMenu: item.isSubMenu,
        });
        getRouteList(
          result,
          getRouteItem(item.children, queryItem) ? [getRouteItem(item.children, queryItem)] : [],
          queryItem,
        );
      }
    });
  }
  return result;
};

const generateToAntdMenus = (data, title = 'title', path = 'path', children = 'children', depth = 1) => {
  return data.map(item => {
    const componentPath = component.filter((citem) => citem.key == item[path]);
    const newItem = {
      title: item[title],
      type: item.type,
      path: item[path],
      icon: item.icon || "",
      name: componentPath[0].name,
      component: componentPath[0].component,
      isChild: componentPath[0].isChild
    };

    if (componentPath[0].isChild) {
      newItem.children = childThirdRoutes[item[path]];
    }

    if (depth < 2 && item[children] && item[children].length > 0) {
      newItem.children = generateToAntdMenus(item[children], title, path, children, depth + 1);
    }
    return newItem;
  });
};

// 判断是否有用该操作权限
const hasPermission = (permissionList, permission)  => {
  const checkPermission = (list, id) => {
    for (const item of list) {
      // 如果当前项的id与权限标识匹配，返回true
      if (item.id === id) {
        return true;
      }
      // 如果当前项有子权限，递归检查子权限
      if (item.children && item.children.length > 0) {
        const hasChildPermission = checkPermission(item.children, id);
        if (hasChildPermission) {
          return true;
        }
      }
    }
    // 如果遍历完列表都没有找到匹配的权限标识，返回false
    return false;
  };
  // 调用递归函数，传入权限列表和权限标识
  return checkPermission(permissionList, permission);
}

export { getRouteItem, getRouteList, generateToAntdMenus, hasPermission};
