/* eslint-disable prettier/prettier */
import { ref, reactive, unref } from "vue";
import { ElMessage } from "element-plus";
import { useNav } from "/@/layout/hooks/useNav";

type Params = {
  code: number;
  message: string;
  handler: () => void;
  errorHandler?: () => void;
};

export function useResponseHandle() {
  const { logout } = useNav();

  function responseHandle({ code, message, handler, errorHandler }: Params) {
    const c = Number(code);
    if (c === 0) {
      handler();
    } else if (c >= 100 && c <= 140) {
      logout();
    } else {
      if (errorHandler) {
        errorHandler();
      } else {
        ElMessage.error(message);
      }
    }
  }

  return responseHandle;
}
export function useAsync<D = any>({
  initalData,
  initalPagination,
  isList = false,
  prop = "data",
  success
}: {
  initalData?: D;
  isList?: boolean;
  initalPagination?: any;
  prop?: string;
  success?: (data?: D) => void;
} = {}) {
  let retry: Function;
  const data = ref<D>(initalData);
  const isError = ref(false);
  const loading = ref(false);
  const pagination = reactive(initalPagination || {});
  const responseHandle = useResponseHandle();

  const setData = (_data: D) => (data.value = _data as any);
  const setloading = (_state: boolean) => (loading.value = _state);

  function getPaginationParams() {
    const { pageSize: size, currentPage: page } = pagination;
    return {
      size,
      page
    };
  }

  function run(promise: Promise<DataType<D>>) {
    setloading(true);

    retry = () => run(promise);

    return promise.then(response => {
      setloading(false);

      const { code: _code, message } = response;

      if (String(_code) !== "0") isError.value = true;

      responseHandle({
        code: _code,
        message,
        handler: () => {
          setData(isList ? (response[prop] as any).list : response[prop]);
          isError.value = false;
          if (pagination) pagination.total = (data as any).count;
          success && success(unref(data as any));
        }
      });
    });
  }

  return {
    run,
    data,
    retry,
    setData,
    loading,
    isError,
    setloading,
    pagination,
    getPaginationParams
  };
}
