<template>
  <div id="container" ref="map"></div>
</template>

<script lang="ts" setup name="mapContainer">
import AMapLoader from "@amap/amap-jsapi-loader";
import { shallowRef } from "@vue/reactivity";

const map = shallowRef(null);
let AMap: any = null;
let markerList: Array<any> = [];
let m_index: Number = 0;
let geocoder: any = null;
let marker: any = null;

const emits = defineEmits(["changeMaps"]);

const resetMap = () => {
  try {
    markerList = [];
    map.value?.clearMap();
    m_index = 0;
    emits("changeMaps", markerList);
  } catch (error) {
    console.log(error);
  }
};

const initMap = async () => {
  const loader = AMapLoader.load({
    key: "4f8f55618010007147aab96fc72bb408",
    version: "2.0",
  });

  AMap = await loader;

  map.value = new AMap.Map("container", {
    zoom: 13,
    viewMode: "2D",
    center: [105.4423, 28.8717],
  });

  AMap.plugin("AMap.Geocoder", function () {
    geocoder = new AMap.Geocoder({
      radius: 10, // 逆地理编码范围，默认值：1000，单位：米
      extensions: "all", // 返回地址描述结果时是否包含引擎内置的POI，默认值：base，可选值：base、all
    }); // 经纬度数组
  });

  AMap.plugin("AMap.Geolocation", function () {
    let geolocation = new AMap.Geolocation({
      enableHighAccuracy: true, // 是否使用高精度定位，默认:true
      timeout: 10000, // 超过1秒后停止定位，默认：无穷大
      buttonPosition: "RB", // 定位按钮的停靠位置
      zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点
    });

    map.value.addControl(geolocation);

    // geolocation.getCurrentPosition(function (status, result) {
    //   console.log(status, result);
    // });
  });

  map.value.setFitView();

  map.value.on("click", (e: any) => {
    // if (m_index >= 1) return;
    if (m_index >= 1) {
      map.value?.remove(marker);
      m_index = 0;
    }
    // 调用函数并传入经纬度
    getDistrictName(e.lnglat.lng, e.lnglat.lat, e);

    // 创建标记并添加到地图
    marker = new AMap.Marker({
      position: e.lnglat,
      offset: new AMap.Pixel(0, 0),
      title: "位置",
    });
    map.value.add(marker);
    m_index++;

    // 添加标记点击事件监听器
    marker.on("click", (event: any) => {
      // markerList = markerList.filter((item: any) => {
      //   item[0] == marker._position.pos[0] &&
      //     item[0] == marker._position.pos[0];
      // });
      markerList = [];
      emits("changeMaps", markerList);
      map.value.remove(marker);
      m_index--;
      marker = null;
    });
  });
};

const searchMap = (address: any) => {
  // ElMessage.error("搜索功能开发中");
  AMap.plugin("AMap.PlaceSearch", async function () {
    try {
      const placeSearch = new AMap.PlaceSearch({
        pageSize: 5, // 单页显示结果条数
        pageIndex: 1, // 页码
        city: "510500", // 兴趣点城市
        citylimit: true, //是否强制限制在设置的城市内搜索
        map: map.value, // 展现结果的地图实例
        panel: false, // 结果列表将在此容器中进行展示。
        autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
      });
      AMap.Event.addListener(placeSearch, "markerClick", (e: any) => {
        marker ? map.value?.remove(marker) : null;
        getDistrictName(e.event.lnglat.lng, e.event.lnglat.lat, e.event);
      });
      placeSearch.search(address);
    } catch (error) {
      ElMessage.error("没找到");
    }
  });
};

// 获取地区名称
const getDistrictName = (lng: any, lat: any, e: any) => {
  geocoder.getAddress([lng, lat], function (status: any, result: any) {
    if (status === "complete" && result.info === "OK") {
      markerList = [];
      markerList.push({
        lnglat: e.lnglat,
        address: result.regeocode.formattedAddress,
      });
      emits("changeMaps", markerList);
    } else {
      // 解析失败
      ElMessage.error("逆地理编码失败");
    }
  });
};

defineExpose({
  resetMap,
  searchMap,
});

onMounted(() => {
  initMap();
});
</script>


<style lang="scss" scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 400px;
  height: 400px;
}
</style>