import React, { Component } from 'react';
import Dropzone from 'react-dropzone';
import message from 'components/message';
import styles from './UploadCsvFile.less';
import {getAssetsUrl} from 'utils/utils';

interface IProps {
  onChange: Function;
  path?: string;
}

interface IState {
  file?: File | null;
}

export default class UploadCsvFile extends Component<IProps, IState> {
  success: boolean;
  constructor(props) {
    super(props);
    this.state = {
      file: null
    };
    this.success = false;
  }
  getStatusTips() {
    const { file } = this.state;
    if (file) {
      if (file.size > 10 * 1024 * 1024) {
        this.success = false;
        return (
          <div className={styles.wrap}>
            <div className={styles.fail}>
              <i className="icon iconfont icon-cuowu" />
              <span>上传失败</span>
            </div>
            <p>点击重新上传</p>
          </div>
        );
      } else {
        this.success = true;
        return (
          <div className={styles.wrap}>
            <div className={styles.csvIcon}>
              <i className="icon iconfont icon-csv-" />
            </div>
            <a>{file.name}</a>
            <p>点击更换文件</p>
          </div>
        );
      }
    } else {
      this.success = false;
      return (
        <div className={styles.wrap}>
          <i className={styles.uploadIcon} />
          <span style={{ color: 'rgba(180, 183, 193, 0.5)' }}>单击或拖放文件至此处进行上传，10M以内</span>
        </div>
      );
    }
  }
  onDrop = (file) => {
    const { onChange } = this.props;
    this.setState(
      {
        file: file[0]
      },
      () => {
        this.success && onChange(this.state.file);
      }
    );
  };

  download = (e) => {
    e.stopPropagation();
    const url = getAssetsUrl(`${this.props.path}`);
    window.open(url);
  };

  render() {
    return (
      <div className={styles.container}>
        <Dropzone
          className={styles.zone}
          accept=".csv"
          multiple={false}
          onDropRejected={() => {
            message.error('文件格式不正确');
          }}
          onDrop={this.onDrop}>
          {this.getStatusTips()}
        </Dropzone>
        {this.props.path && <i title="下载" className="icon iconfont icon-btn_export1 download" onClick={this.download} />}
      </div>
    );
  }
}
