import React, { PureComponent } from 'react';
import { Upload, Icon, message } from 'antd';
import apis from '@/services/api';
import axios from 'axios';

class Uploader extends PureComponent {
  state = {
    key: '',
    url: '',
    imageUrl: '',
  }

  // 这里可以做上传之前的操作，比如文件大小的校验等
  beforeUpload = async (file) => {
    const res = await this.fetchUploadToken();
    return res;
  }

  // 获取上传凭证
  fetchUploadToken = async () => {
    const params = {
      quantity: 1,
      module: 3,
      fileType: 1,
    };
    const res = await apis.fileSign(params);
    const { d, m } = res;
    if (m === 'success') {
      const { key, url } = d.l[0];
      this.setState({ key, url });
      return true;
    } else {
      return false;
    }
  }

  render() {
    const { imageUrl, url, key } = this.state;
    const that = this;
    const uploadProps = {
      name: 'file',
      showUploadList: false,
      multiple: false,
      accept: '.png, .jpg, .jpeg, .gif',
      action: url,
     // beforeUpload: that.beforeUpload,
      // 这里需要指定文件上传的content-type
      headers: {
        'Content-Type': 'application/octet-stream',
      },
      // 自定文件上传的方法，覆盖组件的 onChange 方法，可以定义上传不同阶段的行为（由 axios 默认提供）
      onStart(file) {
        console.log('onStart', file, file.name);
      },
      onSuccess(ret, file) {
        console.log('onSuccess', ret, file);
        that.props.getData(key);
      },
      onProgress({ percent }, file) {
        console.log('onProgress', `${percent}%`, file.name);
      },
      onError(err) {
        console.log('onError', err);
      },
      customRequest({
        action,
        file,
        headers,
        onError,
        onProgress,
        onSuccess,
        withCredentials,
      }) {
        // 使用 FileReader 将上传的文件转换成二进制流，满足 'application/octet-stream' 格式的要求
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        let fileData = null;
        reader.onload = (e) => {
          // 在文件读取结束后执行的操作
          fileData = e.target.result;
          // 使用 axios 进行文件上传的请求
          axios.put(action, fileData, {
            withCredentials,
            headers,
            onUploadProgress: ({ total, loaded }) => {
              // 进行上传进度输出，更加直观
              onProgress({ percent: Math.round(loaded / total * 100).toFixed(2) }, file);
            },
          }).then(response => {
              onSuccess(response, file);
            })
            .catch(onError);
        };
        return {
          abort() {
            console.log('upload progress is aborted.');
          },
        };
      },
    };
    return (
      <div>
        <Upload {...uploadProps}>
          { imageUrl ? <img src={imageUrl} /> : <Icon type='plus' /> }
        </Upload>
      </div>
    );
  }
}

export default Uploader;
