import React, { Component } from 'react';
import { Icon, Button } from 'antd';
import './index.less';
import Logo from '../Logo';
import { search, uuid } from '../../services/Tools';

/**
 * demo
 * <FileUpload capture='camera' accept='image/*' onStart={() => {}} onEnd={() => {}} />
 */
class FileUpload extends Component {
  constructor(props) {
    super(props);
    this.FileInput = null;
    this.state = { uploading: false, type: props.type || 'image', fileName: '', key: 1 };
  }

  importFile() {
    if (this.FileInput) {
      this.FileInput.click();
    }
  }

  uploadFile(file, cb) {
    const suffix = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
    if (this.props.arrowSuffix) {
      if (search(this.props.arrowSuffix, null, suffix) === -1) {
        if (this.props.onError) this.props.onError(new Error('不支持该文件格式'));
        return;
      }
    }
    const name = uuid();
    this.setState({ uploading: true });
    if (this.props.onStart) this.props.onStart(this.state.type === 'image' ? file.preview : file.name);
    this.props
      .onUpload({ file, name: `${name}${suffix}` })
      .then(data => {
        this.setState({ uploading: false });
        if (this.props.onChange) this.props.onChange(data.url, file);
        if (this.props.onEnd) this.props.onEnd(data.url, file);
        if (cb) cb(data.url, file);
        this.setState({ fileName: file.name, key: this.state.key + 1 });
      })
      .catch(err => {
        this.setState({ uploading: false, key: this.state.key + 1 });
        if (this.props.onError) this.props.onError(err);
      });
  }

  onChange(e) {
    const files = this.getFiles(e);
    const file = files[0];
    this.uploadFile(file);
  }

  progress(data) {
    return done => {
      if (this.props.onProgress) this.props.onProgress(data);
      done();
    };
  }

  getFiles(e) {
    e.preventDefault();

    let f = null;
    if (e.dataTransfer) {
      f = e.dataTransfer.files;
    } else if (e.target) {
      f = e.target.files;
    }
    return f;
  }

  render() {
    const { accept = [] } = this.props;
    return (
      <div hidden={this.props.hidden} className={`file-upload type-${this.state.type}`} style={this.props.style}>
        <input
          key={this.state.key}
          hidden={this.props.hidden || this.props.disabled}
          type="file"
          ref={ref => {
            this.FileInput = ref;
          }}
          multiple={false}
          accept={this.state.type === 'file' ? accept.join(',') : 'image/x-png,image/jpeg'}
          onChange={e => this.onChange(e)}
        />
        {this.state.type === 'image' ? (
          this.props.src && !this.state.uploading ? (
            <img src={this.props.src} style={{ width: '100%', height: '100%' }} />
          ) : (
            <Icon type={this.state.uploading ? 'loading' : 'upload'} />
          )
        ) : (
          ''
        )}
        {this.state.type === 'logo' ? (
          <div>
            <Logo className="m-r-1" src={this.props.value} icon={this.props.icon} />
            <Button disabled={this.props.disabled}>
              <Icon type="upload" />
              上传
            </Button>
          </div>
        ) : (
          ''
        )}
        {this.state.type === 'file' ? (
          <span>
            <Button disabled={this.props.disabled} className="m-r-1">
              <Icon type={this.state.uploading ? 'loading' : 'upload'} /> {this.props.title}
            </Button>
            <div>{this.props.accept && `支持文件格式: ${this.props.accept.join(' ')}`}</div>
            {this.props.hiddenFile ? '' : this.state.fileName}
          </span>
        ) : (
          ''
        )}
      </div>
    );
  }
}

FileUpload.propTypes = {
  src: React.PropTypes.string,
  onProgress: React.PropTypes.function,
  onError: React.PropTypes.function,
  onEnd: React.PropTypes.function,
  onStart: React.PropTypes.function,
  onUpload: React.PropTypes.function,
  type: React.PropTypes.string,
  style: React.PropTypes.any,
};

export default FileUpload;
