import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Overlay } from 'amos-framework';
import ImageConsts from '@gm/graphmod-assets';
import './style.scss';

const ms = 1000; // 1000毫秒
const speed = 100; // 百分比进度
const halve = 900;
/**
 * 导入文档可以显示进度（模拟进度）
 *
 * @class ImportFile
 * @extends {Component}
 */
class ImportFile extends Component {

  static propTypes = {
    accept: PropTypes.string,
    canCancel: PropTypes.bool, // 上传过程中可否取消上传
    img: PropTypes.any, // 上传文件的类型图片
    time: PropTypes.number // 100k数据上传大概时间(毫秒)，用于模拟进度条
  };

  static defaultProps = {
    time: 1,
    img: ImageConsts.common.tech,
    onSave: () => new Promise((resolve, reject) => setTimeout(() => resolve(), ms))
  };

  constructor(props) {
    super(props);
    this.state = {
      file: {},
      time: 0,
      step: 0,
      visible: false,
      isRuning: false,
      isError: false
    };
  }

  onOpen = (save, cancel) => {
    this.save = save;
    this.cancel = cancel;
    this.content.click();
  }

  onFileChange = (file) => {
    const { time } = this.props;
    const formData = new window.FormData();
    formData.append('file', file);
    this.setState({ file, visible: true, isRuning: true, isError: false, time: (time / speed)  * file.size }, () => {
      this.timer = setInterval(() => {
        const { step } = this.state;
        if (step < halve) {
          this.setState({ step: step + 1 });
        } else {
          this.setState({ step: step + (ms - step) / ms });
        }
      }, this.state.time / ms);
    });

    this.save && this.save(formData).then(d => {
      this.setState({ isRuning: false, isError: false, step: 1000 });
      clearInterval(this.timer);
      setTimeout(() => this.onCancel(), ms);
    }).catch(d => {
      this.setState({ isRuning: false, isError: true });
      clearInterval(this.timer);
    });
  }

  onCancel = () => {
    clearInterval(this.timer);
    const formData = new window.FormData();
    formData.append('file', this.state.file);
    this.cancel && this.cancel(formData);
    this.form.reset();
    this.setState({
      visible: false,
      file: {},
      isRuning: false,
      isError: false,
      time: 0,
      step: 0
    });
  }

  render() {
    const { file, isRuning, isError, step } = this.state;
    const { accept } = this.props;
    return (
      <React.Fragment>
        <form ref={node => this.form = node} style={{ display: 'none' }}>
          <input
            ref={node => this.content = node}
            type="file"
            accept={accept}
            style={{ display: 'none' }}
            onChange={(e) => this.onFileChange(e.target.files[0])}
          />
        </form>
        <Overlay
          className="mods-com-importfile"
          maskClosable={false}
          visible={this.state.visible}
          onClose={this.onCancel}
        >
          <div className="mods-com-importfile-container">
            <div className="mods-com-importfile-header">
              {
                isRuning ? <div className="mods-com-importfile-title mods-com-importfile-running">
                  <img src={ImageConsts.common.uploadRunning} alt="" /><span>正在导入...</span></div> :
                  isError ? <div className="mods-com-importfile-title mods-com-importfile-error">
                    <img src={ImageConsts.common.uploadError} alt="" /><span>导入失败</span></div> :
                    <div className="mods-com-importfile-title mods-com-importfile-success">
                      <img src={ImageConsts.common.uploadSuccess} alt="" /><span>导入成功</span></div>
              }
              <div className="mods-com-importfile-close">
                { this.props.canCancel || (!isRuning && isError) && <img onClick={this.onCancel} src={ImageConsts.common.close} alt="" /> }
              </div>
            </div>
            <div className="mods-com-importfile-content">
              <div className="mods-com-importfile-info">
                <img src={this.props.img} alt="" />
                <span className="mods-com-importfile-name">
                  { file.name }
                </span>
                <span className="mods-com-importfile-stepvalue" style={{ color: isRuning ? '#CCC' : isError ? 'red' : '#1e6fff' }}>
                  {
                    isRuning ? `${parseInt(step / ms * speed)} %` : isError ? '导入失败,请重新导入' : '导入成功'
                  }
                </span>
              </div>
              <div className="mods-com-importfile-step" style={{ width: `calc(100% / 1000 * ${step})` }} />
            </div>
            <br />
          </div>
        </Overlay>
      </React.Fragment>

    );
  }
}

export default ImportFile;
