Blame view

src/pages/Order/components/ConfirmReceiptModal.tsx 6.1 KB
1
import { RESPONSE_CODE } from '@/constants/enum';
zhongnanhuang authored
2
import { postServiceOrderConfirmReceipt } from '@/services';
3
4
import { PlusOutlined } from '@ant-design/icons';
import { Button, Modal, Upload, message } from 'antd';
zhongnanhuang authored
5
import { RcFile, UploadFile, UploadProps } from 'antd/es/upload';
zhongnanhuang authored
6
7
8
import { cloneDeep } from 'lodash';
import { useEffect, useRef, useState } from 'react';
import { COMFIR_RECEIPT_IMAGES_NUMBER } from '../constant';
zhongnanhuang authored
9
export default ({ data, onClose }) => {
10
  // const [form] = Form.useForm<{ name: string; company: string }>();
zhongnanhuang authored
11
12
13
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
zhongnanhuang authored
14
  const fileListObj = useRef<UploadFile[]>([]); //使用引用类型,使得在useEffect里面设置监听事件后,不用更新监听事件也能保持obj与外界一致
zhongnanhuang authored
15
16
17
18
19
20
21
22
23
  const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState(false);
24
  const handleCancel = () => setPreviewOpen(false);
zhongnanhuang authored
25
26
27
28
29

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    //fileListObj得在change里变化,change的参数是已经处理过的file数组
    //beforeUpload中的参数file是未处理过,还需要Base64拿到文件数据处理
    fileListObj.current = newFileList;
30
    setFileList(newFileList);
zhongnanhuang authored
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
  };

  /** 粘贴快捷键的回调 */
  const onPaste = async (e: any) => {
    /** 获取剪切板的数据clipboardData */
    let clipboardData = e.clipboardData,
      i = 0,
      items,
      item,
      types;

    /** 为空判断 */
    if (clipboardData) {
      items = clipboardData.items;
      if (!items) {
        message.info('您的剪贴板中没有照片');
        return;
      }

      item = items[0];
      types = clipboardData.types || [];
      /** 遍历剪切板的数据 */
      for (; i < types.length; i++) {
        if (types[i] === 'Files') {
          item = items[i];
          break;
        }
      }

      /** 判断文件是否为图片 */
      if (item && item.kind === 'file' && item.type.match(/^image\//i)) {
        const imgItem = item.getAsFile();
        const newFileList = cloneDeep(fileListObj.current);
        let filteredArray = newFileList.filter(
          (obj) => obj.status !== 'removed',
        ); //过滤掉状态为已删除的照片
        const listItem = {
          ...imgItem,
          status: 'done',
          url: await getBase64(imgItem),
          originFileObj: imgItem,
        };
zhongnanhuang authored
73
zhongnanhuang authored
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
        if (filteredArray.length >= COMFIR_RECEIPT_IMAGES_NUMBER) {
          message.info('发货凭证照片数量不能超过3');
          return;
        }
        fileListObj.current = filteredArray;
        filteredArray.push(listItem);
        setFileList(filteredArray);
        return;
      }
    }

    message.info('您的剪贴板中没有照片');
  };
  useEffect(() => {
    document.addEventListener('paste', onPaste);
    return () => {
      document.removeEventListener('paste', onPaste);
    };
  }, []);
93
94
95
96
97
98
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传凭证</div>
    </div>
  );
zhongnanhuang authored
99
100
101
102
103
104
105
  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
    setPreviewTitle(
zhongnanhuang authored
106
107
108
      file.name ||
        file.originFileObj?.name ||
        file.url!.substring(file.url!.lastIndexOf('/') + 1),
zhongnanhuang authored
109
110
111
112
113
    );
  };

  const handleUpload = async () => {
    const formData = new FormData();
114
115
116
117
118
119
    fileList.forEach((file) => {
      //originFileObj二进制文件
      formData.append('files', file.originFileObj as RcFile);
    });
    // console.log(fileList[0] as RcFile)
    // formData.append('file', fileList[0] as RcFile);
zhongnanhuang authored
120
121
122
    formData.append('id', data.id);
    setUploading(true);
    // You can use any AJAX library you like
123
124
125
126
127
128
129
130
131
132
133
134
    const res = await postServiceOrderConfirmReceipt({
      data: formData,
      headers: {
        'Content-Type':
          'multipart/form-data; boundary=----WebKitFormBoundarynl6gT1BKdPWIejNq',
      },
    });

    if (res.result === RESPONSE_CODE.SUCCESS) {
      message.success(res.message);
      onClose();
    }
zhongnanhuang authored
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149

    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;
    },
150
    listType: 'picture-card',
zhongnanhuang authored
151
152
    onPreview: handlePreview,
    fileList,
153
    onChange: handleChange,
zhongnanhuang authored
154
    accept: 'image/png, image/jpeg, image/png',
zhongnanhuang authored
155
156
157
  };

  return (
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
    <>
      <Modal
        width={500}
        open
        title="确认收货"
        footer={[
          <Button key="cancel" onClick={onClose}>
            取消
          </Button>,
          <Button
            type="primary"
            key="ok"
            onClick={handleUpload}
            disabled={fileList.length === 0}
            loading={uploading}
          >
            {uploading ? '上传中' : '提交'}
          </Button>,
        ]}
        onCancel={async () => {
          onClose();
        }}
      >
zhongnanhuang authored
181
182
183
184
185
        <div className="pt-4 font-semibold">请将买家确认收货的凭证照片上传</div>
        <div className="pb-4 text-xs decoration-gray-50">可复制照片粘贴</div>
        <Upload {...props}>
          {fileList.length < COMFIR_RECEIPT_IMAGES_NUMBER ? uploadButton : ''}
        </Upload>
186
187
188
189
190
191
      </Modal>
      <Modal
        open={previewOpen}
        title={previewTitle}
        footer={null}
        onCancel={handleCancel}
zhongnanhuang authored
192
      >
zhongnanhuang authored
193
        <img alt="图片预览" style={{ width: '100%' }} src={previewImage} />
194
195
      </Modal>
    </>
zhongnanhuang authored
196
197
  );
};