UploadCard.tsx 12.9 KB
import { useState, useCallback, useEffect, useRef } from 'react';
import { App } from 'antd';
import {
  InfoCircleFilled,
  UploadOutlined,
  CheckCircleFilled,
  CloseOutlined,
  FileExcelOutlined,
  LoadingOutlined,
} from '@ant-design/icons';
import type { UploadProps, UploadFile } from 'antd';
import type { RcFile } from 'antd/es/upload/interface';
import { UCard, UUpload, UText, UButton } from '@uj/ui';
import { store } from '@/api';
import type { StoreImportCheckVO } from '@/api/modules/store';
import { validateFileExtension, validateFileSize, UPLOAD_RULES } from '../tools/uploadValidate';

const TEMPLATE_NAME = '【优加】门店上架模版-V1.0.1.xlsx';

export interface UploadCardProps {
  file?: File | null;
  remark?: string;
  /** 上传后 check 接口返回结果(用于回显行数/门店数/场景数/分类数/版本) */
  checkResult?: StoreImportCheckVO | null;
  /** 父组件触发重新上传的信号:每次递增即自动重跑 runUpload(使用已选 file) */
  reUploadTrigger?: number;
  onFileChange?: (file: File | null) => void;
  onUploadSuccess?: (vo: StoreImportCheckVO) => void;
}

export function UploadCard({
  file,
  remark,
  checkResult,
  reUploadTrigger = 0,
  onFileChange,
  onUploadSuccess,
}: UploadCardProps) {
  const { message } = App.useApp();
  const [uploading, setUploading] = useState(false);
  const [downloading, setDownloading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  // antd Upload 实例,用于编程式打开文件选择框
  const uploadRef = useRef<any>(null);
  // 记录上一次已处理的 reUploadTrigger,防止 effect 因其它依赖变化而重复触发
  const processedTriggerRef = useRef(0);

  /** 从 checkResult + 文件名推导要显示的统计文案:共 N 行(X 家门店 × Y 场景 × Z 分类)· 模板版本 vX.X.X */
  const statLineText = (() => {
    if (!checkResult) return null;
    const previewRows = checkResult.previewRows ?? [];
    // 门店数:优先 storeName 存在即算 1 家;或从 previewRows 去重
    const storeCount = (() => {
      if (checkResult.storeName) return 1;
      const s = new Set(previewRows.map((r) => r.storeName).filter(Boolean));
      return s.size || 1;
    })();
    const sceneCount =
      // 注意:businessScene 是单值(名字里可能带 "/" 是组合名,不拆分),有值就算 1 个场景;
      // 多场景统计通过 previewRows 去重派生
      (checkResult.businessScene ? 1 : 0) ||
      new Set(previewRows.map((r) => r.businessScene).filter(Boolean)).size ||
      0;
    const categoryCount =
      (checkResult.productCategories
        ? new Set(
            checkResult.productCategories
              .split('/')
              .map((s) => s.trim())
              .filter(Boolean),
          ).size
        : 0) ||
      new Set(previewRows.map((r) => r.productCategory).filter(Boolean)).size ||
      0;
    const totalRows =
      typeof checkResult.productCategoryRowCount === 'number'
        ? checkResult.productCategoryRowCount
        : typeof checkResult.totalRows === 'number'
          ? checkResult.totalRows
          : previewRows.length || 0;

    // 模板版本:优先从文件名解析(xxx-V1.0.1.xlsx → v1.0.1);兜底 TEMPLATE_NAME 里的版本
    const fileVersion = (() => {
      const name = fileList[0]?.name || TEMPLATE_NAME || '';
      const m = name.match(/[Vv](\d+(?:\.\d+){0,3})/);
      if (m && m[1]) return `v${m[1]}`;
      const mm = TEMPLATE_NAME.match(/[Vv](\d+(?:\.\d+){0,3})/);
      return mm ? `v${mm[1]}` : 'v1.0.1';
    })();

    if (sceneCount > 0 && categoryCount > 0) {
      return `共 ${totalRows} 行数据(${storeCount} 家门店 × ${sceneCount} 个业务场景 × ${categoryCount} 个产品分类)· 模板版本 ${fileVersion}`;
    }
    return `共 ${totalRows} 行数据 · 模板版本 ${fileVersion}`;
  })();

  // 受控:父组件 file 变化时,同步内部 fileList(解决返回上一步组件重新挂载丢失文件的问题)
  useEffect(() => {
    if (file) {
      setFileList([buildUploadFile(file)]);
    } else {
      setFileList([]);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [file]);

  const clearFileState = useCallback(() => {
    setFileList([]);
    onFileChange?.(null);
  }, [onFileChange]);

  const handleRemove = useCallback(() => {
    clearFileState();
    message.info('已移除文件');
    return true;
  }, [clearFileState, message]);

  const handleDownloadTemplate = async (e?: React.MouseEvent) => {
    e?.stopPropagation?.();
    if (downloading || uploading) return;
    setDownloading(true);
    try {
      await store.downloadImportTemplate(TEMPLATE_NAME);
      message.success('模板下载成功');
    } catch (e) {
      message.error((e as Error).message ?? '模板下载失败');
    } finally {
      setDownloading(false);
    }
  };

  const buildUploadFile = (f: File): UploadFile => ({
    uid: Date.now().toString(),
    name: f.name,
    size: f.size,
    type: f.type,
    originFileObj: f as RcFile,
    status: 'done',
  });

  const runUpload = useCallback(
    async (f: File) => {
      if (!validateFileExtension(f.name)) {
        message.error(`仅支持 ${UPLOAD_RULES.ALLOW_EXTS.join(' / ')} 格式`);
        return;
      }
      if (!validateFileSize(f.size)) {
        message.error(
          `文件大小超过限制,单文件 ≤ 10MB(当前 ${(f.size / 1024 / 1024).toFixed(2)}MB)`,
        );
        return;
      }
      setUploading(true);
      try {
        const vo = await store.uploadImport({ file: f, remark });
        setFileList([buildUploadFile(f)]);
        onFileChange?.(f);
        onUploadSuccess?.(vo);
      } catch (e) {
        message.error((e as Error).message ?? '上传失败');
        clearFileState();
      } finally {
        setUploading(false);
      }
    },
    [remark, onFileChange, onUploadSuccess, clearFileState, message],
  );

  const customRequest: NonNullable<UploadProps['customRequest']> = (options) => {
    const f = options.file as File;
    void runUpload(f).finally(() => {
      options.onSuccess?.({ ok: true });
    });
  };

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    accept: UPLOAD_RULES.ALLOW_EXTS.join(','),
    showUploadList: false,
    customRequest,
    onRemove: handleRemove,
    fileList,
  };

  /**
   * Step 2 → 点击失败明细里的【重新上传】:
   *   父组件 handleReUpload = 切 Step0 + 清空 checkResult + reUploadCounter++
   * 本 effect 监听 reUploadTrigger 变化,清空已选文件并编程式打开文件选择对话框,
   * 让用户重新选择文件(选完文件后走正常 customRequest → runUpload → check 接口链路)。
   * 注意:不再自动用原文件调用 check 接口,必须由用户重新选文件。
   */
  useEffect(() => {
    if (reUploadTrigger <= 0) return;
    if (reUploadTrigger === processedTriggerRef.current) return;
    processedTriggerRef.current = reUploadTrigger;
    // 清空文件状态
    setFileList([]);
    onFileChange?.(null);
    // 等 DOM 更新后再打开文件选择框:兼容 antd Upload ref 可能不暴露 upload() 的情况,
    // 优先用 ref.upload(),兜底通过 DOM 查找隐藏的 input[type=file] 触发 click
    setTimeout(() => {
      const inst = uploadRef.current;
      if (inst && typeof inst.upload === 'function') {
        inst.upload();
        return;
      }
      const input = document.querySelector<HTMLInputElement>(
        '.uj-upload-dragger input[type="file"], .ant-upload input[type="file"]',
      );
      if (input) {
        input.value = '';
        input.click();
      }
    }, 0);
  }, [reUploadTrigger, onFileChange]);

  return (
    <UCard
      styles={{ body: { padding: 20 } }}
      style={{ border: '1px solid #E5E7EB', marginBottom: 20 }}
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <InfoCircleFilled style={{ color: '#2B5CE6', fontSize: 14 }} />
          <span style={{ fontSize: 15, fontWeight: 600 }}>上传门店上架表</span>
        </div>
      }
      extra={
        <UText type="secondary" style={{ fontSize: 12 }}>
          支持 {UPLOAD_RULES.ALLOW_EXTS.join(' / ')} · 单文件 ≤ 10MB · 单次导入 1 家门店(≤{' '}
          {UPLOAD_RULES.MAX_ROWS} 行)
        </UText>
      }
    >
      <div style={{ position: 'relative' }}>
        <UUpload.Dragger ref={uploadRef} {...uploadProps}>
          <div style={{ padding: '30px 0' }}>
            <div
              style={{
                width: 48,
                height: 48,
                borderRadius: 12,
                background: '#EEF2FF',
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginBottom: 16,
              }}
            >
              {uploading ? (
                <LoadingOutlined style={{ fontSize: 22, color: '#2B5CE6' }} />
              ) : (
                <UploadOutlined style={{ fontSize: 22, color: '#2B5CE6' }} />
              )}
            </div>
            <p
              className="ant-upload-text"
              style={{
                fontSize: 15,
                fontWeight: 500,
                color: '#374151',
                marginBottom: 8,
              }}
            >
              {uploading ? '上传中,请稍候...' : '点击选择文件,或拖拽到此处'}
            </p>
            <p
              className="ant-upload-hint"
              style={{
                fontSize: 12,
                color: '#9CA3AF',
                marginBottom: 6,
              }}
            >
              请使用《{TEMPLATE_NAME}》填写
              <UButton
                type="link"
                size="small"
                loading={downloading}
                disabled={uploading}
                style={{ padding: '0 4px', height: 'auto' }}
                onClick={handleDownloadTemplate}
              >
                下载最新模板
              </UButton>
            </p>
            <div
              style={{
                fontSize: 12,
                color: '#C7CDD6',
              }}
            >
              模板版本:v1.0.1 · 系统将校验模板版本一致性
            </div>
          </div>
        </UUpload.Dragger>
        {uploading && (
          <div
            style={{
              position: 'absolute',
              inset: 0,
              background: 'rgba(255,255,255,0.01)',
              cursor: 'not-allowed',
            }}
          />
        )}
      </div>

      {fileList[0] && (
        <div
          style={{
            marginTop: 16,
            display: 'flex',
            alignItems: 'center',
            padding: '14px 16px',
            background: '#F9FAFB',
            borderRadius: 8,
            border: '1px solid #E5E7EB',
          }}
        >
          <div
            style={{
              width: 36,
              height: 36,
              borderRadius: 8,
              background: '#E7F5EE',
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              marginRight: 12,
              flex: 'none',
            }}
          >
            <FileExcelOutlined style={{ color: '#16A34A', fontSize: 18 }} />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 8,
                marginBottom: 4,
              }}
            >
              <span
                style={{
                  fontSize: 14,
                  fontWeight: 600,
                  color: '#1A202C',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                }}
              >
                {fileList[0].name}
              </span>
              <CheckCircleFilled style={{ color: '#16A34A', fontSize: 16, flex: 'none' }} />
            </div>
            <div style={{ fontSize: 12, color: '#6B7280' }}>
              {fileList[0].size ? Math.max(1, Math.round(fileList[0].size / 1024)) : '-'} KB
              <CheckCircleFilled style={{ color: '#16A34A', fontSize: 12, marginLeft: 6 }} />
            </div>
            {statLineText && (
              <div
                style={{
                  marginTop: 6,
                  fontSize: 12,
                  color: '#4B5563',
                  lineHeight: 1.6,
                }}
              >
                {statLineText}
              </div>
            )}
          </div>
          <UButton
            type="text"
            size="small"
            icon={<CloseOutlined />}
            onClick={() => handleRemove()}
            style={{
              color: '#9CA3AF',
              padding: '4px 8px',
              flex: 'none',
              marginLeft: 8,
            }}
          >
            移除
          </UButton>
        </div>
      )}
    </UCard>
  );
}