/**
 * @description 使用递归扁平化菜单，方便添加动态路由
 * @param {Array} menuList 菜单列表
 * @returns {Array}
 */
export function getFlatMenuList(menuList) {
  let newMenuList = JSON.parse(JSON.stringify(menuList));
  return newMenuList.flatMap((item) => [
    item,
    ...(item.children ? getFlatMenuList(item.children) : []),
  ]);
}

/**
 * @description 使用递归过滤出需要渲染在左侧菜单的列表 (需剔除 isHide == true 的菜单)
 * @param {Array} menuList 菜单列表
 * @returns {Array}
 * */
export function getShowMenuList(menuList) {
  let newMenuList = JSON.parse(JSON.stringify(menuList));

  return newMenuList.filter((item) => {
    item.children?.length && (item.children = getShowMenuList(item.children));
    return !item.meta?.isHide;
  });
}

/**
 * @description 使用递归找出所有面包屑存储到 pinia/vuex 中
 * @param {Array} menuList 菜单列表
 * @param {Array} parent 父级菜单
 * @param {Object} result 处理后的结果
 * @returns {Object}
 */
export const getAllBreadcrumbList = (menuList, parent = [], result = {}) => {
  for (const item of menuList) {
    result[item.path] = [...parent, item];
    if (item.children) getAllBreadcrumbList(item.children, result[item.path], result);
  }
  return result;
};

/**
 * 通过全部菜单匹配用户的扁平菜单
 * @param {*} menus 菜单列表
 * @param {*} userMenus 用户菜单
 * @param {*} menu 处理后的菜单
 * @returns
 */
export function filterMenu(menus, userMenus, menu = []) {
  if (!menus?.length) return menu;
  menus.forEach((m) => {
    if (userMenus.find((v) => v.id === m.id)) {
      const target = {
        path: m.path,
        name: m.name,
        redirect: m.redirect,
        component: m.component,
        meta: {
          icon: m.icon,
          title: m.title,
          isLink: m.link,
          isHide: m.hide === 'Y',
          isFull: m.full === 'Y',
          isAffix: m.affix === 'Y',
          isKeepAlive: m.keepAlive == 'Y',
          activeMenu: m.activeMenu,
        },
      };
      menu.push(target);
      if (m.children?.length) {
        target.children = filterMenu(m.children, userMenus, []);
      }
    }
  });
  return menu;
}
