import { SysMenuInfo } from "../model/SysMenuInfo";
import { NavMenu } from "../model/NavMenu";
import { MenuType } from "../constants/enum/menu-type.enum";

export class MenuTreeConvertService {
  /**
   * @description: 菜单转换
   * @author ChenRui
   * @date 2020/9/3 0:46
   */
  menuToTree(sysMenuInfos: SysMenuInfo[] = []): SysMenuInfo[] {
    const sysMenuInfosRes: SysMenuInfo[] = [];
    sysMenuInfos.forEach((item) => {
      if (!item.menuSupId) {
        sysMenuInfosRes.push(this.recursiveAcquisitionOfSubnodes(item, sysMenuInfos));
      }
    });
    return sysMenuInfosRes;
  }

  /**
   * @description: 树结构递归转换
   * @author ChenRui
   * @date 2020/9/3 0:47
   */
  recursiveAcquisitionOfSubnodes(sysMenuInfoIt: SysMenuInfo, sysMenuInfos: SysMenuInfo[]): SysMenuInfo {
    sysMenuInfoIt.children = [];
    for (const sysMenuInfo of sysMenuInfos) {
      if (sysMenuInfoIt.menuId === sysMenuInfo.menuSupId) {
        sysMenuInfoIt.children.push(this.recursiveAcquisitionOfSubnodes(sysMenuInfo, sysMenuInfos));
      }
    }
    return sysMenuInfoIt;
  }

  /**
   * @description: 菜单模型转换自定义模型
   * @author ChenRui
   * @date 2020/9/3 0:57
   */
  menuToNavMenu(sysMenuInfosSource: SysMenuInfo[]): NavMenu[] {
    const sysMenuInfos: SysMenuInfo[] = this.menuToTree(sysMenuInfosSource);
    const navMenus: NavMenu[] = this.recursionMenuToNavMenu(sysMenuInfos);
    return navMenus;
  }

  /**
   * @description: 菜单对象递归转换
   * @author ChenRui
   * @date 2020/9/3 0:56
   */
  recursionMenuToNavMenu(sysMenuInfos: SysMenuInfo[]): NavMenu[] {
    let navMenus: NavMenu[] = [];
    sysMenuInfos.forEach((val) => {
      const navMenu: NavMenu = {
        key: val.menuId,
        title: val.menuName,
        icon: val.menuIcon,
        url: val.menuUrl,
        activate: false,
        type: MenuType.MENU.code,
        order: val.sortNo,
      };
      if (!!val.children && val.children.length > 0) {
        navMenu.type = MenuType.BUTTON.code;
        navMenu.children = this.recursionMenuToNavMenu(val.children);
      }
      navMenus.push(navMenu);
    });
    navMenus = navMenus.sort((a, b) => (a.order || 999) - (b.order || 999));
    return navMenus;
  }
}
const menuTreeConvertService: MenuTreeConvertService = new MenuTreeConvertService();
export { menuTreeConvertService };
