import React from 'react';
import { Modal, Input, Form, message } from 'antd';

class CreateFolderModal extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      validate: true,
      warnText:  null,
      folderName: props.folderName
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.isOpen) {
      this.setState({
        folderName: nextProps.folderName
      });
    }
  }

  componentDidUpdate(prevProps) {
    // 输入框自动聚焦
    this.refs.folderNameInput && this.refs.folderNameInput.focus();
  }

  handleChangeFolderName = (event) => {
    const { value } = event.target;

    // 是否超出了限制
    const hasExceededLimit = value.length > 50;
    this.setState({
      folderName: value,
      validate: !hasExceededLimit,
      warnText: hasExceededLimit && '名称不能超过50个字'
    });
  }

  handleOk = () => {
    this.props.form.validateFields((err) => {
      const { folderName, validate } = this.state;
      if (!folderName) {
        this.setState({
          validate: false,
          warnText: '名称不能为空'
        });
        return;
      };

      if (!validate) return;
      
      this.props.onOk(folderName).then((res) => {
        // 防止新建和重命名的时候重复提示
        if (!this.props.title) {
          message.success('创建文件夹成功');
        }
      });
    });
  }

  handleCancel = () => {
    this.setState({
      validate: true
    });
    this.props.onClose();
  }

  render() {
    
    const { folderName, warnText, validate } = this.state;
    const { isOpen, form, title = '新建文件夹' } = this.props;
    const { getFieldDecorator } = form;
    
    return (
      <Modal
        title={title}
        visible={isOpen}
        onCancel={this.handleCancel}
        onOk={this.handleOk}
        maskClosable={false}
        closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
        width={448}
        className="create-folder-modal"
      >
        <Form>
          <Form.Item
            required
            help={ !validate && warnText}
            validateStatus={!validate ? 'error' : null}
          >
          <Input
            value={folderName}
            placeholder="请输入文件夹名称"
            style={{width: '348px'}}
            onChange={this.handleChangeFolderName}
            ref="folderNameInput"
          />
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}

// export default Form.create()(CreateFolderModal);
export default CreateFolderModal;