options.ts 11.7 KB
import { useMemo } from 'react';
import { useQuery, type UseQueryResult } from '@tanstack/react-query';
import type { FieldOption } from '@/components';
import {
  pointsApi,
  withdrawApi,
  type ChannelNode,
  type DictOption,
  type LegacyOption,
  type TagNode,
} from '@/api';
import { errorMessage } from './format';

/**
 * 远程筛选项。
 *
 * 老系统每个页面在 mounted 里各拉一遍、各自往 baseData 里塞,
 * 这里按「一份数据一个 hook」重做:同一次会话里同一份选项只发一次请求,
 * 换页不再重复拉;字段名差别(confId / id / code / nameWithId)在各自 hook 里抹平。
 */

/** 老接口有三种返回:数组、{ data: 数组 }、null。 */
function asArray(value: unknown): LegacyOption[] {
  if (Array.isArray(value)) return value as LegacyOption[];
  if (value && typeof value === 'object' && Array.isArray((value as { data?: unknown }).data)) {
    return (value as { data: LegacyOption[] }).data;
  }
  return [];
}

function options(
  items: LegacyOption[],
  valueKey: keyof LegacyOption,
  labelKey: keyof LegacyOption,
): DictOption[] {
  return items
    .map((item) => ({
      value: String(item[valueKey] ?? item.id ?? item.code ?? item.confId ?? ''),
      label: String(item[labelKey] ?? item.name ?? item.confLabel ?? item.label ?? ''),
    }))
    .filter((option) => option.value);
}

/** 一次查询的公共形状:页面只需要 options 与 loading/error。 */
export interface OptionQuery {
  options: DictOption[];
  isLoading: boolean;
  error?: string;
  query: UseQueryResult<unknown, Error>;
}

function useOptionQuery(
  scope: string,
  key: unknown[],
  fetcher: () => Promise<unknown>,
  enabled: boolean,
  pick: (raw: unknown) => DictOption[],
): OptionQuery {
  const query = useQuery({
    queryKey: ['points', scope, ...key],
    queryFn: fetcher,
    enabled,
    staleTime: 5 * 60 * 1000,
  });
  return {
    options: useMemo(() => (query.data ? pick(query.data) : []), [query.data, pick]),
    isLoading: enabled && query.isPending,
    error: query.error ? errorMessage(query.error) : undefined,
    query,
  };
}

/** 去掉老渠道树里的空 child,否则级联框会出现一层空白板。 */
export function pruneChannelTree(nodes: unknown): ChannelNode[] {
  if (!Array.isArray(nodes)) return [];
  return (nodes as ChannelNode[]).map((node) => {
    const child = Array.isArray(node.child) ? pruneChannelTree(node.child) : [];
    const next: ChannelNode = { ...node };
    if (child.length) next.child = child;
    else delete next.child;
    return next;
  });
}

function toCascader(nodes: ChannelNode[]): FieldOption[] {
  return nodes.map((node) => ({
    value: String(node.code ?? node.id ?? ''),
    label: String(node.name ?? node.code ?? ''),
    children: Array.isArray(node.child) && node.child.length ? toCascader(node.child) : undefined,
  }));
}

/**
 * 付款渠道树(搜索用)。同一份树还派生出「付款主体」下拉:
 * 老系统的付款主体不是独立接口,而是所选渠道下的子节点去重(见 entityOptions)。
 */
export function useChannelTree(enabled = true) {
  const result = useOptionQuery(
    'channel-tree',
    [],
    () => withdrawApi.channelTree({}),
    enabled,
    (raw) => options(asArray(raw), 'code', 'name'),
  );
  const nodes = useMemo(
    () => pruneChannelTree(result.query.data) as ChannelNode[],
    [result.query.data],
  );
  return { ...result, nodes, cascader: toCascader(nodes) };
}

/** 渠道树里选中渠道(或未选)之后的付款主体候选,按 code 去重。 */
export function entityOptions(nodes: ChannelNode[], channelCode?: string): DictOption[] {
  const children = nodes
    .filter((node) => !channelCode || node.code === channelCode)
    .flatMap((node) => (Array.isArray(node.child) ? node.child : []));
  const seen = new Set<string>();
  const unique: ChannelNode[] = [];
  for (const child of children) {
    const code = String(child.code ?? '');
    if (!code || seen.has(code)) continue;
    seen.add(code);
    unique.push(child);
  }
  return options(unique, 'code', 'name');
}

/** 付款弹窗的渠道级联:候选随提现类型与提现方式变化(老 getChannel)。 */
export function usePayChannelTree(
  params: { transferType?: string; mode?: string },
  enabled: boolean,
) {
  const query = useQuery({
    queryKey: ['points', 'pay-channel-tree', params.transferType ?? '', params.mode ?? ''],
    queryFn: () => withdrawApi.channelTree({ ...params }),
    enabled,
    staleTime: 0,
  });
  const nodes = useMemo(() => pruneChannelTree(query.data) as ChannelNode[], [query.data]);
  return { nodes, cascader: toCascader(nodes), isLoading: query.isPending };
}

/** 所属门店(提现域接口,展示「名称(编号)」,提交 id)。 */
export function useWithdrawMerchants(enabled = true) {
  return useOptionQuery(
    'merchants',
    [],
    () => withdrawApi.merchantOptions({}),
    enabled,
    (raw) =>
      asArray(raw).map((item) => ({
        value: String(item.id ?? ''),
        label: String(item.nameWithId ?? `${item.name ?? ''}(${item.id ?? ''})`),
      })),
  );
}

/** 门店列表(dj 网关,用户积分明细用:提交 merchantId,显示 merchantName)。 */
export function useShopMerchants(enabled = true) {
  return useOptionQuery(
    'shop-merchants',
    [],
    () => pointsApi.merchantOptions({}),
    enabled,
    (raw) => options(asArray(raw), 'merchantId', 'merchantName'),
  );
}

/** 主营品牌(提交 id)。 */
export function useBrands(enabled = true) {
  return useOptionQuery(
    'brands',
    [],
    () => withdrawApi.brandOptions({}),
    enabled,
    (raw) => options(asArray(raw), 'id', 'name'),
  );
}

/** 省份(提交 code)。 */
export function useProvinces(enabled = true) {
  return useOptionQuery(
    'provinces',
    [],
    () => withdrawApi.provinceOptions({}),
    enabled,
    (raw) => options(asArray(raw), 'code', 'name'),
  );
}

/** 代征主体(付款弹窗)。 */
export function usePayLevies(enabled = true) {
  return useOptionQuery(
    'pay-levies',
    [],
    () => withdrawApi.payLevyList({}),
    enabled,
    (raw) => options(asArray(raw), 'code', 'name'),
  );
}

/** 审批侧付款主体(付款审核弹窗)。 */
export function useApprovalPaymentEntities(enabled = true) {
  return useOptionQuery(
    'approval-payment-entities',
    [],
    () => withdrawApi.approvalPaymentEntityList({}),
    enabled,
    (raw) => options(asArray(raw), 'code', 'name'),
  );
}

/**
 * 提现标签树。
 * 一份数据三种用法:抽屉按层级渲染并就地增删改(nodes)、
 * 批量标注弹窗要求选到已补全的末级(cascader + onlyComplete)、
 * 筛选项则摊平成「一级 / 二级」路径文案,选任意层级都能筛(paths)。
 */
export function useTagTree(enabled = true, onlyComplete = false) {
  const query = useQuery({
    queryKey: ['points', 'tag-tree', onlyComplete],
    queryFn: () => withdrawApi.tagTree(onlyComplete ? { onlyComplete: true } : {}),
    enabled,
    staleTime: onlyComplete ? 0 : 5 * 60 * 1000,
  });
  const nodes = useMemo(() => toTagNodes(query.data), [query.data]);
  return {
    nodes,
    cascader: toTagCascader(nodes),
    paths: flattenTagPaths(nodes),
    isLoading: query.isPending,
    error: query.error ? errorMessage(query.error) : undefined,
    refetch: query.refetch,
  };
}

/** 老接口三种名字写法(name / label / tagName)都出现过,子节点字段也是 children 与 child 并存。 */
function toTagNodes(raw: unknown): TagNode[] {
  const nodes: TagNode[] = [];
  for (const item of asArray(raw)) {
    const id = String(item.id ?? '');
    if (!id) continue;
    nodes.push({
      id,
      name: String(item.name ?? item.label ?? item.tagName ?? id),
      parentId: item.parentId === undefined || item.parentId === null ? '' : String(item.parentId),
      children: toTagNodes(item.children ?? item.child ?? []),
    });
  }
  return nodes;
}

function toTagCascader(nodes: TagNode[]): FieldOption[] {
  return nodes.map((node) => ({
    value: node.id,
    label: String(node.name ?? node.id),
    children: node.children && node.children.length ? toTagCascader(node.children) : undefined,
  }));
}

/** 摊平成带路径前缀的平铺候选:老系统的级联框可以只选到一级,平铺之后这一层能力不丢。 */
function flattenTagPaths(nodes: TagNode[], parent = ''): DictOption[] {
  const flat: DictOption[] = [];
  for (const node of nodes) {
    const path = parent ? `${parent} / ${node.name ?? node.id}` : String(node.name ?? node.id);
    flat.push({ value: node.id, label: path });
    if (node.children?.length) flat.push(...flattenTagPaths(node.children, path));
  }
  return flat;
}

/** 渠道管理员(付款验证码发给谁)。 */
export function useChannelAdmins(channel: string | undefined, enabled: boolean) {
  const query = useQuery({
    queryKey: ['points', 'channel-admins', channel ?? ''],
    queryFn: () => withdrawApi.channelConfig(channel ? { channel } : {}),
    enabled,
    staleTime: 5 * 60 * 1000,
  });
  const admins = useMemo(() => asArray(query.data), [query.data]);
  return { admins, isLoading: query.isPending };
}

/**
 * 审批侧的「付款渠道 → 付款主体 → 代征主体」。
 *
 * 老系统这三层是级联框的懒加载(approve.vue 与 payApproval.vue 各抄了一份同样的三个方法),
 * 提交的是 paymentSubjectId(主体 id)与 paymentChannelId(代征主体 id,字段名是历史遗留)。
 * 取数与候选派生放在这里一次,级联框与筛选区的下拉都用它。
 */
export interface ApprovalLevy {
  value: string;
  label: string;
  /** 税点;付款审批弹窗按它重算付款总额。 */
  tax: string;
}

function toFieldOptions(items: LegacyOption[], valueKey: string, labelKey: string): DictOption[] {
  return items
    .map((item) => ({ value: String(item[valueKey] ?? ''), label: String(item[labelKey] ?? '') }))
    .filter((option) => option.value);
}

export async function loadApprovalChannels(): Promise<DictOption[]> {
  return toFieldOptions(asArray(await withdrawApi.channelList({})), 'channel', 'channelName');
}

export async function loadApprovalEntities(channel: string): Promise<DictOption[]> {
  if (!channel) return [];
  return toFieldOptions(
    asArray(await withdrawApi.paymentEntityList({ channel })),
    'paymentEntityId',
    'paymentEntityName',
  );
}

export async function loadApprovalLevies(
  channel: string,
  paymentEntityId: string,
): Promise<ApprovalLevy[]> {
  if (!channel || !paymentEntityId) return [];
  return asArray(await withdrawApi.payLevyList({ channel, paymentEntityId }))
    .map((item) => ({
      value: String(item.id ?? ''),
      label: String(item.levyName ?? ''),
      tax: String(item.tax ?? ''),
    }))
    .filter((item) => item.value);
}

/** 筛选区用的三层候选:选了上一层才发下一层的请求(与老系统懒加载的时机一致)。 */
export function useApprovalChannelOptions(channel: string | undefined, entity: string | undefined) {
  const channels = useQuery({
    queryKey: ['points', 'approval-channels'],
    queryFn: loadApprovalChannels,
    staleTime: 5 * 60 * 1000,
  });
  const entities = useQuery({
    queryKey: ['points', 'approval-entities', channel ?? ''],
    queryFn: () => loadApprovalEntities(channel ?? ''),
    enabled: !!channel,
    staleTime: 5 * 60 * 1000,
  });
  const levies = useQuery({
    queryKey: ['points', 'approval-levies', channel ?? '', entity ?? ''],
    queryFn: () => loadApprovalLevies(channel ?? '', entity ?? ''),
    enabled: !!channel && !!entity,
    staleTime: 5 * 60 * 1000,
  });
  return {
    channels: channels.data ?? [],
    entities: entities.data ?? [],
    levies: levies.data ?? [],
    isLoading: channels.isPending || entities.isPending || levies.isPending,
  };
}