import React from 'react'
import { Tag, Input, Tooltip, Icon } from 'antd';

class EditableTagGroup extends React.Component {
  state = {
    inputVisible: false,
    inputValue: '',
  };

  // 每次取值，都从 this.props.value 获取最新值
  getTags = () => (this.props.value || '').split(',')

  toggleOnChange = tags => {
    if (typeof this.props.onChange === 'function') {
      this.props.onChange(tags.join(','))
    }
  }

  handleClose = removedTag => {
    const tags = this.getTags().filter(tag => tag !== removedTag);
    // this.setState({ tags });
    this.toggleOnChange(tags)
  };

  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  };

  handleInputChange = e => {
    this.setState({ inputValue: e.target.value });
  };

  handleInputConfirm = () => {
    const { inputValue } = this.state;

    const tags = this.getTags()
    if (inputValue && tags.indexOf(inputValue) === -1) {
      // 如果有新的值，就把这个值追加到 tags 原本值的后面，在通过onChange事件传递出去
      this.toggleOnChange(tags.concat(inputValue))
    }

    this.setState({
      inputVisible: false,
      inputValue: '',
    });
  };

  saveInputRef = input => (this.input = input);

  render() {
    const { inputVisible, inputValue } = this.state;

    return (
      <div>
        {this.getTags().map((tag, index) => {
          const isLongTag = tag.length > 20;
          const tagElem = (
            <Tag key={tag} closable onClose={() => this.handleClose(tag)}>
              {isLongTag ? `${tag.slice(0, 20)}...` : tag}
            </Tag>
          );
          return isLongTag ? (
            <Tooltip title={tag} key={tag}>
              {tagElem}
            </Tooltip>
          ) : (
            tagElem
          );
        })}
        {inputVisible && (
          <Input
            ref={this.saveInputRef}
            type="text"
            size="small"
            style={{ width: 78 }}
            value={inputValue}
            onChange={this.handleInputChange}
            onBlur={this.handleInputConfirm}
            onPressEnter={this.handleInputConfirm}
          />
        )}
        {!inputVisible && (
          <Tag onClick={this.showInput} style={{ background: '#fff', borderStyle: 'dashed' }}>
            <Icon type="plus" /> 新建
          </Tag>
        )}
      </div>
    );
  }
}

export default EditableTagGroup
