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

/**
 * 数据格式：[{ tagName: inputValue, delete: true, automatic: false }]
 * @param delete 是否删除
 * @param automatic 是否自动数据（比如获取地图数据就是自动的true，手动输入的是手动false）
 */
class EditableTagGroup extends React.Component {
  state = {
    inputVisible: false,
    inputValue: '',
  };

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

    return []
  }

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

  handleClose = removedTag => {
    const tags = this.getTags().filter(tag => tag.tagName !== 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()
    const tagList = tags.map(x => x.tagName)
    if (inputValue && tagList.indexOf(inputValue) === -1) {
      // 如果有新的值，就把这个值追加到 tags 原本值的后面，在通过onChange事件传递出去
      this.toggleOnChange(tags.concat([{ tagName: inputValue, delete: true, automatic: false }]))
    }

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

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

  render() {
    const { inputVisible, inputValue } = this.state;
    console.log('this.getTags(): ', this.getTags())
    return (
      <div>
        {this.getTags().map((tag, index) => {
          const isLongTag = tag.length > 20;
          const tagElem = (
            <Tag key={`${tag.tagName}${index}`} closable={ tag.delete } onClose={() => this.handleClose(tag.tagName)}>
              {isLongTag ? `${tag.slice(0, 20)}...` : tag.tagName}
            </Tag>
          );
          return isLongTag ? (
            <Tooltip title={tag.tagName} key={`${tag.tagName}${index}`}>
              {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
