import React from 'react'
import { Upload, message, Button} from 'antd';
import { PlusOutlined } from '@ant-design/icons';

class AliyunOSSUpload extends React.Component {
  state = {
    OSSData: {},
  };

  componentDidMount() {
    this.init();
  }

  init = () => {
    try {
      const { OSSData } = this.props;

      this.setState({
        OSSData,
      });
    } catch (error) {
      message.error(error);
    }
  };

  onChange = ({ file, fileList }) => {
    const { onChange, onDone , onUploading} = this.props;
    console.log('Aliyun OSS:', file, fileList);
    if (onChange) {
      onChange([...fileList]);
    }

    if (onDone) {
      if (file.status === 'done')
        onDone(file)
    }
    if(onUploading && file.status === 'uploading') {
      onUploading({ file, fileList })
    }
    this.setState({ fileList: [...fileList] });
  };

  onRemove = file => {
    const { value, onChange } = this.props;

    const files = value.filter(v => v.url !== file.url);

    if (onChange) {
      onChange(files);
    }
  };

  transformFile = file => {
    const { OSSData } = this.state;
    file.url = OSSData.dir + file.name;
    return file;
  };

  getExtraData = file => {
    const { OSSData } = this.state;

    return {
      key: file.url,
      OSSAccessKeyId: OSSData.accessid,
      policy: OSSData.policy,
      Signature: OSSData.signature,
    };
  };

  beforeUpload = async () => {
    const { OSSData } = this.state;
    const expire = OSSData.expire * 1000;

    if (expire < Date.now()) {
      await this.init();
    }
    return true;
  };

  render() {
    const { value, directory, label, noStyle, showUploadList, accept } = this.props;
    const props = {
      name: 'file',
      fileList: this.state.fileList,
      action: this.state.OSSData.host,
      onChange: this.onChange,
      onRemove: this.onRemove,
      transformFile: this.transformFile,
      data: this.getExtraData,
      beforeUpload: this.beforeUpload,
      accept: accept,
      showUploadList: showUploadList !== false,
      headers: { "Access-Control-Allow-Origin": "*" }
    };
    return (
      <Upload {...props} directory={directory}>
        {noStyle ? label : (<Button type="primary">
          <PlusOutlined /> {label}
        </Button>)}

      </Upload>
    );
  }
}


export default AliyunOSSUpload;
