import { useAntdTable } from "ahooks";
import useUrlQueryCriteria from "../useUrlQueryCriteria";

/**
 * 获取数据
 */
function getService(service, getExtraParams = {}, transform, usePermission) {
  // 获取额外的参数
  const extraParams = (typeof getExtraParams === "function" ? getExtraParams() : getExtraParams) || {};
  // 获取数据
  return async ({ current, pageSize }, formData = {}) => {
    // 如果提供了 transform 函数，则在请求之前调用它
    let transformedFormData = formData;
    if (typeof transform === "function") {
      const transformResult = transform(formData);
      // 如果 transform 函数有返回值，则将其与原始表单数据合并，transform 的优先级更高
      if (transformResult && typeof transformResult === "object") {
        transformedFormData = { ...formData, ...transformResult };
      }
    }

    const params = {
      pageIndex: current,
      pageSize,
      ...transformedFormData,
      ...extraParams,
    };

    if (usePermission)
      params.menuPath = window.location.pathname;

    // 发起请求
    const res = await service(params);
    // 返回数据
    return {
      list: res.data || [],
      total: res.totalCount || 0,
      ...res,
    };
  };
}

/**
 * 自定义 useTable，继承 ahooks 的 useAntdTable，根据需求进行扩展
 */
function useTable(service, options) {
  if (!service) {
    console.error("【useTable】 缺少 service 参数");
    return;
  }

  // 获取额外参数和转换函数
  const { params: extraParams, transform, ...restOptions } = options || {};

  // 获取配置项
  const {
    useStorageQueryCriteria = true,
    usePagination = true,
    usePermission = true,
    defaultType = "advance",
    defaultCurrent = 1,
    defaultPageSize = 20,
    defaultPagination = { current: defaultCurrent, pageSize: defaultPageSize },
    ...restRestOptions
  } = restOptions;

  const { setUrlCriteriaQuery, getUrlCriteriaQuery } = useUrlQueryCriteria();

  // 获取存储的查询条件
  const storageQueryCriteriaSearchForm = useStorageQueryCriteria ? getUrlCriteriaQuery("searchFormKeys", "searchFormValues") : {};
  const storageQueryCriteriaPagination = useStorageQueryCriteria && usePagination ? getUrlCriteriaQuery("paginationKeys", "paginationValues") : {};

  // 确定实际使用的搜索表单和分页参数
  const actualSearchForm = Object.keys(storageQueryCriteriaSearchForm).length > 0 ? storageQueryCriteriaSearchForm : {};
  /** @type {{current: number, pageSize: number}} */
  const actualPagination = usePagination ? Object.keys(storageQueryCriteriaPagination).length > 0 ? storageQueryCriteriaPagination : defaultPagination : {};

  // 调用 ahooks 的 useAntdTable
  const res = useAntdTable(
    getService(service, extraParams, transform, usePermission),
    {
      ...restRestOptions,
      defaultParams: [actualPagination, actualSearchForm],
      defaultType,
      onSuccess: (data, params) => {
        // 执行成功回调，为了保留 ahooks 的 onSuccess 回调
        restOptions.onSuccess && restOptions.onSuccess(data, params);
        // 存储查询条件和分页到 URL
        useStorageQueryCriteria && setUrlCriteriaQuery(
          params[1] ?? {},
          usePagination
            ? { current: res.tableProps.pagination.current, pageSize: res.tableProps.pagination.pageSize }
            : {},
        );
      },
    },
  );

  if (restOptions.callback !== undefined) {
    console.warn("【useTable】 callback 参数已弃用，请使用 onSuccess 参数");
  }

  // 执行回调函数
  restOptions.callback && restOptions.callback(res?.data?.list || [], res?.data || {});

  // 返回结果
  return {
    ...res,
    tableProps: {
      ...res.tableProps,
      pagination: usePagination ? { ...res.tableProps.pagination, showQuickJumper: true, showSizeChanger: true } : false,
    },
    getData: res.search.submit,
  };
}

export default useTable;
