// 全局共享数据示例
import { useRequest } from '@umijs/max';
import { queryCurrentV2, queryUserRole } from '@/services/user';

const useUser = () => {
  const { data: user, loading, run } = useRequest(queryCurrentV2, {
    cacheKey: 'queryCurrent',
  });
  // const { data: roleData, loading } = useRequest(() => queryUserRole(user.ID), {
  //   cacheKey: 'queryUserRole',
  //   ready: !!user?.ID,
  // });
  // if (!roleData) return { user: null, loading: loading };
  if (!user) return { user: null, loading: loading, run };
  let permission = {};
  user.Permissions?.forEach((item: any) => {
    permission = {
      ...permission,
      ...item.Menus,
    };
  });
  // let roleList = getRoleList(roleData.Dep);

  return {
    user: {
      ...user,
      Permission: permission,
      // roleList: roleList,
    },
    loading,
    run
  };
};

const getRoleList = (data: any) => {
  let roleList: any = [];
  (data || []).forEach((dep: any) => {
    (dep.Role || []).forEach((role: any) => {
      roleList.push(role);
    });

    if (dep.children) {
      let res = getRoleList(dep.children);
      roleList = res.concat(res);
    }
  });
  return roleList;
};
export default useUser;
