
const iconNoraml = '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png';
const iconActive = '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png';

export function newMarker(AMap, options = {}) {
  const { active = false, ...params } = options;
  const icon = new AMap.Icon({
    size: new AMap.Size(25, 34),
    image: active ? iconActive : iconNoraml,
    imageSize: new AMap.Size(25, 34),
  })
  const offset = new AMap.Pixel(-13, -30)

  return new AMap.Marker({ icon, offset, ...params });
}

export function autoPos(AMap, options = {}) {
  return new AMap.Geolocation({
    enableHighAccuracy: true,//是否使用高精度定位，默认:true
    timeout: 10000,          //超过10秒后停止定位，默认：5s
    buttonPosition:'RB',    //定位按钮的停靠位置
    buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
    zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
    ...options,
  });
}

const labelStyle = `
  padding: .5em .8em;
  border-radius: .25rem;
  background-color: white;
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.2);
`

export function autoPoi(map, AMap, inputRef, evt) {
  const markers = [];
  const input = inputRef.current

  const destroy = () => {
    if (markers.length) {
      markers.forEach((m) => map.remove(m))
      markers.splice(0, markers.length)
    }
  }

  const handleSearchResult = (status, result) => {
    // 先清空
    destroy();

    const { pois } = result.poiList;
    (pois || []).forEach((poi) => {
      const { location, name } = poi;
      const marker = newMarker(AMap, {
        map,
        position: location,
        label: {
          content: `<div style="${labelStyle}">${name}</div>`,
          direction: 'top',
        },
      })
      marker.on('click', evt.click)
      markers.push(marker)
    })
    // map.setZoom(18);
    map.setFitView();
  }
  
  const placeSearch = new AMap.PlaceSearch({ pageSize: 20 });
  const autoComplete = new AMap.Autocomplete({ input });

  // 选择自动填充
  autoComplete.on('select', e => {
    placeSearch.setCity(e.poi.adcode)
    placeSearch.search(e.poi.name, handleSearchResult)
  })

  autoComplete.on('error', (err) => console.error(err))

  return autoComplete;
}
