import {TreeRoleMenuData} from '@models';

export type ParseMenuType = {
  key: string,
  title: string,
  label: string,
  pid: string;
  url: string;
  children?: ParseMenuType[],
};

export function sortMenu(menus: TreeRoleMenuData[]) {
  const topMenu: ParseMenuType[] = [],
        childMenu: ParseMenuType[] = [];

  // 拆分一级菜单和二级菜单
  menus.forEach(function({id, pId, name, url}) {
    const data = {key: id, title: name, label: name, pid: pId, url};

    pId === '0'
      ? topMenu.push(data)
      : childMenu.push(data);
  });

  // 填充一级菜单
  childMenu.forEach(function(data) {
    const index = topMenu.findIndex(val => val.key === data.pid);
    topMenu[index]?.children
      ? topMenu[index]!.children!.push(data)
      : topMenu[index] = {...topMenu[index], children: [data]};
  });

  return topMenu;
}
