import {getUserBasicMenu} from '@apis';
import {MAIN_PATH} from '@routes';
import {menuStore, tabStore} from '@stores';
import {useQuery} from '@tanstack/react-query';
import {MENU_COLLAPSED_STORAGE, sortMenu} from '@utils';
import {useBoolean, useLocalStorageState} from 'ahooks';
import {useEffect, useState} from 'react';
import {useStore} from 'zustand';

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

  const {data} = useQuery({
    queryKey: [getUserBasicMenu.name],
    async queryFn() {
      const data = await getUserBasicMenu();

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

        setMenus(finalMenu);
        dispatch({
          type: 'ADD',
          payload: {key: '-1', url: MAIN_PATH, label: '首页'},
        });
        return sortMenu(finalMenu);
      }

      throw new Error(data.errMsg);
    },
    suspense: true,
    cacheTime: Infinity,
    staleTime: Infinity,
  });

  return data;
}

export function useMenuState() {
  const [openKeys, setOpenKey] = useState<string[]>(['-1']);

  function onOpenChange(keys: string[]) {
    setOpenKey([keys[keys.length - 1]]);
  }

  const pages = useStore(menuStore, state => state.menus);
  const activeKey = useStore(tabStore, state => state.activeKey);
  const dispatch = useStore(tabStore, state => state.dispatch);
  function onClick(e: {key: string; keyPath: string[]}) {
    setOpenKey(e.keyPath);
    const data = pages.find(val => val.id === e.key);
    if (!data || data.url === '.')
      return;

    dispatch({
      type: 'ADD',
      payload: {key: data.id, url: data.url, label: data.name},
    });
  }

  const [selectKey, setSelectKey] = useState(['-1']);
  useEffect(
    function() {
      const menu = pages.find(val => val.id === activeKey);
      menu && menu.pId !== '0' ? setOpenKey([menu.pId]) : setOpenKey([]);

      setSelectKey([activeKey]);
    },
    [activeKey, pages],
  );

  return [
    {openKeys, selectKey},
    {onOpenChange, onClick},
  ] as const;
}

export function useCollapsedMenu() {
  const [storage, setStorage] = useLocalStorageState<'0' | '1' | undefined>(
    MENU_COLLAPSED_STORAGE,
  );
  const [state, {set}] = useBoolean(
    storage ? storage === '1' : window.innerWidth <= 1200,
  );

  function toggle() {
    setStorage(state ? '0' : '1');
    set(!state);
  }

  return [state, toggle] as const;
}
