import { Upload, Icon, Modal, message, Button, notification } from 'antd';
import React, { useState, useEffect } from 'react';
import config from '../../../../config/env.config';
import styles from '../style.less';
import UUID from '../../../utils/uuid';
import { qiniuToken } from '@/services/qiniu';

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

const { qiniuHost } = config;

let token = null;

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

  async componentDidMount() {
    this.initFileList(this.props.fileList || []);
    if (this.props.status === 1) {
      token = await qiniuToken();
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!nextProps?.fileList?.fileList) {
      this.initFileList(nextProps.fileList || []);
    }
  }

  initFileList = fileList => {
    const fileLists =
      fileList.map((item, index) => ({
        url: item.url,
        name: item.name ? item.name : '发票',
        uid: index,
        status: 'done',
      })) || [];
    this.setState({ fileList: fileLists });
  };

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

  customRequest = ({ file, onError, onSuccess }) => {
    let filename = '';
    let suffix = '';
    if (file.name) {
      const index = file.name.lastIndexOf('.');
      filename = file.name.substr(0, index);
      suffix = file.name.substr(index + 1, file.name.length - 1);
      const types = ['pdf', 'doc', 'docx', 'zip', 'rar', 'png', 'jpeg'];
      if (!types.includes(suffix)) {
        message.error('文件格式错误！');
        return;
      }
    }
    const vm = this;
    // eslint-disable-next-line new-cap
    const data = `${UUID.createUUID()}.${suffix}`;
    const observable = qiniu.upload(file, data, token);
    const observer = {
      next() {
        // ...
      },
      error(t) {
        if (t.code === 614) {
          notification.error({
            message: '文件名重复，请更换文件名。',
          });
        }
        onError(file);
        // ...
      },
      complete(res) {
        const comFile = file;
        const url = `${qiniuHost}/${res.key}`;
        comFile.url = url;
        const list = vm.state.fileList;
        list.push({
          url: file.url,
          name: file.name,
          uid: list.length,
          status: 'done',
        });
        vm.setState({ fileList: [...list] });
        vm.props.onChange(list);

        onSuccess(comFile);
        // ...
      },
    };
    observable.subscribe(observer); // 上传开始
  };

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

  render() {
    const { fileList } = this.state;
    const { status } = this.props;

    const uploadButton = (
      <div className={styles.uploadButton}>
        <Icon type="upload" />
        <span style={{ paddingLeft: '10px' }}>点击上传发票</span>
      </div>
    );
    const { max } = this.props;
    return (
      <div className="clearfix">
        <Upload
          {...this.props}
          customRequest={this.customRequest}
          listType="text"
          fileList={fileList}
          onRemove={status === 1 ? this.clearFileList : ''}
        >
          {max && fileList.length >= max ? null : uploadButton}
        </Upload>
      </div>
    );
  }
}
export default PicturesWall;
