import React from "react";
import _ from "lodash";
import { Select } from 'antd'
import { cache } from '@zenview/micro-utils';
import { Service } from '@zenview/micro-basic-library';

class SearchPio extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      adressArr: []
    };
    this.debounced = null;
  }
  componentWillUnmount() {
    this.debounced && this.debounced.cancel();
    this.debounced = null;
  }
  /*地图搜索*/
  onSearch = async value => {
    this.debounced && this.debounced.cancel();
    if (!value.trim()) {
      return await this.setState({ adressArr: [] });
    } else {
      this.debounced = _.debounce(() => this.requestAction(value), 500);
      this.debounced();
    }
  };
  requestAction = async value => {
    const res = await Service.$http({
      headers: {
        Authorization: cache.getCache('token', 'session'),
      },
      url: `/api/place/v1/inputAssistant`,
      method: 'post',
      data: { keywords: value },
      requestId: 'inputAssistant',
    })
    let adressArr = res.data || []
    adressArr.map(v => {
      v.value = v.location
      // v.label = v.address + v.district
      v.label = v.name
      return v
    })

    this.setState({ adressArr: res.data || [] });
  };
  /*定位*/
  jumpPoi = value => {
    if (!value) {
      return
    }
    let { adressArr } = this.state;
    let item = adressArr.find(v => v.location === value);
    let centerPoint = item ? item.location.split(",") : "";
    const [longitude, latitude] = centerPoint;
    item.longitude = longitude;
    item.latitude = latitude;
    this.props.getCenter && this.props.getCenter(item);
  };
  render() {
    let { adressArr } = this.state;

    return (
      <Select
        className="map-search-pio"
        showSearch
        allowClear
        itemKey="location"
        showArrow={false}
        filterOption={false}
        onSearch={this.onSearch}
        onChange={this.jumpPoi}
        defaultActiveFirstOption={false}
        placeholder="请输入关键词定位位置"
        options={adressArr}
      />
    );
  }
}
export default SearchPio;
