<template>
  <div>
    <a-button
      :disabled="isUpdate === 3"
      @click="handleOpenModal"
      type="primary"
      :icon="h(SearchOutlined)"
      >点击获取经纬度</a-button
    >
  </div>

  <BasicModal
    v-bind="$attrs"
    :title="'获取经纬度'"
    @register="register"
    :width="1200"
    @ok="handleSubmit"
  >
    <div>
      <div style="margin-bottom: 8px">
        <a-input-search
          v-model:value="mapData.keyword"
          placeholder="请输入地点搜索"
          enter-button="搜索"
          size="large"
          @search="search"
        />
        <!-- <a-button type="primary" @click="zoomIn">放大</a-button>
        <a-button type="primary" @click="zoomOut">缩小</a-button> -->
      </div>

      <div id="container" class="map" style="height: 400px; border-radius: 5px" />
      <div>经度：{{ lng }}</div>
      <div>经度：{{ lat }}</div>
    </div>
  </BasicModal>
</template>
<script setup>
import { SearchOutlined } from "@ant-design/icons-vue";
import { BasicModal, useModal } from "@/components/Modal";
import { onMounted, reactive, ref, h, defineEmits, defineModel } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

const map = ref(null);
const emit = defineEmits(["getLatLng"]);
const isUpdate = defineModel("isUpdate");
const mapData = reactive({
  map: {},
  keyword: "",
  selectedLocation: {},
  selectedAddress: "",
  marker: null, // 用于存储选中位置的标记
});
const lng = ref(0);
const lat = ref(0);

const [register, { openModal, closeModal }] = useModal();
const handleSubmit = () => {
  emit("getLatLng", { lat: lat.value, lng: lng.value });
  closeModal();
};
const handleOpenModal = () => {
  openModal(true);
  setTimeout(() => {
    loadMap();
  }, 200);
};

const loadMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: "f5abb0a2cae2075683e2e6d6f62dde18", // 密钥
  };

  AMapLoader.load({
    key: "fbe22df4797c15ebb02de6ee7de73892", // key值
    version: "2.0",
    plugins: ["AMap.PlaceSearch"],
  })
    .then((AMap) => {
      const mapInstance = new AMap.Map("container", {
        viewMode: "3D",
        zoom: 11,
        center: [114.266784, 30.513206], // 初始化地图中心点位置

        scrollWheel: true, // 启用滚动缩放
      });

      mapInstance.on("click", (e) => {
        lng.value = e.lnglat.getLng();
        lat.value = e.lnglat.getLat();

        // 移除之前的标记
        if (mapData.marker) {
          mapData.marker.setMap(null);
        }

        // 创建新的标记
        const marker = new AMap.Marker({
          position: [lng.value, lat.value],
          icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", // 选中位置的图标
          offset: new AMap.Pixel(-15, -30), // 调整图标的偏移位置
        });

        // 将标记添加到地图
        marker.setMap(mapInstance);

        // 存储选中位置的标记
        mapData.marker = marker;

        // 将地图中心设置为选中位置
        mapData.map.setCenter([lng.value, lat.value]);
      });

      mapData.map = mapInstance;
    })
    .catch((e) => {
      console.log(e);
    });
};
const search = () => {
  console.log(mapData.keyword);
  if (mapData.keyword) {
    AMapLoader.load({
      key: "fbe22df4797c15ebb02de6ee7de73892",
      version: "2.0",
      plugins: ["AMap.PlaceSearch"],
    })
      .then((AMap) => {
        const placeSearch = new AMap.PlaceSearch({
          city: "全国", // 请根据实际情况设置城市
          map: mapData.map,
        });
        placeSearch.search(mapData.keyword, (status, result) => {
          console.log(result); // 输出完整的搜索结果

          if (status === "complete") {
            const pois = result.poiList.pois;
            if (pois.length > 0) {
              const { location } = pois[0];

              // 移除之前的标记
              if (mapData.marker) {
                mapData.marker.setMap(null);
              }

              // 创建新的标记
              const marker = new AMap.Marker({
                position: location,
                icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                offset: new AMap.Pixel(-15, -30),
              });

              // 将标记添加到地图
              marker.setMap(mapData.map);

              // 存储选中位置的标记
              mapData.marker = marker;

              // 将地图中心设置为选中位置
              mapData.map.setCenter(location);
            }
          } else {
            console.log("搜索失败或无结果");
          }
        });
      })
      .catch((e) => {
        console.log(e);
      });
  }
};

const zoomIn = () => {
  mapData.map.zoomIn();
};

const zoomOut = () => {
  mapData.map.zoomOut();
};
</script>
<style lang="less">
.search-btn {
  cursor: pointer;
}
.map {
  width: 100%;
}
</style>
