import React, { Component } from 'react'; import PropTypes from 'prop-types';
import { Form,Icon,Input,Button } from 'amos-antd';
import './style/filter.scss';

const FormItem = Form.Item;
const createForm = Form.create;
/**
 * 模糊匹配
 *
 * @class VagueTextFilter
 * @extends {Component}
 */
class VagueTextFilter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.vagueExtra !== this.props.vagueExtra){
      this.setState({
        value: ''
      });
    }
  }

  isTextSearch = () => {
    let { filterSearchModel } = this.props;
    let filter = filterSearchModel.filter((e)=> e.primary === true && e.st === 'text');
    return filter;
  }

  handelChange = (e) => {
    let value = e.target.value;
    let { invokeFeDataFilter } = this.props;
    this.setState({ value }, invokeFeDataFilter(value));
  }

  handleClick = () => {
    let primaryFilter = this.isTextSearch()[0];
    let obj = {};
    obj[primaryFilter.dataIndex] = this.state.value;
    this.props.changeFilters(obj);
  }

  handleReset = (e) => {
    e.preventDefault();
    this.props.form.resetFields();
    this.props.changeFilters({});
    this.setState({
      value: ''
    });
  }
  render() {
    let primaryFilter = this.isTextSearch()[0];
    let display = { display: primaryFilter ? 'block' : 'none' };
    let placeholder = `${primaryFilter.title}搜索`;
    return (
      <div className='amos-filter-content' style={display} >
        <Form inline onSubmit={this.handleSubmit} className='vague-filter'>
          <FormItem>
            <Input
              className='vague-input'
              value={this.state.value}
              onChange={this.handelChange}
              addonAfter={<Icon onClick={this.handleClick} type="search" />}
              placeholder={placeholder}
            />
          </FormItem>
          <Button className='vague-button' onClick={this.handleReset}>
            <Icon onClick={this.handleReset} type="reload" />重置
          </Button>
        </Form>
      </div>
    );
  }
}

VagueTextFilter.propTypes = {
  form: PropTypes.any,
  invokeFeDataFilter: PropTypes.func, // 执行前端数据过滤
  vagueExtra: PropTypes.any, // 模糊匹配额外条件
  filterSearchModel: PropTypes.array,//表格列模型，默认值空数组
  changeFilters: PropTypes.func//表格过滤条件变化方法，用于回调获取表格搜索条件
};

VagueTextFilter.defaultProps = {
  invokeFeDataFilter(){}
};

export default createForm()(VagueTextFilter);
