import React, { Component } from "react";
import { AutoComplete, Input, message, Select } from "antd";
import $ from "jquery/src/ajax";

class StaffSearch extends Component {
    constructor(props) {
        super(props);
        this.state = {
            superior: '',
            customerArr: [],
            loading: false,
        }
        this.httpChange = this.httpChange.bind(this);
        this.supervisor = this.supervisor.bind(this);
        this.selectAuto = this.selectAuto.bind(this);
    }

    httpChange(e) {
        if (e.length >= 1) {
            this.supervisor(e);
        }
        this.setState({
            superior: e
        })
        this.props.onBlurText({ title: e });
        if (!e) {
            this.props.onBlurChange({ title: e, value: null });
        }
    }

    supervisor(e) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/organization/selectName",
            data: {
                name: e
            },
            success: function (data) {
                if (data.error.length === 0) {
                    this.setState({
                        customerArr: data.data,
                    });
                } else {
                    message.error(data.error[0].message)
                }
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    }

    selectAuto(value) {
        let theType = '';
        let contactLists = this.state.customerArr || [];
        if (value) {
            contactLists.map(function (item) {
                if (item.name == value.toString()) {
                    theType = item.id;
                }
            });
        }
        this.setState({
            superior: value
        })
        this.props.onBlurChange({ title: value, value: theType });
    }

    render() {
        const options = this.state.customerArr.map((group, index) =>
            <Select.Option key={index} value={group.name}>{group.name}</Select.Option>
        )
        return (
            <AutoComplete
                className="certain-category-search"
                dropdownClassName="certain-category-search-dropdown"
                dropdownMatchSelectWidth={false}
                size="large"
                style={{ width: '200px' }}
                dataSource={options}
                placeholder={this.props.placeholder}
                value={this.props.valueName}
                // value={this.state.superior ? this.state.superior : this.props.valueName}
                onChange={this.httpChange}
                filterOption={true}
                onSelect={this.selectAuto}
            >
                <Input />
            </AutoComplete>
        )
    }
}

export default StaffSearch;