BankImportModal.tsx 4.23 KB
import { RESPONSE_CODE } from '@/constants/enum';
import { postServiceBankStatementImportBankStatementForm } from '@/services';
import { UploadOutlined } from '@ant-design/icons';
import { ModalForm } from '@ant-design/pro-components';
import { Button, Form, Upload, UploadFile, UploadProps, message } from 'antd';
import { RcFile } from 'antd/es/upload';
import axios from 'axios';
import { useState } from 'react';

// import { cloneDeep } from 'lodash';
export default ({ setVisible, onClose }) => {
  const [form] = Form.useForm<{ name: string; company: string }>();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) =>
    setFileList(newFileList);

  const [messageApi] = message.useMessage();
  const [uploadLoading, setUploading] = useState(false);
  console.log(uploadLoading);

  const exportLoading = (content: string) => {
    messageApi.open({
      type: 'loading',
      content: content,
      duration: 0,
    });
  };

  const downloadImportTemplate = async () => {
    axios({
      url: '/api/service/bankStatement/exportTemplate',
      method: 'post',
      responseType: 'blob',
      headers: { Authorization: localStorage.getItem('token') },
    })
      .then((response) => {
        // 创建一个新的 Blob 对象,它包含了服务器响应的数据(即你的 Excel 文件)
        const blob = new Blob([response.data]); // Excel 的 MIME 类型
        const downloadUrl = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = downloadUrl;
        a.download = '银行流水导入模板.xlsx'; // 你可以为文件命名
        document.body.appendChild(a);
        a.click(); // 模拟点击操作来下载文件
        URL.revokeObjectURL(downloadUrl); // 释放掉 blob 对象所占用的内存
        document.body.removeChild(a);
      })
      .catch((error) => {
        // 处理错误
        console.error('导出错误', error);
      });
  };
  const handleUpload = async () => {
    const formData = new FormData();
    fileList.forEach((file) => {
      //originFileObj二进制文件
      formData.append('file', file.originFileObj as RcFile);
    });
    // console.log(fileList[0] as RcFile)
    // formData.append('file', fileList[0] as RcFile);
    setUploading(true);
    // You can use any AJAX library you like
    const res = await postServiceBankStatementImportBankStatementForm({
      data: formData,
      headers: {
        'Content-Type':
          'multipart/form-data; boundary=----WebKitFormBoundarynl6gT1BKdPWIejNq',
      },
    });

    if (res.result === RESPONSE_CODE.SUCCESS) {
      message.success(res.message);
      onClose();
    } else {
      if (res.message === '表格中没有数据') {
        setUploading(false);
        return;
      }
      //存在错误信息,下载错误信息模板
      exportLoading('正在下载错误信息...');
    }

    setUploading(false);
  };
  const props: UploadProps = {
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: (file) => {
      setFileList([...fileList, file]);

      return false;
    },
    fileList,
    onChange: handleChange,
    accept: '.xlsx',
  };

  return (
    <>
      <ModalForm<{
        name: string;
        company: string;
      }>
        width={500}
        open
        title="标题"
        form={form}
        autoFocusFirstInput
        modalProps={{
          okText: '确定',
          cancelText: '取消',
          destroyOnClose: true,
          onCancel: () => {
            setVisible(false);
          },
        }}
        onFinish={async () => {
          handleUpload();
          onClose();
        }}
        onOpenChange={setVisible}
      >
        <div className="py-4 font-semibold">
          导入银行流水
          <Button type="link" onClick={downloadImportTemplate}>
            下载导入模板
          </Button>
        </div>
        <Upload {...props}>
          <Button icon={<UploadOutlined />} disabled={fileList.length > 0}>
            点击选择文件
          </Button>
        </Upload>
      </ModalForm>
    </>
  );
};