BankImportModal.tsx 5.28 KB
import { RESPONSE_CODE } from '@/constants/enum';
import { blobToJson } from '@/utils';

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, contextHolder] = 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 () => {
    exportLoading('正在下载......');
    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);
      })
      .finally(() => {
        messageApi.destroy();
      });
  };
  const handleUpload = async () => {
    exportLoading('正在导入......');

    const formData = new FormData();
    fileList.forEach((file) => {
      formData.append('file', file.originFileObj as RcFile);
    });

    setUploading(true);

    axios({
      url: '/api/service/bankStatement/importBankStatementForm',
      method: 'post',
      responseType: 'blob',
      headers: {
        Authorization: localStorage.getItem('token'),
        'Content-Type':
          'multipart/form-data; boundary=----WebKitFormBoundarynl6gT1BKdPWIejNq',
      },
      data: formData,
    })
      .then((response) => {
        let data = response.data;
        if (data.type === 'application/json') {
          blobToJson(data).then((dataJson) => {
            if (dataJson?.result === RESPONSE_CODE.SUCCESS) {
              message.success(dataJson?.message);
              onClose();
            } else {
              message.error(dataJson?.message);
            }
          });
        } else {
          message.error('上传失败,已下载错误信息表格');
          // 创建一个新的 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) => {
        // 处理错误
        message.error('系统出现异常了,请联系管理员', error);
      })
      .finally(() => {
        setUploading(false);
        messageApi.destroy();
      });
  };
  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();
        }}
        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>

      {contextHolder}
    </>
  );
};