import React,{Component} from "react"; import {AutoComplete, message, Select,Spin} from "antd"; import $ from "jquery/src/ajax"; class AutoCompleteSearch extends Component{ constructor(props) { super(props); this.state={ contactsOption:[], autoCompleteSearchLoading:false, searchValue:props.config.searchValue } this.onSelect = this.onSelect.bind(this); this.onSearch = this.onSearch.bind(this); } onReset(){ this.setState({ searchValue:'' }) } onSelect(value,option){ let arr = this.state.contactsOption.filter(v=>v.value === value); this.setState({ searchValue:arr[0]['value'] }) this.props.onSelect(value,option.props.children) } onSearch(value){ if(this.state.autoCompleteSearchLoading){ this.ajax && this.ajax.abort(); } this.setState({ autoCompleteSearchLoading: true, searchValue: value }); if(value == "") { this.setState({ autoCompleteSearchLoading: false, }) return } let data = {}; data[this.props.config.search] = value this.ajax = $.ajax({ method: "get", dataType: "json", crossDomain: false, url: globalConfig.context + this.props.config.api, data, success: function (data) { let theArr = []; if (data.error && data.error.length === 0) { for(let i=0;i<data.data.length;i++){ let theData = data.data[i]; theArr.push( { value:theData.id, label:theData.name } ); }; this.setState({ contactsOption: theArr, }); }else{ message.warning(data.error[0].message); } }.bind(this), }).always(function () { this.setState({ autoCompleteSearchLoading: false }); }.bind(this)); } render() { const customerOptions = this.state.contactsOption.map((group) => ( <Select.Option key={group.label} value={group.value}> {group.label} </Select.Option> )); return ( <Spin spinning={this.state.autoCompleteSearchLoading}> <AutoComplete value={this.state.searchValue} dataSource={customerOptions} style={{ width: 200 }} onSelect={this.onSelect} onSearch={this.onSearch} placeholder={this.props.config.placeholder} /> </Spin> ) } } export default AutoCompleteSearch;