import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form } from 'amos-framework';
import Modal from '../modal';
import { formRules, formLayout } from './../form/FormUtils';

const FormItem = Form.Item;
/**
 * 导入文件
 *
 * @class ImportFile
 * @extends {Component}
 */
class ImportFile extends Component {

  static propTypes = {
    onDownload: PropTypes.func
  };

  constructor(props) {
    super(props);
    this.state = {
      form: {},
      visible: false,
      rules: {
        file: [formRules.required()]
      },
      title: ''
    };
  }

  onOpen = (title, save) => {
    this.setState({ visible: true, title });
    this.save = save;
  }

  onSave = () => {
    this.form.validate((valid,dataValues) => {
      if (valid) {
        const formData = new window.FormData();
        formData.append('file', dataValues.file);
        this.save && this.save(formData).then(d => {
          this.onCancel();
        });
      }
    });
  }

  onCancel = () => {
    this.setState({
      form: {},
      visible: false
    });
  }

  onFileChange = (varName, value) => {
    const { form } = this.state;
    form[varName] = value;
    this.setState({ form });
  }

  render() {
    const { visible, form, title, rules } = this.state;
    const { accept } = this.props;
    return (
      <Modal
        modalClass=""
        width={450}
        visible={visible}
        onCancel={this.onCancel}
        onOk={this.onSave}
        okText="保存"
        title={`${title}` || '导入文件'}
      >
        <div>
          <Form className="eb-form-tablelist-filter-content" rules={rules} ref={form => this.form = form} model={form}>
            <FormItem className={formLayout('100', '100')} label={<span>选择文件</span>} field="file">
              <input
                ref={node => this.fileInput = node}
                type="file"
                name="avatar"
                accept={ accept || '.xls,.xlsx'}
                onChange={(e) => this.onFileChange('file', e.target.files[0])}
              />
            </FormItem>
          </Form>
        </div>
      </Modal>
    );
  }
}

ImportFile.propTypes = {
  accept: PropTypes.string
};

export default ImportFile;
