/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-12-14 14:14:32
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-08-10 13:56:50
 * @FilePath: /BudgetManaSystem/src/access.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

interface MenuItem {
  function: any;
  path: string;
  name: string;
  children?: MenuItem[];
}

function findMenuItem(menu: MenuItem[], path: string): MenuItem | undefined {
  for (let i = 0; i < menu.length; i++) {
    if (menu[i].path === path) {
      return menu[i];
    } else if (menu[i].children) {
      let found = findMenuItem(menu[i].children as MenuItem[], path);
      if (found) return found;
    }
  }
}

export default (initialState: { name: string; memuData: any[] }) => {
  // 在这里按照初始化数据定义项目中的权限，统一管理
  // 参考文档 https://next.umijs.org/docs/max/access

  //console.log({initialState});

  const { memuData } = initialState;

  const canSeeAdmin = !!(
    initialState && initialState.name !== 'dontHaveAccess'
  );

  const whatCanIDoInThisPage = (pagePath: string) => {
    if (memuData) {
      const thisPageData = findMenuItem(memuData, pagePath);
      // console.log({pagePath,thisPageData});
      if (thisPageData) {
        return thisPageData.function ? thisPageData.function : [];
      }
      return [];
    }
  };

  const canIReadThisPage = (pagePath: string) => {
    if (memuData) {
      const thisPageData = findMenuItem(memuData, pagePath);
      // console.log({pagePath,thisPageData});
      if (thisPageData) {
        return true;
      }
      return false;
    }
  };

  return {
    canSeeAdmin,
    whatCanIDoInThisPage,
    canIReadThisPage,
  };
};
