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

class AliyunOSSUpload extends React.Component {
  state = {
    OSSData: { host: '' },
    fileList: [],
    url: '',
  };

  async componentDidMount() {
    await this.init();
  }

  init = async () => {
    try {
      let res = await getOSSCmsData();
      const OSSData = res.data;
      this.setState({
        OSSData,
      });
    } catch (error) {
      message.error(error);
    }
  };

  onChange = ({ file, fileList }) => {
    fileList = fileList.slice(-1);
    if (file.status === 'done') {
      this.setState({
        fileList,
        url: this.state.OSSData.host + '/' + file.url,
      });
    } else {
      this.setState({
        fileList,
        url: '',
      });
    }
    this.props.uploaded(this.state.url);
  };

  onRemove = (file) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange([]);
      this.setState({
        url: '',
      });
      this.props.uploaded(this.state.url);
    }
  };

  getExtraData = (file) => {
    const { OSSData } = this.state;
    this.setState({
      url: OSSData.host + '/' + file.url,
    });
    return {
      key: file.url,
      OSSAccessKeyId: OSSData.accessKeyId,
      policy: OSSData.policy,
      Signature: OSSData.signature,
      success_action_status: '200',
    };
  };

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

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

    if (this.props.isImg) {
      if (file.type !== 'image/png' && file.type !== 'image/jpeg') {
        message.error('图片格式错误');
        return Upload.LIST_IGNORE;
      }
    } else {
      console.log(file.type);
      if (
        file.type !== 'audio/ogg' &&
        file.type !== 'audio/x-wav' &&
        file.type !== 'audio/wav' &&
        file.type !== 'audio/mpeg' &&
        file.type !== 'audio/x-m4a'
      ) {
        message.error('音频格式错误');
        return Upload.LIST_IGNORE;
      }
    }

    const suffix = file.name.slice(file.name.lastIndexOf('.'));
    const filename = Date.now() + suffix;
    file.url = OSSData.ossDirPrefix + filename;

    return file;
  };

  render() {
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );

    const props = {
      name: 'file',
      action: this.state.OSSData.host,
      onChange: this.onChange,
      onRemove: this.onRemove,
      data: this.getExtraData,
      beforeUpload: this.beforeUpload,
      maxCount: 1,
      showUploadList: false,
    };

    const imgProps = {
      listType: 'picture-card',
      className: 'avatar-uploader',
    };

    if (this.props.isImg) {
      return (
        <Upload {...props} {...imgProps} fileList={this.state.fileList}>
          {this.state.url ? (
            <img width={100} height={100} src={this.state.url} alt="image" />
          ) : (
            uploadButton
          )}
        </Upload>
      );
    } else {
      return (
        <Upload {...props} fileList={this.state.fileList}>
          <Button icon={<UploadOutlined />}>
            {this.state.url ? '已上传(点击更换)' : '选择文件'}
          </Button>
        </Upload>
      );
    }
  }
}

export default AliyunOSSUpload;
