index.tsx 9.66 KB
import { useEffect, useMemo, useState } from 'react';
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { App } from 'antd';
import { DownloadOutlined, SettingOutlined } from '@ant-design/icons';
import { Skeleton, UAlert, UButton, UCard, UResult, UText, UTitle } from '@uj/ui';
import { P, useAccess } from '@/access';
import { store, type ListingPageParams, type StoreId, type StoreListingRow } from '@/api';
import {
  DataTable,
  DEFAULT_PAGE_SIZE,
  SearchForm,
  type ActionSchema,
  type FieldSchema,
  type RowActionSchema,
} from '@/components';
import { StoreDetailDrawer } from '@/features/store/StoreDetailDrawer';
import { STORE_DICTIONARIES } from '@/features/store/dictionaries';
import { useStoreFilterOptions } from '@/features/store/useStoreFilterOptions';
import { buildColumns } from './components/columns';
import { ColumnConfigModal } from './components/ColumnConfigModal';
import {
  errorText,
  exportParams,
  filterParams,
  INITIAL_PARAMS,
  normalizeColumns,
  type ListingFilters,
} from './tools/listing';
import '@/features/store/store.css';
import './listing.css';

const CONFIG_KEY = ['store', 'listing', 'columns'] as const;

export default function StoreListing() {
  const { message } = App.useApp();
  const { canPoint } = useAccess();
  const allowed = canPoint(P.STORE_LISTING_VIEW);
  const filterOptions = useStoreFilterOptions({ enabled: allowed, includeProducts: false });
  const queryClient = useQueryClient();
  const [params, setParams] = useState<ListingPageParams>(INITIAL_PARAMS);
  const [queryVersion, setQueryVersion] = useState(0);
  const [selected, setSelected] = useState<{ id: StoreId; tab: string } | null>(null);
  const [configOpen, setConfigOpen] = useState(false);
  const listing = useQuery({
    queryKey: ['store', 'listing', 'page', params, queryVersion],
    queryFn: () => store.listStores(params),
    placeholderData: keepPreviousData,
    enabled: allowed,
  });
  const config = useQuery({
    queryKey: CONFIG_KEY,
    queryFn: () => store.getColumnConfig(),
    enabled: allowed,
  });
  const configuredColumns = useMemo(() => normalizeColumns(config.data?.columns), [config.data]);
  const detail = useQuery({
    queryKey: ['store', 'listing', 'detail', selected?.id],
    enabled: allowed && selected !== null,
    queryFn: async () => {
      const id = selected!.id;
      const [data, changes] = await Promise.all([store.getStore(id), store.getChanges(id)]);
      return { ...data, changeHistory: changes };
    },
  });
  useEffect(() => {
    if (!allowed || !listing.data || listing.isPlaceholderData) return;
    const lastPage = Math.max(1, Math.ceil(listing.data.total / (params.size ?? 20)));
    if ((params.current ?? 1) > lastPage) {
      setParams((previous) => ({ ...previous, current: lastPage }));
      setQueryVersion((version) => version + 1);
    }
  }, [allowed, listing.data, listing.isPlaceholderData, params.current, params.size]);
  const saveConfig = useMutation({
    mutationFn: async (columns: string[]) => {
      await store.saveColumnConfig(columns);
      return store.getColumnConfig();
    },
    onSuccess: (result) => {
      queryClient.setQueryData(CONFIG_KEY, result);
      setConfigOpen(false);
      message.success('列配置已保存');
    },
  });
  const exportFile = useMutation({
    mutationFn: () => store.exportStores(exportParams(params)),
    onSuccess: () => {
      message.success('导出文件已下载');
    },
  });
  const total = listing.data?.total ?? 0;
  const overExportLimit = total > 50_000;
  const openDetail = (row: StoreListingRow, tab = 'info') =>
    setSelected({ id: row.listingId, tab });
  const fields: FieldSchema<ListingFilters>[] = [
    { name: 'storeName', label: '门店名称', type: 'input', placeholder: '模糊搜索', width: '100%' },
    {
      name: 'merchantNo',
      label: '门店商户号',
      type: 'input',
      placeholder: '模糊搜索',
      width: '100%',
    },
    {
      name: 'businessScene',
      label: '业务场景',
      type: 'select',
      width: '100%',
      options: filterOptions.businessScene.options,
      selectProps: filterOptions.businessScene.selectProps,
    },
    { name: 'effectiveRange', label: '上架时间', type: 'dateRange', width: '100%' },
  ];
  const columns = buildColumns({
    visible: configuredColumns,
    spec: STORE_DICTIONARIES,
  });
  const rowActions: RowActionSchema<StoreListingRow>[] = [
    { label: '查看详情', permission: P.STORE_LISTING_VIEW, onClick: (row) => openDetail(row) },
    {
      label: '变更历史',
      permission: P.STORE_LISTING_VIEW,
      onClick: (row) => openDetail(row, 'history'),
    },
  ];
  const actions: ActionSchema[] = [
    {
      label: (
        <>
          <SettingOutlined aria-hidden /> 列配置
        </>
      ),
      type: 'default',
      permission: P.STORE_LISTING_VIEW,
      onClick: () => {
        saveConfig.reset();
        setConfigOpen(true);
      },
    },
    {
      label: (
        <>
          <DownloadOutlined aria-hidden /> {exportFile.isPending ? '正在导出…' : '导出'}
        </>
      ),
      type: 'default',
      permission: P.STORE_LISTING_EXPORT,
      disabled:
        overExportLimit || listing.isFetching || Boolean(listing.error) || exportFile.isPending,
      onClick: () => {
        if (!overExportLimit && !exportFile.isPending) exportFile.mutate();
      },
    },
  ];

  if (!allowed)
    return (
      <UResult status="403" title="无门店列表访问权限" subTitle="请联系管理员开通访问权限。" />
    );
  if (listing.isPending) return <Skeleton variant="table" />;

  return (
    <div className="store-page">
      <div className="store-page-header">
        <div>
          <UTitle level={3} style={{ margin: 0 }}>
            门店列表
          </UTitle>
          <UText type="secondary">
            仅展示审批通过的数据。一行对应一个门店与一个业务场景,门店名称相同、业务场景不同的记录分别展示。
          </UText>
        </div>
      </div>
      <UCard className="store-filter-card" size="small">
        <SearchForm<ListingFilters>
          fields={fields}
          layout="vertical"
          className="store-search-form"
          initialValues={{ businessScene: '' }}
          onSearch={(values) => {
            const next = {
              ...filterParams(values),
              current: 1,
              size: params.size,
              sortField: params.sortField,
              sortOrder: params.sortOrder,
            };
            setParams(next);
            setQueryVersion((version) => version + 1);
            if (!exportFile.isPending) exportFile.reset();
          }}
          onReset={() => {
            filterOptions.reset();
            setParams({ ...INITIAL_PARAMS, size: params.size });
            setQueryVersion((version) => version + 1);
            if (!exportFile.isPending) exportFile.reset();
          }}
        />
      </UCard>
      {listing.error ? (
        <UAlert
          type="error"
          showIcon
          title={errorText(listing.error, '门店列表加载失败')}
          action={
            <UButton type="link" onClick={() => void listing.refetch()}>
              重新加载列表
            </UButton>
          }
        />
      ) : null}
      {exportFile.error ? (
        <UAlert type="error" showIcon title={errorText(exportFile.error, '导出失败,请重试')} />
      ) : null}
      {overExportLimit ? (
        <UAlert type="warning" showIcon title="筛选结果超过 50,000 条,请缩小范围后导出。" />
      ) : null}
      <div className="store-listing-section">
        <DataTable<StoreListingRow>
          className="store-listing-table"
          rowKey="listingId"
          columns={columns}
          rowActions={rowActions}
          actionColumnWidth={150}
          actionColumnFixed="right"
          toolbarTitle={
            <UText strong>
              已生效门店 <UText type="secondary">{total} 条</UText>
            </UText>
          }
          toolbarClassName="store-listing-toolbar"
          actions={actions}
          dataSource={listing.data?.records ?? []}
          loading={listing.isFetching}
          scroll={{ x: 950 }}
          pagination={{
            current: params.current ?? 1,
            pageSize: params.size ?? DEFAULT_PAGE_SIZE,
            total,
            showSizeChanger: false,
            pageSizeOptions: [10, 20, 50, 100],
            showTotal: (count) =>
              `共 ${count.toLocaleString('zh-CN')} 条记录 · 每页 ${params.size ?? DEFAULT_PAGE_SIZE} 条`,
            onChange: (current, size) =>
              setParams((previous) => ({
                ...previous,
                current: size !== previous.size ? 1 : current,
                size,
              })),
          }}
        />
      </div>
      <ColumnConfigModal
        open={configOpen}
        columns={configuredColumns}
        loading={config.isFetching}
        error={config.error}
        saving={saveConfig.isPending}
        saveError={saveConfig.error}
        onClose={() => setConfigOpen(false)}
        onRetry={() => void config.refetch()}
        onSave={(next) => {
          if (!config.isFetching && !config.error && !saveConfig.isPending) saveConfig.mutate(next);
        }}
      />
      <StoreDetailDrawer
        key={selected ? `${selected.id}:${selected.tab}` : 'closed'}
        open={selected !== null}
        detail={detail.data}
        spec={STORE_DICTIONARIES}
        loading={detail.isPending && selected !== null}
        error={detail.error}
        mode="listing"
        initialTab={selected?.tab}
        onClose={() => setSelected(null)}
        onRetry={() => void detail.refetch()}
      />
    </div>
  );
}