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: any, 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: any) => {
      Message.error(data.message);
      if (data.errorCode === '100003') {
        setTimeout(() => {
          localStorage.removeItem('token_key');
          if (window.location.href && !window.location.href.includes("/login-page"))
            window.location.href = '/v2/pages/login-page'
        }, 4000);
      }
    },
    ...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;
