import { useEffect, useState } from "react";
import AMapLoader from "@amap/amap-jsapi-loader";

export default function MapFrom(props:any) {
  let [amap, setmaps] = useState<any>(null);
  useEffect(() => {
    loadMaps();
    return () => {
      amap?.destroy();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const loadMaps = async () => {
    const Amap = await AMapLoader.load({
      key: "d58999d072ed7e5897d3900a769cfda0", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ["AMap.Scale", "AMap.AutoComplete", "AMap.PlaceSearch"],
    });
    amap = new Amap.Map("mapFrom", {
      viewMode: "2D", // 是否为3D地图模式
      zoom: 11, // 初始化地图级别
      center: [103.55, 30.34], // 初始化地图中心点位置
    });

    Amap.plugin(["AMap.PlaceSearch", "AMap.AutoComplete"], function () {
      var auto = new Amap.AutoComplete({ input: "tipinput" });
      var placeSearch = new Amap.PlaceSearch({ map: amap }); //构造地点查询类
      auto.on("select", (e) => {
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name); //关键字查询查询
      }); //注册监听，当选中某条记录时会触发
    });
    var markers = []
    Amap.plugin(["AMap.MouseTool"], function () {
      var mouseTool = new Amap.MouseTool(amap);
      // 开启坐标选择功能
      mouseTool.on("draw", function (event) {
        var lnglat = event.obj.getBounds().getCenter(); // 获取图形的中心点坐标
        markers = mouseTool.overlays.marker
        props.onChange({lng:lnglat.lng,lat:lnglat.lat})
        var mk = []
        for (let index = 0; index < markers.length-1; index++) {
          mk.push(markers[index])
        }
        amap.remove(mk);
      });
      mouseTool.marker();
    });
   
    setmaps(Amap);
  };

  return (
    <div style={{ height: "400px", width: "400px" }}>
      <div style={{ position: "relative" }}>
        <div id="mapFrom" style={{ height: "400px", width: "400px" }}></div>
        <input
          style={{ position: "absolute", right: "5px", top: "5px" }}
          id="tipinput"
        />
      </div>
    </div>
  );
}
