import React from 'react';
import ReactDOM from 'react-dom';
import { Map, Marker } from 'react-amap'
import debounce from 'lodash.debounce'
import styles from './style.less'

const getPosFromProps = props => {
  if (props.value) {
    const temp = props.value.split(',')
    return { longitude: temp[0], latitude: temp[1] }
  } else {
    return null
  }
}

class AMapSearch extends React.PureComponent {

  constructor(props) {
    super(props);
    this.state = {
      markerPosition: getPosFromProps(props),
    }

    // 高德地图 Marker 实例
    this.markerInstance = undefined
    // 高德地图 Map 实例
    this.mapInstance = undefined

    this.amapEvents = {
      created: mapInstance => {
        this.mapInstance = mapInstance
        
        AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.CitySearch'], () => {
          // 实例化Autocomplete
          const autoOptions = { input: 'amapInput' }
          const autoComplete = new AMap.Autocomplete(autoOptions)
          const placeSearch = new AMap.PlaceSearch({ map: mapInstance })

          // 监听下拉框选中事件
          AMap.event.addListener(autoComplete, 'select', e => {
            // TODO 针对选中的poi实现自己的功能
            placeSearch.setCity(e.poi.adcode)
            placeSearch.search(e.poi.name)
          })

          const citySearch = new AMap.CitySearch()
          citySearch.getLocalCity((status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              // 查询成功，result即为当前所在城市信息
              console.log('当前所在城市：', result)
              if (result && result.city && result.bounds) {
                // 当前城市位置信息
                const citybounds = result.bounds;
                // 地图显示当前城市
                mapInstance.setBounds(citybounds);
                // 需要在设置坐标成功后，重新设置 缩放级别
                // mapInstance.setZoom(15)
              }
            }
          })

          // 搜索结果点击
          placeSearch.on('markerClick', debounce(e => {
            const { location: loc } = e.data
            const lngLat = `${loc.lng},${loc.lat}`
            this.props.onChange(lngLat, e)
          }, 300, { leading: true }))
        })

        // 实例点击事件
        mapInstance.on('click', debounce(e => {
          const lngLat = `${e.lnglat.getLng()},${e.lnglat.getLat()}`
          this.props.onChange(lngLat, e)
        }, 300, { leading: true }));
      },
    };
    
    this.markerEvents = {
      created: markerInstance => {
        this.markerInstance = markerInstance
        console.log('--->',markerInstance)
      }
    }
    // this.markerPosition = { longitude: 120, latitude: 30 };
  }

  static getDerivedStateFromProps(props, state) {
    if (props.value && !state.markerPosition) {
      return { markerPosition: getPosFromProps(props) }
    }

    return null
  }

  componentDidUpdate(prevProps) {
    if (this.props.value !== prevProps.value) {
      if (this.props.value) {
        this.setState({ markerPosition: getPosFromProps(this.props) }, () => {
          if (this.mapInstance) {
            // 需要在设置坐标成功后，重新设置 缩放级别
            // this.mapInstance.setZoom(15)
          }
        })
      }
    }
  }

  render() {
    return (
      <>
        <div style={{ width: '100%', height: '100%', minHeight: '400px', position: 'relative' }}>
          {/* zoom={15} 设置后，无效，不知道什么原因，必须手动设置 */}
          <Map plugins={['ToolBar']} events={this.amapEvents} amapkey={this.props.amapkey} center={this.state.markerPosition}>
            <Marker position={this.state.markerPosition} events={this.markerEvents} clickable />
          </Map>
          {
          <div className={styles.infoBox}>
            <span className={styles.inputText}>请输入关键字</span>
            <input id="amapInput" className={styles.input} type="text" />
          </div>
          }
        </div>
      </>
    )
  }
}

export default AMapSearch
