import {getRoleMenu} from '@apis';
import {HOME_PATH} from '@routes';
import {menuStore} from '@stores';
import {useQuery} from '@tanstack/react-query';
import {sortMenu} from '@utils';
import {useStore} from 'zustand';

export function useMenu() {
  const setMenus = useStore(menuStore, state => state.setMenu);

  const {data} = useQuery(
    [getRoleMenu.name],
    async function() {
      const data = await getRoleMenu();

      if (data.msg === '200') {
        const finalMenu = [
          {
            id: '-1',
            name: '首页',
            url: HOME_PATH,
            pId: '0',
            page: 1,
            limit: 0,
            orderBy: '0',
          },
          ...data.data,
        ];

        setMenus(finalMenu);
        return sortMenu(finalMenu);
      }

      throw new Error(data.errMsg);
    },
    {
      suspense: true,
    },
  );

  return data;
}
