queries.ts 4.41 KB
import { useEffect } from 'react';
import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
import { DEFAULT_PAGE_SIZE } from '@/components';
import { rows, totalOf, pageParams, type PageKey, type RpcListResult } from '@/api';
import { errorMessage } from './format';
import { openExportUrl } from './files';

import { useUMessage } from '@uj/ui';
/** 列表页共享的分页状态:与 DataTable 的 pagination 直接对齐。 */
export interface ListPage {
  current: number;
  size: number;
}
export const firstPage: ListPage = { current: 1, size: DEFAULT_PAGE_SIZE };

export interface ListQuery<T> {
  queryKey: unknown[];
  queryFn: () => Promise<RpcListResult<T>>;
  enabled: boolean;
}

export interface ListQueryOptions<T> {
  /** queryKey 前缀:同一份列表用同一个作用域,刷新与失效都按它整批处理。 */
  scope: unknown[];
  filters: Record<string, unknown>;
  page: ListPage;
  /** 老接口的页码字段名不统一,见 pageParams()。 */
  pageKey?: PageKey;
  fetcher: (params: Record<string, unknown>) => Promise<RpcListResult<T>>;
  enabled?: boolean;
  /** tab 预加载时非当前 tab 只取 1 条用于计数(与门店审批页同一套做法)。 */
  probe?: boolean;
}

/**
 * 分页查询的唯一构造方式:把「老接口的 currentPage/pageNum 差别」和 queryKey 形状收口,
 * 于是每个列表页只需要给出作用域、筛选条件与取数函数。
 */
export function listQuery<T>(options: ListQueryOptions<T>): ListQuery<T> {
  const params = {
    ...options.filters,
    ...pageParams(
      options.probe ? 1 : options.page.current,
      options.probe ? 1 : options.page.size,
      options.pageKey,
    ),
  };
  return {
    queryKey: [...options.scope, params],
    queryFn: () => options.fetcher(params),
    enabled: options.enabled !== false,
  };
}

export function useList<T>(options: ListQueryOptions<T>) {
  const query = useQuery(listQuery(options));
  return {
    query,
    records: rows<T>(query.data),
    total: totalOf(query.data),
    error: errorMessage(query.error),
  };
}

/** 多个 tab 各自一份列表数据时按顺序取;页码只作用于当前 tab,其余 tab 用 1 条探测总数。 */
export function useLists<T>(
  tabs: Array<{ key: string; active: boolean }>,
  build: (tab: string, active: boolean) => ListQueryOptions<T>,
) {
  const queries = useQueries({ queries: tabs.map((tab) => listQuery(build(tab.key, tab.active))) });
  return tabs.map((tab, index) => {
    const query = queries[index];
    return {
      key: tab.key,
      query,
      records: rows<T>(query.data),
      total: query.data ? totalOf(query.data) : 0,
      error: errorMessage(query.error),
    };
  });
}

/** 删除或操作后当前页可能空掉:把页码回拉到最后一页(老系统靠列表组件自动跳页)。 */
export function usePageClamp(total: number, page: ListPage, setPage: (next: ListPage) => void) {
  const { current, size } = page;
  useEffect(() => {
    const last = Math.max(1, Math.ceil(total / size));
    if (current > last) setPage({ current: last, size });
  }, [total, current, size, setPage]);
}

/** 业务动作成功后让本域列表重新取数(老系统每个动作回调都调 handleSearch)。 */
export function useRefresh(scope: unknown[]) {
  const client = useQueryClient();
  return () => client.invalidateQueries({ queryKey: scope });
}

/**
 * 导出:老系统所有导出接口返回一个下载地址,点开即下载。
 * 统一在这里做「无地址 = 失败」的兜底提示,页面只负责传当前筛选条件。
 */
export function useExport(
  fetcher: (params: Record<string, unknown>) => Promise<string>,
  label = '导出文件',
) {
  const message = useUMessage();
  return useMutation({
    mutationKey: ['points', 'export', label],
    mutationFn: async (params: Record<string, unknown>) => {
      const url = await fetcher(params);
      if (!openExportUrl(url, label)) throw new Error('后端未返回下载地址,请稍后重试');
      return url;
    },
    onError: (error) => message.error(errorMessage(error)),
  });
}

/** 写操作统一提示:老系统按 code=='0' 判断,适配层已在失败时抛错,这里只处理成功分支之外的文案。 */
export function useActionMessage() {
  const message = useUMessage();
  return {
    success: (text = '操作成功') => message.success(text),
    fail: (error: unknown) => message.error(errorMessage(error)),
  };
}