import { onMounted, ref } from "vue";
import { useNav } from "/@/layout/hooks/useNav";
import { ActionType, PageContentProps } from "../types";
import { mapActionToApi } from "../utils/create-operation";
import { mergeParams } from "../utils/merge-params";
import { responseHandle } from "/@/utils/responseHandle";
import { handleTree } from "@pureadmin/utils";
import { usePagination } from "./use-pagination";
import { useParams } from "./use-params";

/**
 * 请求方法
 */
export function useRequeset(props: PageContentProps) {
  const { logout } = useNav();
  const { contentConfig } = props;
  const { mockData } = contentConfig;

  const loading = ref(false);
  const dataList = ref(mockData ? mockData : []);
  const initRequest = ref(!props.contentConfig.notReuqiredInit);

  const { getBasicParams, changeBasicParams } = useParams();
  const paginationConfig = usePagination(props, {
    onSearch
  });

  const { changePagination, getPagination } = paginationConfig;

  /**
   * 搜索
   */
  async function onSearch() {
    const { contentConfig } = props;
    const { apis, isTree, mockData } = contentConfig;

    if (!initRequest.value || mockData) return (initRequest.value = true);

    loading.value = true;

    const { code, data, message } = await apis.httpList(
      mergeParams({
        pagination: getPagination ? getPagination() : {},
        basicParams: getBasicParams()
      })
    );

    responseHandle({
      code,
      message,
      logout,
      handler: () => {
        const list = Array.isArray(data) ? data : data.list;
        dataList.value = isTree ? handleTree(list ?? []) : list;
        changePagination("total", data.count);
      }
    });

    loading.value = false;
  }

  /**
   * 外部使用的请求方法
   */
  function getPageData(parmas: any = {}) {
    changePagination && changePagination("currentPage", 1);
    changeBasicParams && changeBasicParams(parmas);
    onSearch();
  }

  /**
   * 外部action执行传入数据发起请求
   */
  async function onBeforeAction(
    action: ActionType,
    data: any = {},
    responseCallback?: () => void
  ) {
    const { contentConfig } = props;
    const { apis } = contentConfig;
    const key = mapActionToApi[action];

    loading.value = true;

    const { code, message } = await apis[key](data);

    responseCallback && responseCallback();

    responseHandle({
      code,
      message,
      logout,
      handler: () => onSearch()
    });

    loading.value = false;
  }

  //初始化数据
  onMounted(() => onSearch());

  return {
    loading,
    dataList,
    getBasicParams,
    getPagination,
    onBeforeAction,
    paginationConfig,
    getPageData,
    onSearch
  };
}
