import React from 'react';
import { Input } from 'antd';
import { debounce } from 'lodash';
import IconFont from '../../themeComponents/IconFont';
import './index.less';

class SearchInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.value || ''
    };
    this.debounced = null;
    this.inputRef = React.createRef();
    this.focusState = false;
    if (props.isEnterKey || props.onEnter) {
      document.addEventListener('keypress', this.initEnterEvent, false);
    }
  }

  componentWillUnmount() {
    document.removeEventListener('keypress', this.initEnterEvent, false);
    this.debounced && this.debounced.cancel();
    this.debounced = null;
    this.focusState = null;
    this.inputRef = null;
  }
  initEnterEvent = event => {
    if (this.props.isEnterKey && event.keyCode === 13 && this.focusState) {
      this.props.onChange && this.props.onChange(this.state.value);
    }
    if (this.props.onEnter && event.keyCode === 13 && this.focusState) {
      this.props.onEnter(this.state.value);
    }
  };
  // 增加防抖
  onChange = (value, isClear) => {
    const { isEnterKey, onChange } = this.props;
    this.setState({ value });
    if ((!isEnterKey && onChange) || isClear) {
      this.debounced && this.debounced.cancel();
      this.debounced = debounce(() => onChange(value), 200);
      this.debounced();
    }
  };
  clearInput = () => {
    this.setState({ value: '' });
  };
  onFocus = () => {
    this.focusState = true;
    this.props.onFocus && this.props.onFocus();
  };
  onBlur = () => {
    this.focusState = false;
    this.props.onBlur && this.props.onBlur();
  };
  autoFocusInput = () => {
    this.inputRef.current.input.focus();
  };
  render() {
    const { className = '', onChange, prefix, suffix, isEnterKey, hasPrefix = true, hasSuffix = true, onEnter, ...rest } = this.props;
    const IconState = this.state.value ? <IconFont type="icon-S_Edit_LineClose" onClick={() => this.onChange(null, true)} /> : null;
    return (
      <Input
        {...rest}
        className={`lm-c-search-input ${className}`}
        onChange={e => this.onChange(e.target.value)}
        prefix={prefix ? prefix : hasPrefix ? <IconFont type="icon-S_Edit_Search" /> : undefined}
        suffix={suffix ? suffix : hasSuffix ? IconState : undefined}
        value={this.state.value}
        onFocus={this.onFocus}
        onBlur={this.onBlur}
        ref={this.inputRef}
      />
    );
  }
}
export default SearchInput;
