import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Input, Select, Group } from 'amos-framework';
import { trim } from 'amos-tool';
import imgStatic from 'CONSTS/imgStatic';

const Option = Select.Option;

const enterkey = 13;
/**
 *
 * @class Search
 * @extends {Component}
 */
class Search extends Component {

  static defaultProps = {
    searchType: 'input'
  };

  constructor(props) {
    super(props);

    this.state = {
      value: '',
      textValue: ''
    };
  }

  onClick = (e) => {
    const { searchType } = this.props;
    if (searchType !== 'selectAndInput') {
      this.props.onSearch(trim(this.state.value || ''));
    } else {
      this.props.onSearch(trim(this.state.textValue || ''));
    }
  }

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

  onTextChange = (e) => {
    this.setState({ textValue: e.target.value });
  }

  onSelectChange = (value) => {
    this.setState({ value });
    this.props.searchOnChange(trim(value || ''));
  }

  getSearchContent = () => {
    const { searchType, dataList } = this.props;
    if (searchType === 'input') {
      return (<Input
        value={this.state.value}
        onChange={this.onChange}
        onKeyPress={this.keypress}
      />);
    } else if (searchType === 'select') {
      return (
        <Select
          data={dataList}
          renderOption={item => <Option value={item.key}>{item.label}</Option>}
          defaultOption={<Option>请选择</Option>}
          onChange={this.onSelectChange}
        />);
    } else if (searchType === 'selectAndInput') {
      let groupStyle = { display: 'unset', width: '70%' };
      let selectStyle = { width: '45%', minWidth: '20%' };
      let inputStyle = { width: '30%', borderRadius: '0px', height: '28px' };
      return (<Group style={groupStyle}>
        <Select
          style={selectStyle}
          data={dataList}
          renderOption={item => <Option value={item.key}>{item.label}</Option>}
          defaultOption={<Option>全部</Option>}
          onChange={this.onSelectChange}
        />
        <Input
          style={inputStyle}
          value={this.state.textValue}
          onChange={this.onTextChange}
          onKeyPress={this.keypress}
        />
      </Group>);
    }
  }

  keypress = (e) => {
    if (e.which === enterkey ){
      this.props.onSearch(trim(this.state.value || ''));
    }
    return;
  }

  render() {
    const { width } = this.props;
    return (
      <div className="search-input" style={{ width }}>
        {
          this.getSearchContent()
        }
        <Button onClick={this.onClick}>
          <img src={imgStatic.datapane.search} alt="" />
        </Button>
      </div>
    );
  }
}

Search.propTypes = {
  width: PropTypes.any,
  onSearch: PropTypes.func,
  searchOnChange: PropTypes.func,
  dataList: PropTypes.array,
  searchType: PropTypes.string
};

export default Search;
