import React, { useEffect, useRef, useState } from 'react';
import { sdk } from '@/utils/map'
import { newMarker, autoPos, autoPoi } from './utils'
import './style.less'

const plugins = ['AMap.Scale', 'AMap.ToolBar', 'AMap.Geolocation', 'AMap.Autocomplete', 'AMap.PlaceSearch']

export default (props) => {
  const map = useRef()
  const container = useRef()
  const inputRef = useRef()
  const posMarker = useRef()
  const [currentPos, setCurrentPos] = useState([]);

  const handleClick = (e) => {
    const { lnglat } = e
    const pos = [lnglat.getLng(), lnglat.getLat()]
    posMarker.current.setMap(map.current);
    setCurrentPos(pos)
    props.onChange(pos.join(','))
  }

  useEffect(() => {
    // 只加载一次 amap 相关 js
    sdk.loadMapModule({ plugins }).then((AMap) => {
      const instance = new AMap.Map(container.current, { zoom: 12 })
      instance.addControl(new AMap.Scale())
      instance.addControl(new AMap.ToolBar())

      // 尝试自动定位到当前位置
      if (!props.value) {
        instance.addControl(autoPos(AMap))
      }

      // 当前选中点 - 初始的时候没有定位
      posMarker.current = newMarker(AMap, {
        active: true,
        position: props.value ? props.value.split(',') : undefined,
      })

      if (props.value) {
        posMarker.current.setMap(instance);
      }

      // POI 搜索
      autoPoi(instance, AMap, inputRef, { click: handleClick })

      instance.on('click', handleClick);
      map.current = instance
    })
  }, [])

  useEffect(() => {
    if (props.value) {
      setCurrentPos(props.value.split(','))
    }
  }, [props.value])

  useEffect(() => {
    if (currentPos.length) {
      if (posMarker.current) {
        posMarker.current.setPosition(currentPos)
      }
      if (map.current) {
        map.current.setCenter(currentPos);
      }
      if (currentPos.length && map.current) {
        posMarker.current.setMap(map.current)
      }
    }
  }, [currentPos])

  const boxStyle = {
    width: '100%',
    height: '400px',
    position: 'relative',
    ...(props.style || {}),
  }

  const mapStyle = {
    height: '100%',
    width: '100%',
    margin: 0,
  }

  const inputStyle = {
    width: '200px',
    padding: '5px',
    position: 'absolute',
    zIndex: 9999,
    right: '30px',
    lineHeight: '1em',
  }

  const inputSty1 = {
    ...inputStyle,
    top: '50px',
  }

  const inputSty2 = {
    ...inputStyle,
    top: '10px',
    background: 'rgba(255, 255, 255, .9)',
    border: '1px solid #bbb',
  }

  return (
    <div className={props.className} style={boxStyle}>
      <div ref={container} style={mapStyle} id="poi-map-wrapper"></div>
      <input placeholder="请输入搜索关键字" ref={inputRef} style={inputSty1} />
      <input value={`坐标: ${currentPos.join(',')}`} style={inputSty2} disabled />
    </div>
  )
}
