index.tsx 7.74 KB
import { useState } from 'react';
import { Skeleton, useUApp } from '@uj/ui';
import { PageHeader } from './components/PageHeader';
import { NoticeSection } from './components/NoticeSection';
import { StepsBar } from './components/StepsBar';
import { ImportInfoCard } from './components/ImportInfoCard';
import type { ImportInfoValues } from './components/ImportInfoCard';
import { UploadCard } from './components/UploadCard';
import { UploadActionBar } from './components/UploadActionBar';
import { ValidationStats } from './components/ValidationStats';
import { ValidationActionBar } from './components/ValidationActionBar';
import { PolicyConfirmHeader } from './components/PolicyConfirmHeader';
import { PolicyConfirmTable } from './components/PolicyConfirmTable';
import { ConfirmActionBar } from './components/ConfirmActionBar';
import { SubmitConfirmCard } from './components/SubmitConfirmCard';
import { ApprovalChainPreview } from './components/ApprovalChainPreview';
import { FailDetailCard } from './components/FailDetailCard';
import { SubmitActionBar } from './components/SubmitActionBar';
import { store } from '@/api';
import type { StoreImportCheckVO } from '@/api/modules/store';

export default function TemplateImport() {
  const loading = false;
  const { message, modal } = useUApp();
  const [currentStep, setCurrentStep] = useState<0 | 1 | 2 | 3>(0);
  const [importInfo, setImportInfo] = useState<ImportInfoValues | null>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [checkResult, setCheckResult] = useState<StoreImportCheckVO | null>(null);
  // Step 4:提交确认勾选状态(受控,用于 disabled=!checked || 无通过数据)
  const [submitChecked, setSubmitChecked] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  // Step 2 点击【重新上传】:递增触发 UploadCard.useEffect 自动重新调用 runUpload(保留选中文件)
  const [reUploadCounter, setReUploadCounter] = useState(0);

  const passCount = checkResult?.passRows ?? 0;
  const failCount = checkResult?.failRows ?? 0;

  const goPrev = () => {
    setCurrentStep((s) => (s > 0 ? ((s - 1) as 0 | 1 | 2 | 3) : s));
  };
  const goNext = () => {
    setCurrentStep((s) => (s < 3 ? ((s + 1) as 0 | 1 | 2 | 3) : s));
  };

  const handleFileChange = (f: File | null) => {
    setSelectedFile(f);
    // 移除文件时,同步清空校验结果 + 导入信息里的 3 个回显字段(保留 remark)
    // 注意:org/scene 用 undefined 而非 '',否则 antd Select 会把 '' 当成选中值,placeholder 不显示
    if (f === null) {
      setCheckResult(null);
      setImportInfo((prev) => ({
        org: undefined,
        scene: undefined,
        categories: [],
        remark: prev?.remark,
      }));
    }
  };

  /** 把后端用「/」分隔的多值字符串拆成数组,兼容空串、含空格的情况 */
  const splitMultiLabel = (raw: string | null | undefined): string[] => {
    if (!raw) return [];
    return raw
      .split('/')
      .map((s) => s.trim())
      .filter(Boolean);
  };

  const handleUploadSuccess = (vo: StoreImportCheckVO) => {
    setCheckResult(vo);
    setImportInfo((prev) => ({
      org: vo.orgPath,
      scene: vo.businessScene,
      categories: splitMultiLabel(vo.productCategories),
      remark: prev?.remark,
    }));
  };

  const handleReUpload = () => {
    // Step 2 重新上传:清空文件 + checkResult,回到 Step0 后由 UploadCard 打开文件选择对话框,
    // 用户重新选择文件后走正常 customRequest → runUpload → check 接口链路
    setSelectedFile(null);
    setCheckResult(null);
    setSubmitChecked(true);
    setCurrentStep(0);
    setReUploadCounter((c) => c + 1);
  };

  const handleFinalSubmit = async () => {
    const listingIds = checkResult?.listingIds ?? [];
    if (listingIds.length === 0) {
      message.warning('本次无可提交的上架记录(listingIds 为空)');
      return;
    }
    if (submitting) return;
    setSubmitting(true);
    try {
      const result = await store.submitImport({ listingIds });
      setCheckResult(result);
      modal.success({
        title: '提交审批成功',
        content: `涉及 ${listingIds.length} 条上架记录,请在「门店审批」中跟踪进度。`,
        okText: '前往门店审批',
        okButtonProps: { type: 'primary' },
        cancelText: '知道了',
        // 非阻塞(不强制跳转):「知道了」留在当前页
        onOk: () => {
          // 跳转门店审批页,tab=mine 默认定位到「我发起的」页签
          window.location.href = '/store/approval?tab=mine';
        },
      });
    } catch (e) {
      message.error((e as Error).message ?? '提交审批失败');
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) return <Skeleton />;

  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <PageHeader />
      <NoticeSection />
      <StepsBar current={currentStep} />

      {currentStep === 0 && (
        <>
          <ImportInfoCard
            values={importInfo ?? undefined}
            checkResult={checkResult}
            onChange={(v) => setImportInfo(v)}
          />
          <UploadCard
            file={selectedFile}
            remark={importInfo?.remark}
            checkResult={checkResult}
            reUploadTrigger={reUploadCounter}
            onFileChange={handleFileChange}
            onUploadSuccess={handleUploadSuccess}
          />
          <UploadActionBar disabled={!checkResult} onNext={goNext} />
        </>
      )}

      {currentStep === 1 && (
        <>
          <ValidationStats checkResult={checkResult ?? undefined} />
          <FailDetailCard
            checkResult={checkResult ?? undefined}
            fileSize={selectedFile?.size}
            onReUpload={handleReUpload}
          />
          <ValidationActionBar nextDisabled={failCount > 0} onBack={goPrev} onNextStep={goNext} />
        </>
      )}

      {currentStep === 2 && (
        <>
          {(() => {
            // Step3 基于 previewRows(只含通过行)派生场景/分类数量,确保标题和 footer 都按通过数量显示
            const previewRows = checkResult?.previewRows ?? [];
            const ruleSceneCount = new Set(previewRows.map((r) => r.businessScene).filter(Boolean))
              .size;
            const ruleCategoryCount = new Set(
              previewRows.map((r) => r.productCategory).filter(Boolean),
            ).size;
            return (
              <>
                <PolicyConfirmHeader
                  storeName={checkResult?.storeName}
                  totalRows={checkResult?.productCategoryRowCount}
                  passRows={checkResult?.passRows}
                  failRows={checkResult?.failRows}
                />
                <PolicyConfirmTable
                  previewRows={checkResult?.previewRows}
                  ruleSceneCount={ruleSceneCount || undefined}
                  ruleCategoryCount={ruleCategoryCount || undefined}
                  ruleTotalRows={passCount || undefined}
                />
                <ConfirmActionBar passCount={passCount} onBack={goPrev} onSubmit={goNext} />
              </>
            );
          })()}
        </>
      )}

      {currentStep === 3 && (
        <>
          <SubmitConfirmCard
            checkResult={checkResult ?? undefined}
            checked={submitChecked}
            onCheckedChange={setSubmitChecked}
          />
          <ApprovalChainPreview />
          <SubmitActionBar
            totalRows={checkResult?.listingIds?.length ?? passCount}
            loading={submitting}
            disabled={!submitChecked || (checkResult?.listingIds?.length ?? 0) === 0}
            onBack={goPrev}
            onSubmit={handleFinalSubmit}
          />
        </>
      )}
    </div>
  );
}