import {addSetting} from '@apis';
import {
  createPageContext,
  createSearchContext,
  useContextSection,
  usePage,
} from '@hooks';
import {userStore} from '@stores';
import {useMutation} from '@tanstack/react-query';
import {message} from 'antd';
import {useLocation} from 'react-router-dom';
import {useStore} from 'zustand';

export function useSaveSetting(
  context: ReturnType<typeof createSearchContext>,
  pageContext: ReturnType<typeof createPageContext>,
  preloadKey?: string,
) {
  const tableState = useContextSection(context, state => state[0]);
  const {isLoading, mutate} = useMutation({
    mutationFn: addSetting,
    onSuccess({msg}) {
      if (msg === '200') {
        message.success('保存完成');
      }
    },
  });

  const userId = useStore(userStore, state => String(state.id));
  const {pathname} = useLocation();
  const [{pageSize}] = usePage(pageContext);
  function onSaveClick() {
    const key = preloadKey ?? pathname;
    mutate({
      userId,
      track: key,
      ...tableState,
      pageLimit: String(pageSize),
    });
  }

  return [isLoading, onSaveClick] as const;
}
