import React from 'react';
import { Modal, Input, Form, message } from 'antd';
import ShowTips from '@/bu-components/ShowTip';
import './CreateFolderModal.less';

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, title = '新建文件夹', folderPathList } = this.props;
    let showTip = null;
    if (folderPathList) {
      showTip = folderPathList.length < 2 ? true : false;
    } else {
      showTip = true;
    }
    return (
      <Modal
        title={title}
        visible={isOpen}
        onCancel={this.handleCancel}
        onOk={this.handleOk}
        width={448}
        maskClosable={false}
        className="create-folder-modal"
      >
        <Form>
          <Form.Item
            required
            help={ !validate && warnText}
            validateStatus={!validate ? 'error' : null}
          >
          {
            this.props.disk === 'COMMON' && window.NewVersion && showTip &&
            <div className="show-tip">
              <ShowTips message="创建后仅自己可以查看，如需其他成员查看请设置权限" />
            </div>
          }
          <Input
            value={folderName}
            placeholder="请输入文件夹名称"
            style={{width: '400px'}}
            onChange={this.handleChangeFolderName}
            maxLength="50"
            ref="folderNameInput"
          />
          </Form.Item>
        </Form>
        <div className="create-tip">创建后仅自己可查看，如需其他成员查看请设置权限</div>
      </Modal>
    )
  }
}

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