import { PlusOutlined } from '@ant-design/icons';
import { Upload, Modal, message } from 'antd';
import React from 'react';
import config from '../../../config/env.config';
import { qiniuToken } from '@/services/qiniu';

const qiniu = require('@/utils/qiniu.min.js');

const { qiniuHost } = config;

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
let token = null;

class PicturesWall extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    fileList: [],
  };

  async componentDidMount() {
    token = await qiniuToken();
  }

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    const fileC = file;
    if (!file.url && !file.preview) {
      fileC.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: fileC.url || fileC.preview,
      previewVisible: true,
    });
  };

  handleChange = info => {
    const lastFile = (info.fileList.length && info.fileList[info.fileList.length - 1]) || [];
    const types = ['application/pdf', 'image/png', 'image/jpeg'];
    if (lastFile && types.indexOf(lastFile.type) === -1) {
      message.error('文件格式错误！');
    }
    const fileList = info.fileList.filter(item => types.indexOf(item.type) !== -1);
    this.setState({ fileList });
  };

  customRequest = ({ file, onError, onSuccess }) => {
    const observable = qiniu.upload(file, null, token);
    const observer = {
      next() {
        // ...
      },
      error() {
        onError(file);
        // ...
      },
      complete(res) {
        const comFile = file;
        const url = `${qiniuHost}/${res.hash}`;
        comFile.url = url;
        onSuccess(comFile);
        // ...
      },
    };
    observable.subscribe(observer); // 上传开始
  };

  getFileList = () => {
    const fileList = this.state.fileList.map(item => item.response?.url);
    return fileList;
  };

  clearFileList = () => {
    this.setState({
      fileList: [],
    });
  };

  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    const { max } = this.props;
    return (
      <div className="clearfix">
        <Upload
          customRequest={this.customRequest}
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          {...this.props}
        >
          {max && fileList.length >= max ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}
export default PicturesWall;
