ImportContractModal.tsx 4.92 KB
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { UAlert, UButton, UModal, UText, UUpload, useUMessage } from '@uj/ui';
import { downloadCenter } from '@uj/platform-sdk';
import { contractApi } from '@/api';
import { uploadFileUrl } from '@/lib/ossUpload';
import { errorDetail } from '@/utils/error';

/**
 * 源合同导入弹窗(contract/index.vue:202-282 + 946-1043):
 * 选文件 → glsk-oss-jssdk 直传 OSS → 成功回调拿 aliyunAddress → 立刻调
 * importContract({ fileUrl }) → 展示成功/失败记录。弹窗不自动关闭。
 */
const TEMPLATE_URL =
  'https://jinrong-huidan-test.oss-cn-shenzhen.aliyuncs.com/template/15b20472-9d99-470d-aaff-67bcd243e0dc%E3%80%90%E6%A8%A1%E6%9D%BF%E3%80%91%E5%90%88%E5%90%8C%E5%AF%BC%E5%85%A5-V1.0.1.xlsx';

interface ImportResult {
  succ?: number;
  fail?: number;
  failDownloadUrl?: string;
  [key: string]: unknown;
}

interface ImportResponse {
  code?: number;
  msg?: string;
  data?: ImportResult;
}

export default function ImportContractModal({
  open,
  onClose,
  onSuccess,
}: {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}) {
  const msg = useUMessage();
  const [fileName, setFileName] = useState('');
  const [result, setResult] = useState<ImportResult | null>(null);

  const importMutation = useMutation({
    mutationFn: async (file: File) => {
      const fileUrl = await uploadFileUrl(file);
      return contractApi.importContract<ImportResponse>({ fileUrl });
    },
    onSuccess: (res) => {
      if (res?.code !== undefined && res.code !== 0) {
        msg.error(res.msg ?? '导入失败');
        return;
      }
      setResult(res?.data ?? {});
      msg.success('导入完成');
      onSuccess();
    },
    onError: (error) => {
      msg.error(errorDetail(error));
      setResult(null);
    },
  });

  const handleFile = (file: File) => {
    const size = file.size / 1024 / 1024;
    if (size >= 10) {
      msg.error('上传文件不可超过 10M');
      return false;
    }
    setFileName(file.name);
    setResult(null);
    importMutation.mutate(file);
    // 与源一致:不让 antd 自己再上传一次,上传完全交给 OSS SDK。
    return false;
  };

  return (
    <UModal
      open={open}
      title="合同导入"
      okText="关闭"
      confirmLoading={false}
      onCancel={onClose}
      onOk={onClose}
      width={560}
    >
      <UAlert
        type="info"
        showIcon
        title="选择合同信息表后自动导入"
        description="文件经 OSS 直传后自动提交导入,导入结果会显示在下方。可从右侧下载标准模板。"
        style={{ marginBottom: 16 }}
      />
      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        <UUpload
          accept=".xls,.xlsx"
          showUploadList={false}
          maxCount={1}
          disabled={importMutation.isPending}
          beforeUpload={handleFile}
        >
          <UButton loading={importMutation.isPending}>添加附件</UButton>
        </UUpload>
        <UText>{fileName || '请选择需要导入的合同信息表格'}</UText>
      </div>
      <div style={{ marginTop: 12, textAlign: 'right' }}>
        <UButton
          type="link"
          onClick={() =>
            downloadCenter.url({
              source: 'usedcar',
              sourceLabel: '运营管理 / 合同管理 / 导入模板',
              label: '合同导入模板',
              url: TEMPLATE_URL,
              fileName: '合同导入模板.xlsx',
              silent: true,
              dedupeKey: 'usedcar-contract-template',
            })
          }
        >
          下载模板
        </UButton>
      </div>
      {result ? (
        <UAlert
          type={Number(result.fail) > 0 ? 'warning' : 'success'}
          showIcon
          title="操作结果"
          description={
            <div>
              <div>
                成功记录 <span style={{ color: 'var(--uj-success)' }}>{result.succ ?? 0}</span>
                {' '}失败记录 <span style={{ color: 'var(--uj-error)' }}>{result.fail ?? 0}</span>
              </div>
              {result.failDownloadUrl ? (
                <UButton
                  type="link"
                  onClick={() =>
                    downloadCenter.url({
                      source: 'usedcar',
                      sourceLabel: '运营管理 / 合同管理 / 导入结果',
                      label: '合同导入失败记录',
                      url: result.failDownloadUrl!,
                      fileName: '合同导入失败记录.xlsx',
                      dedupeKey: `usedcar-contract-import-fail-${result.failDownloadUrl}`,
                    })
                  }
                  style={{ paddingLeft: 0 }}
                >
                  导出失败记录
                </UButton>
              ) : null}
            </div>
          }
          style={{ marginTop: 16 }}
        />
      ) : null}
    </UModal>
  );
}