import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Input, Button } from 'amos-framework';
import FilterBtn from './FilterBtn';

/**
 * 搜索栏
 */
class SearchBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      filterDisplay: 'hide-div',
      //搜索名称
      inputName: '',
      //选择的筛选条件，格式为filterList: [{name: 'dicIdCommMode',type: 'IN',value: filterList}]
      filterList: []
    };
  }

  //点击搜索
  onSearch = values => {
    let { inputName, filterList } = this.state;
    let newCriteriasList = [];
    for (var i = 0; i < filterList.length; i++) {
      let element = filterList[i];
      if ('dicIdCommMode' === element.name) {
        newCriteriasList.push(element);
      }
    }
    if (inputName.length !== 0) {
      newCriteriasList.push({ name: 'name', type: 'LIKE', value: inputName });
    }
    this.props.handleCriterias(newCriteriasList);
  };

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

  //筛选条件改变事件
  filterOnChange = selectedOption => {
    let communityFilterOptionsList = [];
    selectedOption.map(option => {
      if (option.selected) {
        communityFilterOptionsList.push(option.value);
      }
    });
    if (communityFilterOptionsList.length !== 0) {
      let communityCondition = [{ name: 'dicIdCommMode', type: 'IN', value: communityFilterOptionsList }];
      this.setState({ filterList: communityCondition });
    } else {
      this.setState({ filterList: [] });
    }
  };

  //显示筛选栏
  showFilter = () => {
    this.setState({ filterDisplay: 'show-div' });
  };

  //隐藏筛选栏
  hidFilter = () => {
    this.setState({ filterDisplay: 'hide-div' });
  };

  render() {
    let { filterDisplay } = this.state;
    let filterStyle = `search-filter ${filterDisplay}`;
    let modalStyle = `modal-box ${filterDisplay}`;
    return (
      <div className="search-bar">
        <div className="search-input">
          <Input placeholder="请输入搜索内容" onFocus={this.showFilter} onChange={this.onChange} />
          <Button onClick={this.onSearch}>搜索</Button>
          <div className={modalStyle} onClick={this.hidFilter} />
          <div className={filterStyle}>
            <FilterBtn filterOnChange={this.filterOnChange} {...this.props} />
          </div>
        </div>
      </div>
    );
  }
}

SearchBar.propTypes = {
  handleCriterias: PropTypes.func,
  communityOptions: PropTypes.array
};

export default SearchBar;
