import {BaseResult} from '@models';
import {useMutation} from '@tanstack/react-query';
import {message} from 'antd';

type UsePutDataOptions<A, E> = {
  addFn: (params: A) => BaseResult;
  editFn: (params: E) => BaseResult;
  onFetch: () => void;
  onClose: () => void;
};

function useQuery<P>(options: {
  fn: (params: P) => BaseResult;
  isAdd: boolean;
  onFetch: UsePutDataOptions<any, any>['onFetch'];
  onClose: UsePutDataOptions<any, any>['onClose'];
}) {
  const {fn, isAdd, onFetch, onClose} = options;

  return useMutation({
    mutationFn: fn,
    onSuccess({msg}) {
      if (msg === '200') {
        message.success(`${isAdd ? '新增' : '修改'}成功`);
        onFetch();
        onClose();
      }
    },
  });
}

export function usePutData<A, E>({
  addFn,
  editFn,
  onFetch,
  onClose,
}: UsePutDataOptions<A, E>) {
  const {isLoading: isAddLoading, mutate: addMutate} = useQuery({
    fn: addFn,
    onFetch,
    onClose,
    isAdd: true,
  });
  const {isLoading: isEditLoading, mutate: editMutate} = useQuery({
    fn: editFn,
    onFetch,
    onClose,
    isAdd: false,
  });
  const isLoading = isAddLoading || isEditLoading;

  return [isLoading, {addMutate, editMutate}] as const;
}
