import { getMenuData } from '@/Project/services/platformMenu';
import { queryCurrentV2 } from '@/Project/services/user';

const filterWaterMenuData = (menuData) => {
  if (!menuData) {
    return [];
  }
  var arr = [];
  menuData.forEach((item) => {
    if (item.Type != 1) return;
    arr.push(item);
    if (item.children) {
      let newChildren = filterWaterMenuData(item.children);
      item.children = newChildren.length == 0 ? null : newChildren;
    }
  });
  return arr;
};

export default {
  namespace: 'menu',
  state: {},

  effects: {
    *getPlatformMenu({ callback, payload }, { put, call }) {
      const allMenu = yield call(getMenuData, payload);
      const response = yield call(queryCurrentV2);
      let permission = {};
      if (response && allMenu) {
        for (let i = 0; i < response?.data?.Permissions?.length; i++) {
          let item = response.data.Permissions[i];
          if (!item.Menus || typeof item.Menus != 'object') return;
          permission = {
            ...permission,
            ...item.Menus,
          };
        }
        let menu = allMenu.data?.list.find((item) => item.MenuType == 0) || {};
        menu.children = filterWaterMenuData(menu.children);
        callback?.(menu, permission);
      }
    },
  },

  reducers: {},
};
