import React, { PureComponent } from 'react'
import { Input, Icon, AutoComplete } from 'antd'

const { Option } = AutoComplete

class HeaderSearch extends PureComponent {
  constructor (props) {
    super(props)
    this.state = {
      searchMode: props.defaultOpen
    }
  }

  onChange = value => {
    const { onChange } = this.props
    onChange instanceof Function && onChange(value)
  }

  enterSearchMode = () => {
    this.setState({ searchMode: true }, () => {
      this.input.focus()
    })
  }

  leaveSearchMode = () => {
    this.setState({
      searchMode: false
    })
  }

  render () {
    const { theme, placeholder, dataSource, onSelect, icon, iconStyle } = this.props

    const options = dataSource.map(group => (
      <Option key={group.ID} value={group.ID}>
        {group.MenuName}({group.CODE})
      </Option>
    ))

    return (
      <div className={`opt-header-search ${theme}`} onClick={this.enterSearchMode}>
        {icon || <Icon type='search' className='opt-header-search__icon' style={iconStyle} />}
        <AutoComplete
          key='AutoComplete'
          className={`opt-header-search__input ${this.state.searchMode ? 'show' : ''}`}
          dataSource={options}
          onSelect={onSelect}
          onChange={this.onChange}
          optionLabelProp='MenuName'
          placeholder='搜索菜单'
        >
          <Input
            ref={ref => { this.input = ref }}
            aria-label={placeholder}
            placeholder={placeholder}
            onBlur={this.leaveSearchMode}
          />
        </AutoComplete>
      </div>
    )
  }
}

export default HeaderSearch
