<template>
  <div class="map-container">
    <div class="search_box">
      <!-- <div class="label">搜索位置</div> -->
      <el-input placeholder="请输入地点名称" v-model="input">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
    </div>
    <div ref="gaode_Map" id="gaode_Map" class="map"></div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  // 设置安全密钥
  securityJsCode: "e779fe2f89c105226f4cc4a78d0bcafe",
};

export default {
  components: {},
  props: [],
  data() {
    return {
      loading: false,
      isDetail: false,
      dataForm: {
        kqName: undefined,
        kqLocation: undefined,
        kqLongitude: undefined,
        kqLatitude: undefined,
        kqWorkUnit: undefined,
        cronkqAccredit: [],
        kqValidCardRange: undefined,
      },
      rules: {},
      input: "",
      map: null,
      auto: null,
      placeSearch: null,
      lnglat: [],
      markers: [],
      position: {},
    };
  },
  computed: {},
  watch: {},
  created() { },
  mounted() {
    // 使用 nextTick 确保 DOM 更新完成后再初始化地图
    this.$nextTick(() => {
      this.initMap();
    });
  },
  methods: {
    // 地图初始化
    initMap() {
      // 苏州园区的经纬度
      let centerLen = [120.585298, 31.322965];
      AMapLoader.load({
        key: "b58f9bc6e9863d1688a2da18446ec14d", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder"],
      })
        .then((AMap) => {
          this.map = new AMap.Map("gaode_Map", {
            // 设置地图容器id
            viewMode: "3D", // 是否为3D地图模式
            zoom: 16, // 初始化地图级别
            center: centerLen, // 中心点坐标
            resizeEnable: true,
          });
          this.setMarker(centerLen);
          // 关键字查询
          this.searchMap();
          // 监听鼠标点击事件
          this.map.on("click", this.clickMapHandler);
        })
        .catch((e) => {
          console.error("地图加载失败:", e);
        });
    },
    // 关键字查询
    searchMap() {
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: "tipinput", // 使用联想输入的input的id
      });
      // 构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
      });
      // 当选中某条搜索记录时触发
      this.auto.on("select", this.selectSite);
    },
    // 选中查询出的记录
    selectSite(e) {
      if (e.poi.location) {
        this.placeSearch.setCity(e.poi.adcode);
        this.placeSearch.search(e.poi.name); // 关键字查询
      } else {
        this.$message.error("查询地址失败，请重新输入地址");
      }
    },
    // 点击地图事件获取经纬度，并添加标记
    clickMapHandler(e) {
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      this.setMarker(this.lnglat);
      // 点击地图上的位置，根据经纬度转换成详细地址
      let geocoder = new AMap.Geocoder({});
      let that = this;
      geocoder.getAddress(this.lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          // 不需要赋值给 dataForm
        } else {
          that.$message.error("查询地址失败，请重新输入地址");
        }
      });
    },
    // 添加标记
    setMarker(lnglat) {
      this.removeMarker();
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker);
    },
    // 删除之前后的标记点
    removeMarker() {
      if (this.markers) {
        this.markers.forEach(marker => marker.setMap(null));
        this.markers = [];
      }
    },
  },
};
</script>

<style lang="scss">
.map-container {
  width: 100%;
  height: 30rem;
  position: relative;
}

.search_box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 50px;
  padding: 0 20px 0 0;
  width: 25rem;

  .label {
    color: #000;
    width: 100px;
  }
}

.map {
  overflow: hidden;
  width: 72rem;
  height: 26.13rem;
  margin: 0;
  position: relative;
  z-index: 1000;
}

.amap-sug-result {
  z-index: 2999 !important;
}
</style>