import { ref, reactive, unref } from "vue";
import { ElMessage } from "element-plus";
import { useNav } from "/@/layout/hooks/nav";
import { IDataType } from "/@/api/types";

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

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

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

  return responseHandle;
}
export function useAsync<D = any>({
  initialData,
  initalData,
  initalPagination,
  isList = false,
  success
}: { initialData?: D,initalData?: D; isList?: boolean; initalPagination?: any; success?: (data?: D) => void; } = {}) {
  const data = ref<D>(initialData || 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<IDataType<D>>) {
    setloading(true);
    return promise.then(response => {
      setloading(false);
      const { code: _code, message, data } = response;
      if (String(_code) !== "0") isError.value = true;
      responseHandle({
        code: _code,
        message,
        handler: () => {
          setData(isList ? (data as any).list : data);
          isError.value = false;
          if (pagination) pagination.total = (data as any)?.count;
          success && success(unref(data));
        }
      });
    });
  }

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