import React from 'react';
import { SingleTag } from '../TagItem';
import { Popover } from 'antd';
import _ from 'lodash';
import IconFont from '../../../themeComponents/IconFont';
import './index.less';

class TagInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.keywords || '',
    };
    this.isFocus = false;
    this.isOnComposition = false;
    this.inputRef = React.createRef();
  }
  static getDerivedStateFromProps(props, state) {
    if (props.keywords && state.value === '') {
      return { value: props.keywords };
    }

    return null;
  }
  componentDidMount() {
    document.body.addEventListener('click', this.computedVisible, false);
  }
  componentWillUnmount() {
    this.inputRef = null;
    document.body.removeEventListener('click', this.computedVisible, false);
    document.removeEventListener('keydown', this.debouncePress, false);
  }
  autoFocusInput() {
    this.inputRef.current.focus();
  }
  clearInput() {
    this.setState({ value: '' });
  }
  onFocusInput = () => {
    this.isFocus = true;
    document.addEventListener('keydown', this.debouncePress, false);
    this.props.openTagSelect();
  };
  onBlurInput = () => {
    this.isFocus = false;
    document.removeEventListener('keydown', this.debouncePress, false);
  };
  onCompositionStart = () => {
    this.isOnComposition = true;
  };
  onCompositionEnd = (e) => {
    this.isOnComposition = false;
    this.props.onInputChange(e.target.value);
  };
  handleChange = (e) => {
    if (!this.isOnComposition) {
      this.props.onInputChange(e.target.value);
    }
    this.setState({ value: e.target.value });
  };
  debouncePress = async (e) => {
    if (e.code === 'Backspace') {
      this.isOnComposition = false;
      this.debounced && this.debounced.cancel();
      this.debounced = _.debounce(() => this.deleteForPress(e), 200);
      this.debounced();
    }
    if (e.code === 'Enter') {
      await this.props.onInputChange(this.state.value, false);
      this.props.onSearch();
    }
  };
  deleteForPress = (e) => {
    const { pictureUrl, selectList } = this.props;
    if (!this.props.keywords && e.code === 'Backspace' && (selectList.length > 0 || !!pictureUrl)) {
      if (selectList.length > 0) {
        return this.props.deleteTag(selectList[selectList.length - 1]);
      }
      this.props.deleteImg();
    }
  };

  computedVisible = (e) => {
    const classList = ['search-image-input-view', 'tag-box-popup', 'mutiple-tag-popover-box', 'modal-select-face'];
    const path = e.path || [];
    let current = path.find((v) => {
      let flag = false;
      if (!v.classList) {
        return flag;
      }
      const classNames = Array.from(v.classList);
      for (let i = 0; i < classList.length; i++) {
        if (classNames.indexOf(classList[i]) > -1) {
          flag = true;
          break;
        }
      }
      return flag;
    });
    if (!current) {
      this.props.closePortal && this.props.closePortal();
    }
  };

  render() {
    let { pictureUrl, selectList, type, placeholder, disabled } = this.props;
    return (
      <div className="search-image-input-view">
        {!disabled && (
          <div className="object-search-btn">
            <IconFont
              onClick={async () => {
                await this.props.onInputChange(this.state.value, false);
                this.props.onSearch();
              }}
              type="icon-M_Bar_Search"
            />
          </div>
        )}
        <div className="input-image-box">
          <ImagePrev disabled={disabled} imgUrl={pictureUrl} onDeleteImg={this.props.deleteImg}></ImagePrev>
          <SelectedTags disabled={disabled} list={selectList} onDeleteTag={this.props.deleteTag}></SelectedTags>
          <input
            disabled={disabled}
            ref={this.inputRef}
            onChange={this.handleChange}
            type="text"
            onFocus={this.onFocusInput}
            onBlur={this.onBlurInput}
            value={this.state.value}
            onCompositionEnd={this.onCompositionEnd}
            onCompositionStart={this.onCompositionStart}
            className="search-image-input"
            placeholder={disabled ? '' : placeholder}
          />
        </div>
        {type === 'person' && !disabled && (
          <div className="object-search-btn">
            <IconFont onClick={this.props.openImgUpload} type="icon-L_Bar_AddImg" />
          </div>
        )}
        {type === 'vehicle' && !disabled && (
          <div className="object-search-btn">
            <IconFont onClick={this.props.openImgUpload} type="icon-L_Bar_AddImg" />
          </div>
        )}
      </div>
    );
  }
}

function SelectedTags({ list = [], onDeleteTag, disabled }) {
  if (list.length === 0) {
    return null;
  }
  return list.map((v) => {
    return (
      <SingleTag
        key={v.code}
        item={v}
        isActive={true}
        suffix={
          disabled ? null : (
            <span onClick={() => onDeleteTag(v)} className={`label-item-suffix-view `}>
              <IconFont type="icon-S_Edit_LineClose" />
            </span>
          )
        }
      />
    );
  });
}

function ImagePrev({ imgUrl, onDeleteImg, disabled }) {
  if (!imgUrl) {
    return null;
  }
  return (
    <Popover
      placement="bottom"
      overlayClassName="input-image-overlay"
      content={
        <div className="picture-box">
          <img className="picture-img" src={imgUrl} alt="" />
        </div>
      }
    >
      <div className="select-img-box">
        <img src={imgUrl} className="header-img" alt="" />
        {!disabled && <IconFont type="icon-S_Edit_LineClose" className="header-img-close" theme="outlined" onClick={onDeleteImg} />}

        <div className="modal-img" />
      </div>
    </Popover>
  );
}

export default TagInput;
