import { useRequest } from "ahooks";
import { useEffect } from "react";
import { useMessage } from "@/components/MySnackbar";

interface CachedData<TData, TParams> {
  data: TData;
  params: TParams;
  time: number;
}

const defaultOptions = {
  manual: true,
  pollingWhenHidden: false,
  throttleWait: 1000,
};

const useMyRequest = <TData, TParams>(
  api: (...args: TParams[]) => Promise<TData>,
  options?: {
    manual?: boolean;
    defaultParams?: TParams[];
    onBefore?: (params: TParams[]) => void;
    onSuccess?: (data: TData, params: TParams[]) => void;
    onError?: (e: Error, params: TParams[]) => void;
    onFinally?: (params: TParams[], data?: TData, e?: Error) => void;
    loadingDelay?: number;
    pollingInterval?: number;
    pollingWhenHidden?: boolean;
    ready?: boolean;
    refreshDeps?: any[];
    refreshOnWindowFocus?: boolean;
    focusTimespan?: number;
    debounceWait?: number;
    debounceLeading?: boolean;
    debounceTrailing?: boolean;
    debounceMaxWait?: number;
    throttleWait?: number;
    throttleLeading?: boolean;
    throttleTrailing?: boolean;
    cacheKey?: string;
    cacheTime?: number;
    staleTime?: number;
    setCache?: (data: CachedData<TData, TParams[]>) => void;
    getCache?: (params: TParams[]) => CachedData<TData, TParams[]>;
    retryCount?: number;
    retryInterval?: number;
    readyText?: string;
  }
) => {
  const Message = useMessage();

  const request = useRequest(api, {
    ...defaultOptions,
    onSuccess: () => {},
    onError: (data) => {
      Message.error(data.message);
    },
    ...options,
  });

  useEffect(() => {
    if (request.loading && options?.readyText) {
      Message.success(options.readyText);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [request.loading]);

  return { ...request, res: request.data };
};

export default useMyRequest;
