StoreDetailDrawer.tsx 13.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
import type { ReactNode } from 'react';
import { Steps, Timeline, type TableColumnsType } from 'antd';
import {
  Skeleton,
  UAlert,
  UButton,
  UDescriptions,
  UDrawer,
  UResult,
  UTable,
  UTabs,
  UTag,
  UText,
} from '@uj/ui';
import type { StoreListingDetail, StoreListingItem } from '@/api';
import type { StoreDictionaries } from './dictionaries';
import { STORE_STATUS, type StoreStatus } from '@/config/storeStatus';
import { dictionaryLabel, formatDateTime, formatMoney, formatPolicyValue } from './formatters';

export interface StoreDetailDrawerProps {
  open: boolean;
  detail?: StoreListingDetail;
  spec?: StoreDictionaries;
  loading?: boolean;
  error?: unknown;
  mode: 'approval' | 'listing';
  initialTab?: string;
  onClose: () => void;
  onRetry?: () => void;
  footer?: ReactNode;
}

type PolicyPrefix = 'marketFee1' | 'marketFee2' | 'sunshine1' | 'sunshine2';

const ACTION_LABELS: Record<string, string> = {
  SUBMIT: '提交',
  PASS: '通过',
  BATCH_PASS: '批量通过',
  REJECT: '打回',
  REVOKE: '撤回',
  REVOKED: '撤回',
  RESUBMIT: '重新提交',
  VOID: '作废',
  APPROVE: '通过',
};
const ROLE_LABELS: Record<string, string> = {
  YJ_BUSINESS_MGR: '优加商务经理',
  YJ_BIZ_MGR: '优加商务经理',
  YJ_FINANCE_MGR: '优加财务经理',
  ONLINE_OPS: '线上运营',
};

function statusInfo(status?: string | null) {
  return status ? STORE_STATUS[status as StoreStatus] : undefined;
}

function statusLabel(status?: string | null) {
  return statusInfo(status)?.label || status || '—';
}

function ApprovalStages({ detail }: { detail: StoreListingDetail }) {
  const roles = detail.totalLevel === 1 ? ['优加财务经理'] : ['优加商务经理', '优加财务经理'];
  const level = detail.currentLevel === 2 && roles.length === 2 ? 2 : 1;
  const approved = detail.status === 'APPROVED';
  const pending = detail.status === 'PENDING';
  const stopped = detail.status === 'REVOKED' || detail.status === 'VOID';
  const current = approved ? roles.length + 1 : stopped ? 0 : level;
  return (
    <section aria-label="审批流程" style={{ margin: '24px 0' }}>
      <Steps
        size="small"
        current={current}
        status={detail.status === 'REJECTED' ? 'error' : stopped ? 'wait' : 'process'}
        items={[
          { title: '提交', content: detail.submitUserName || '—' },
          ...roles.map((title, index) => ({
            title,
            content: pending && index + 1 === level ? '当前审批节点' : undefined,
          })),
          {
            title: '生效',
            content: approved
              ? formatDateTime(detail.effectiveTime ?? detail.approveTime)
              : undefined,
            status: approved ? ('finish' as const) : ('wait' as const),
          },
        ]}
      />
    </section>
  );
}

function DetailContent({
  detail,
  spec,
  mode,
  initialTab,
  open,
}: Pick<StoreDetailDrawerProps, 'spec' | 'mode' | 'initialTab' | 'open'> & {
  detail: StoreListingDetail;
}) {
  const items = (detail.items || []).map((item, index) => ({
    ...item,
    displayKey: String(item.itemId ?? index),
  }));
  const scene = dictionaryLabel(spec?.businessScenes, detail.businessScene);
  const categoryColumn: TableColumnsType<StoreListingItem>[number] = {
    title: '产品分类',
    key: 'category',
    width: 150,
    fixed: 'left',
    render: (_, item) => (
      <UTag>{dictionaryLabel(spec?.productCategories, item.productCategory)}</UTag>
    ),
  };
  const columnsFor = (
    prefix: PolicyPrefix,
    title: string,
  ): TableColumnsType<StoreListingItem>[number] => ({
    title,
    key: prefix,
    children: [
      ...(prefix === 'sunshine1' || prefix === 'sunshine2'
        ? [
            {
              title: '开启线上积分',
              key: `${prefix}OnlinePoint`,
              width: 115,
              render: (_: unknown, item: StoreListingItem) =>
                dictionaryLabel(spec?.onlinePointFlags, item[`${prefix}OnlinePoint`]),
            },
          ]
        : []),
      {
        title: '计算模式',
        key: `${prefix}CalcMode`,
        width: 120,
        render: (_, item) => dictionaryLabel(spec?.calcModes, item[`${prefix}CalcMode`]),
      },
      {
        title: '计算方式',
        key: `${prefix}CalcWay`,
        width: 140,
        render: (_, item) => dictionaryLabel(spec?.calcWays, item[`${prefix}CalcWay`]),
      },
      {
        title: '数值',
        key: `${prefix}Value`,
        width: 130,
        align: 'right',
        render: (_, item) =>
          formatPolicyValue(item[`${prefix}Value`], item[`${prefix}Unit`] ?? undefined),
      },
    ],
  });
  const policyTable = (columns: TableColumnsType<StoreListingItem>) => (
    <UTable<StoreListingItem>
      rowKey="displayKey"
      size="small"
      pagination={false}
      columns={columns}
      dataSource={items}
      scroll={{ x: 'max-content' }}
    />
  );
  const compactPolicy = (item: StoreListingItem, prefix: PolicyPrefix) => (
    <div>
      {dictionaryLabel(spec?.calcModes, item[`${prefix}CalcMode`])} /{' '}
      {dictionaryLabel(spec?.calcWays, item[`${prefix}CalcWay`])} /{' '}
      {formatPolicyValue(item[`${prefix}Value`], item[`${prefix}Unit`] ?? undefined)}
      {(prefix === 'sunshine1' || prefix === 'sunshine2') && (
        <div>
          <UText type="secondary">
            开启线上积分:{dictionaryLabel(spec?.onlinePointFlags, item[`${prefix}OnlinePoint`])}
          </UText>
        </div>
      )}
    </div>
  );
  const costPanel = (
    <>
      <UDescriptions
        column={1}
        bordered
        size="small"
        items={[
          {
            key: 'decoration',
            label: '装修、设备总投入',
            children: formatMoney(detail.costDecoration),
          },
          {
            key: 'monthly',
            label: '当月产生(房租、水电、耗材等)',
            children: formatMoney(detail.costMonthly),
          },
          { key: 'labor', label: '人工成本', children: formatMoney(detail.costLabor) },
          {
            key: 'total',
            label: '运营成本合计',
            children: <strong>{formatMoney(detail.costTotal)}</strong>,
          },
        ]}
      />
      <p>
        <UText type="secondary">运营成本为门店维度,不随产品分类数或业务场景数重复累计。</UText>
      </p>
    </>
  );
  const logs = [...(detail.approvalLogs || [])].sort((a, b) =>
    (a.operateTime || '').localeCompare(b.operateTime || ''),
  );
  const history = [...(detail.changeHistory || [])].sort((a, b) =>
    (b.effectiveTime || '').localeCompare(a.effectiveTime || ''),
  );
  const approvalTabs = [
    {
      key: 'market',
      label: '管理层市场费',
      children: policyTable([
        categoryColumn,
        columnsFor('marketFee1', '市场费 1'),
        columnsFor('marketFee2', '市场费 2'),
      ]),
    },
    {
      key: 'sunshine',
      label: '一线阳光激励',
      children: policyTable([
        categoryColumn,
        columnsFor('sunshine1', '阳光激励 1'),
        columnsFor('sunshine2', '阳光激励 2'),
      ]),
    },
    { key: 'costs', label: '运营成本', children: costPanel },
    {
      key: 'logs',
      label: '审批留痕',
      children: logs.length ? (
        <Timeline
          items={logs.map((log, index) => ({
            key: String(log.logId ?? index),
            color: log.action === 'REJECT' ? 'red' : 'blue',
            title: formatDateTime(log.operateTime),
            content: (
              <div>
                <strong>{ACTION_LABELS[log.action || ''] || log.action || '—'}</strong> ·{' '}
                <span>{log.operatorName || '—'}</span> ·{' '}
                {ROLE_LABELS[log.operatorRole || ''] || log.operatorRole || '—'}
                <div>
                  {statusLabel(log.preStatus)} → {statusLabel(log.postStatus)}
                </div>
                {log.reason && (
                  <p style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}>{log.reason}</p>
                )}
                <UText type="secondary">IP:{log.operateIp || '—'}</UText>
              </div>
            ),
          }))}
        />
      ) : (
        <UText type="secondary">暂无审批留痕</UText>
      ),
    },
  ];
  const listingTabs = [
    {
      key: 'info',
      label: '门店信息',
      children: (
        <UDescriptions
          column={1}
          bordered
          size="small"
          items={[
            { key: 'name', label: '门店名称', children: detail.storeName },
            { key: 'merchant', label: '门店商户号', children: detail.merchantNo },
            { key: 'scene', label: '业务场景', children: scene },
            {
              key: 'categories',
              label: '产品分类数',
              children: detail.categoryCount ?? items.length,
            },
            {
              key: 'status',
              label: '上架状态',
              children: detail.statusLabel || statusLabel(detail.status),
            },
            {
              key: 'effective',
              label: '生效时间',
              children: formatDateTime(detail.effectiveTime ?? detail.approveTime),
            },
          ]}
        />
      ),
    },
    {
      key: 'products',
      label: '产品与场景',
      children: policyTable([
        categoryColumn,
        { title: '业务场景', key: 'scene', width: 200, render: () => scene },
        {
          title: '阳光激励 1 计算模式',
          key: 'mode1',
          width: 160,
          render: (_, item) => dictionaryLabel(spec?.calcModes, item.sunshine1CalcMode),
        },
        {
          title: '阳光激励 2 计算模式',
          key: 'mode2',
          width: 160,
          render: (_, item) => dictionaryLabel(spec?.calcModes, item.sunshine2CalcMode),
        },
      ]),
    },
    {
      key: 'policies',
      label: '市场与激励',
      children: policyTable([
        categoryColumn,
        ...(['marketFee1', 'marketFee2', 'sunshine1', 'sunshine2'] as const).map(
          (prefix, index) => ({
            title: ['管理层市场费 1', '管理层市场费 2', '一线阳光激励费 1', '一线阳光激励费 2'][
              index
            ],
            key: prefix,
            width: 240,
            render: (_: unknown, item: StoreListingItem) => compactPolicy(item, prefix),
          }),
        ),
      ]),
    },
    { key: 'costs', label: '运营成本', children: costPanel },
    {
      key: 'history',
      label: '变更历史',
      children: history.length ? (
        <Timeline
          items={history.map((change, index) => ({
            key: String(change.changeId ?? index),
            title: change.versionNo == null ? '版本未提供' : `v${change.versionNo}`,
            content: (
              <div>
                <strong>{change.changeField || '—'}</strong>
                <p style={{ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' }}>
                  {change.beforeValue ?? '—'} → {change.afterValue ?? '—'}
                </p>
                <UText type="secondary">
                  变更人:{change.changeUserName || '—'} · 生效时间:
                  {formatDateTime(change.effectiveTime)}
                </UText>
              </div>
            ),
          }))}
        />
      ) : (
        <UText type="secondary">暂无变更历史</UText>
      ),
    },
  ];
  const tabs = mode === 'approval' ? approvalTabs : listingTabs;
  const selectedTab = tabs.some((tab) => tab.key === initialTab) ? initialTab : tabs[0].key;
  return (
    <>
      <div
        style={{
          display: 'flex',
          gap: 12,
          flexWrap: 'wrap',
          alignItems: 'center',
          marginBottom: 16,
        }}
      >
        <h3 style={{ margin: 0 }}>{detail.storeName}</h3>
        <UTag color={statusInfo(detail.status)?.color}>
          {detail.statusLabel || statusLabel(detail.status)}
        </UTag>
      </div>
      <UDescriptions
        size="small"
        column={2}
        items={[
          { key: 'merchant', label: '门店商户号', children: detail.merchantNo },
          { key: 'scene', label: '业务场景', children: scene },
          {
            key: 'categories',
            label: '产品分类',
            children: `${detail.categoryCount ?? items.length} 个`,
          },
          { key: 'total', label: '运营成本合计', children: formatMoney(detail.costTotal) },
          { key: 'submitter', label: '提交人', children: detail.submitUserName || '—' },
          { key: 'submitTime', label: '提交时间', children: formatDateTime(detail.submitTime) },
        ]}
      />
      {mode === 'approval' && <ApprovalStages detail={detail} />}
      {detail.rejectReason && (
        <UAlert
          type="warning"
          title="打回原因"
          description={detail.rejectReason}
          style={{ marginBottom: 16 }}
        />
      )}
      <UTabs
        key={`${detail.listingId}:${mode}:${initialTab}:${open}`}
        defaultActiveKey={selectedTab}
        items={tabs}
      />
    </>
  );
}

export function StoreDetailDrawer({
  open,
  detail,
  spec,
  loading,
  error,
  mode,
  initialTab,
  onClose,
  onRetry,
  footer,
}: StoreDetailDrawerProps) {
  return (
    <UDrawer
      open={open}
      onClose={onClose}
      title={mode === 'approval' ? '门店审批详情' : '门店详情'}
      footer={footer}
    >
      {loading ? (
        <Skeleton variant="detail" />
      ) : error ? (
        <UResult
          status="error"
          title="详情加载失败"
          subTitle={error instanceof Error ? error.message : '请稍后重试'}
          extra={onRetry && <UButton onClick={onRetry}>重试</UButton>}
        />
      ) : detail ? (
        <DetailContent
          open={open}
          detail={detail}
          spec={spec}
          mode={mode}
          initialTab={initialTab}
        />
      ) : (
        <UResult status="info" title="暂无门店详情" />
      )}
    </UDrawer>
  );
}