import { CommonController } from '../services';
import { DEFAULT_APP_NAME } from '../constants';
import { getListFromTree, getTreeFromList } from './tree';
import { sessionStore } from './store';
import { pathHolder } from './route';

export async function getAppIdHolder() {
  const appList = await CommonController.getAppListApi();
  const { appId } =
    appList.find((item) => item.appNameEn === DEFAULT_APP_NAME) || {};
  return appId;
}

export async function getMenuHolder(appId: string, groupName: string) {
  let _menuList = await CommonController.getMenuListApi(appId);

  if (groupName) {
    const { children } =
      (_menuList || []).find((item) => item.menuName === groupName) || {};
    _menuList = children || [];
  }
  const menuList = getListFromTree(_menuList || []).map((item) => {
    const { menuName: name, menuId: key, path: _path, icon, parentId } = item;
    const path = pathHolder(_path);
    return {
      name,
      key,
      path,
      icon,
      parentId,
    };
  });
  const menuTreeList = getTreeFromList(menuList, {
    idKey: 'key',
    parentIdKey: 'parentId',
  });
  const authorizedRouteList = menuList
    .filter((item) => item.path)
    .map(({ path, name }) => {
      return { path, name };
    });
  sessionStore.set('menu-tree-list', menuTreeList);
  sessionStore.set('authorized-route-list', authorizedRouteList);
  return _menuList;
}

export async function getButtonHolder(appId: string) {
  const buttonList = await CommonController.getButtonListApi(appId);
  sessionStore.set('button-list', buttonList);
  return buttonList;
}
