FailDetailCard.tsx 9.66 KB
import { useMemo } from 'react';
import { InfoCircleFilled, UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import { UCard, UButton } from '@uj/ui';
import type { StoreImportFailVO, StoreImportCheckVO } from '@/api/modules/store';

export interface FailDetailCardProps {
  checkResult?: StoreImportCheckVO;
  /** 上传文件的字节数(兜底:后端可能不返回 fileSize,用 File 对象的 size 字段) */
  fileSize?: number;
  /** 点击「重新上传」时触发(通常回到 Step 0 并清空文件) */
  onReUpload?: () => void;
}

const FAIL_COL_LABELS = [
  { key: 'rowIndex' as const, label: '行号', width: 92 },
  { key: 'storeName' as const, label: '门店名称', width: 300 },
  { key: 'merchantNo' as const, label: '门店商户号', width: 160 },
  { key: 'reason' as const, label: '失败原因', width: undefined },
] as const;

/** 触发下载失败明细文件(直接使用后端 failFileUrl) */
function triggerDownloadFailFile(url: string) {
  try {
    const a = document.createElement('a');
    a.href = url;
    a.target = '_blank';
    a.rel = 'noopener noreferrer';
    a.download = '失败明细.xlsx';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  } catch (e) {
    window.open(url, '_blank', 'noopener noreferrer');
  }
}

export function FailDetailCard({ checkResult, fileSize, onReUpload }: FailDetailCardProps) {
  const failRows = (checkResult?.failRows ?? 0) as number;
  const failFileUrl = checkResult?.failFileUrl ?? null;
  const failures = (checkResult?.failures ?? []) as StoreImportFailVO[];

  const hasFailures = Array.isArray(failures) && failures.length > 0;
  const hasFailFile = !!failFileUrl;

  // 失败明细为空也允许渲染(显示 0 条失败 + 底部通过说明)
  const shouldRender = failRows > 0 || hasFailures || hasFailFile;
  if (!shouldRender) return null;

  /**
   * 底部 L1 / L2 通过校验文字(复用 checkResult 的字段,无则从 failures.length 推断)
   */
  const l1 = useMemo(() => {
    // 文件大小:优先后端 fileSize,兜底用传入的 File.size(字节)
    const rawSize = typeof checkResult?.fileSize === 'number' ? checkResult.fileSize : fileSize;
    const size =
      typeof rawSize === 'number'
        ? rawSize === 0
          ? '0'
          : `${Math.max(1, Math.round(rawSize / 1024))}KB`
        : '';
    const total = typeof checkResult?.totalRows === 'number' ? `${checkResult.totalRows} 行` : '';
    const version = checkResult?.templateVersion ? `模板版本${checkResult.templateVersion}` : '';
    const parts = [
      checkResult?.failL1Passed === false
        ? '格式不正确 / 模板版本不一致,校验失败'
        : `格式 .xlsx / ${size}${total ? ' / ' + total : ''}${version ? ' / ' + version : ''}`,
    ];
    return parts.filter(Boolean).join(' · ');
  }, [checkResult, fileSize]);

  const l2 = useMemo(() => {
    const template = checkResult?.templateVersion
      ? `《模板${checkResult.templateVersion}》`
      : '《【优加】门店上架模版》';
    if (checkResult?.failL2Passed === false) {
      return `${template}(21 列) 存在缺失列或多余列,请重新下载模板填写`;
    }
    return `${template}(21 列) 全部列匹配,无缺失列、无多余列`;
  }, [checkResult]);

  const handleDownload = () => {
    if (!failFileUrl) return;
    triggerDownloadFailFile(failFileUrl);
  };

  return (
    <UCard
      styles={{ body: { padding: '18px 20px 14px' } }}
      style={{
        border: '1px solid #E5E7EB',
        marginBottom: 20,
        borderRadius: 12,
        background: '#fff',
        overflow: 'hidden',
      }}
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span
            style={{
              width: 8,
              height: 8,
              borderRadius: '50%',
              background: '#2563EB',
              flex: 'none',
            }}
          />
          <span style={{ fontSize: 17, fontWeight: 700, color: '#111827' }}>校验失败明细</span>
          {failRows > 0 && (
            <span style={{ fontSize: 13, color: '#9CA3AF', marginLeft: 4 }}>共 {failRows} 条</span>
          )}
        </div>
      }
      extra={
        <div style={{ display: 'flex', gap: 10 }}>
          <UButton icon={<DownloadOutlined />} onClick={handleDownload} disabled={!hasFailFile}>
            下载失败明细
          </UButton>
          <UButton
            icon={<UploadOutlined />}
            type="link"
            onClick={onReUpload}
            style={{ color: '#111827' }}
          >
            重新上传
          </UButton>
        </div>
      }
    >
      {/* 失败明细表头 + 明细行(原生 table,样式与截图一致) */}
      <div
        style={{
          width: '100%',
          maxHeight: 360,
          overflowX: 'auto',
          overflowY: 'auto',
          marginBottom: 14,
        }}
      >
        <table
          style={{
            width: '100%',
            borderCollapse: 'separate',
            borderSpacing: 0,
            tableLayout: 'fixed',
            fontSize: 13,
          }}
        >
          <colgroup>
            {FAIL_COL_LABELS.map((c) => (
              <col key={c.key} style={{ width: c.width ?? 'auto' }} />
            ))}
          </colgroup>
          <thead>
            <tr style={{ position: 'sticky', top: 0, zIndex: 1 }}>
              {FAIL_COL_LABELS.map((c) => (
                <th
                  key={c.key}
                  style={{
                    textAlign: 'left',
                    color: '#6B7280',
                    fontWeight: 400,
                    fontSize: 13,
                    padding: '10px 8px',
                    borderBottom: '1px solid #F3F4F6',
                    whiteSpace: 'nowrap',
                    background: '#fff',
                  }}
                >
                  {c.label}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {hasFailures ? (
              failures.map((f, i) => (
                <tr key={`${f.rowIndex ?? i}-${f.levelCode ?? ''}-${f.productCategory ?? ''}`}>
                  {/* 行号(蓝 #2563EB) */}
                  <td
                    style={{
                      padding: '14px 8px',
                      borderBottom: '1px solid #F3F4F6',
                      color: '#2563EB',
                      fontWeight: 500,
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {String(f.rowIndex ?? i + 1).padStart(2, '0')}
                  </td>
                  {/* 门店名称(深灰 普通字) */}
                  <td
                    style={{
                      padding: '14px 8px',
                      borderBottom: '1px solid #F3F4F6',
                      color: '#111827',
                      fontWeight: 500,
                      whiteSpace: 'nowrap',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                    }}
                    title={f.storeName}
                  >
                    {f.storeName ?? '-'}
                  </td>
                  {/* 门店商户号(蓝 #2563EB) */}
                  <td
                    style={{
                      padding: '14px 8px',
                      borderBottom: '1px solid #F3F4F6',
                      color: '#2563EB',
                      fontWeight: 500,
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {f.merchantNo ?? '-'}
                  </td>
                  {/* 失败原因(红 #991B1B) */}
                  <td
                    style={{
                      padding: '14px 8px',
                      borderBottom: '1px solid #F3F4F6',
                      color: '#991B1B',
                      fontWeight: 500,
                      lineHeight: 1.5,
                      wordBreak: 'break-all',
                    }}
                    title={f.reason}
                  >
                    {f.reason ?? '-'}
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td
                  colSpan={FAIL_COL_LABELS.length}
                  style={{
                    padding: '18px 8px',
                    color: '#6B7280',
                    fontSize: 13,
                    textAlign: 'center',
                    borderBottom: '1px solid #F3F4F6',
                  }}
                >
                  <InfoCircleFilled style={{ color: '#9CA3AF', marginRight: 6 }} />
                  明细已生成失败文件,请点击右上角「下载失败明细」查看完整失败原因
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* 底部 L1 / L2 校验说明(截图 2 行灰字) */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, paddingTop: 6 }}>
        <div style={{ fontSize: 13, color: '#6B7280', lineHeight: 1.6 }}>
          <span>表头级(L2)校验:</span>
          <span
            style={{
              color: '#047857',
              fontWeight: 600,
              margin: '0 6px',
            }}
          >
            通过
          </span>
          <span>—— {l2}</span>
        </div>
        <div style={{ fontSize: 13, color: '#6B7280', lineHeight: 1.6 }}>
          <span>文件级(L1)校验:</span>
          <span
            style={{
              color: '#047857',
              fontWeight: 600,
              margin: '0 6px',
            }}
          >
            通过
          </span>
          <span>—— {l1}</span>
        </div>
      </div>
    </UCard>
  );
}