<template>
  <div id="map-container">
    <div class="search-bar">
      <el-input
        v-model="keyword"
        placeholder="请输入关键词"
        size="small"
        @keyup.enter="searchPoint"
      >
        <template #suffix>
          <el-icon @click="searchPoint">
            <Search />
          </el-icon>
        </template>
      </el-input>
    </div>
  </div>
</template>

<script setup>
import { loadMap } from "@/utils/amap";
import { onMounted, ref, shallowRef, toRefs } from "vue";
import markBsPng from "@/assets/images/mark_bs.png";
import { Search } from "@element-plus/icons-vue";

const props = defineProps({
  lat: Number,
  lng: Number,
  lnglat: Array,
});
const { lnglat } = toRefs(props);
const emit = defineEmits(["selected"]);
const AMap = shallowRef();
const map = shallowRef();
const placeSearch = shallowRef(null);
const searchResultMarkers = shallowRef([]); // 搜索结果表笔列表
const resultInfoWindow = shallowRef(null);

const handleMapClick = (event) => {
  map.value.clearMap();
  const { lnglat } = event;
  const marker = new AMap.value.Marker({
    position: lnglat,
  });
  map.value.add(marker);
  emit("selected", lnglat);
};

// 鼠标悬停搜索结果标记
const handleResultHover = (ev) => {
  console.log(ev);
  resultInfoWindow.value.setContent(`
    <div>
    ${ev.target.getExtData().name}</div>
    `);
  resultInfoWindow.value.open(map.value, [ev.lnglat.lng, ev.lnglat.lat]);
};

// 搜索结果点击
const handleResultClick = async (ev) => {
  map.value.clearMap();
  searchResultMarkers.value = [];
  const lnglat = ev.target.getExtData()?.location;
  // if (!lnglat) return ElMessage.error("获取经纬度失败");
  // addFencePath(lnglat);
  const marker = new AMap.value.Marker({
    position: lnglat,
  });
  map.value.add(marker);
  map.value.setFitView([marker]);
  emit("selected", lnglat);
};

// 根据名称搜索地图标点
const keyword = ref("");
const searchPoint = (val /** 搜索建议选项 */, type) => {
  map.value.clearMap();
  placeSearch.value.search(keyword.value, (status, result) => {
    // TODO: 添加搜索结果标记
    if (status === "complete") {
      console.log(status, result);
      searchResultMarkers.value = result.poiList.pois.map((el, index) => {
        const marker = new AMap.value.Marker({
          map: map.value,
          position: el.location,
          anchor: "bottom-center",
          extData: el,
          content: `
              <div
                style="
                  background-image: url(${markBsPng});
                  width: 19px;
                  height: 31px;
                  background-size: cover;
                  color: #fff;
                  text-align: center;
                  font-size: 12px;
                  /*padding-top: 3px;*/
                "
              >
                ${index + 1}
              </div>
              `,
        });
        marker.on("mouseover", handleResultHover);
        marker.on("click", handleResultClick);
        marker.on("mouseout", (ev) => {
          resultInfoWindow.value.close();
        });
        return marker;
      });
      map.value.setFitView(searchResultMarkers.value);
    } else {
      console.log(status, result);
    }
  });
};

onMounted(async () => {
  AMap.value = await loadMap(["AMap.PlaceSearch"]);
  map.value = new AMap.value.Map("map-container", { zoom: 11 });
  map.value.on("click", handleMapClick);
  // 地点搜索插件
  placeSearch.value = new AMap.value.PlaceSearch({
    // map: map.value
    // city: "0551"
  });
  resultInfoWindow.value = new AMap.value.InfoWindow({
    anchor: "bottom-center",
    offset: new AMap.value.Pixel(0, -31),
  });
  if (lnglat.value.length === 2) {
    const marker = new AMap.value.Marker({
      position: lnglat.value,
    });
    map.value.add(marker);
    map.value.setFitView([marker]);
  }
});
</script>

<style lang="scss" scoped>
#map-container {
  width: 100%;
  height: 300px;
  //margin-left: 140px;
  //margin-bottom: 18px;
  position: relative;

  .search-bar {
    //display: none;
    position: absolute;
    left: 0;
    top: 10px;
    padding: 0 10px;
    z-index: 2023;
  }
}
</style>
