<template>
  <div class="location-picker" v-if="visabled">
    <!-- 地图容器 -->
    <div id="map-container"></div>

    <div class="confirmLocation">
      <!-- 搜索框 -->
      <input
        v-model="searchText"
        @change="handleSearch"
        ref="searchInput"
        placeholder="搜索地点..."
      />

      <!-- 搜索结果列表 -->
      <ul v-if="searchResults.length" class="search-results">
        <li
          v-for="(result, index) in searchResults"
          :key="index"
          @click="selectSearchResult(result)"
        >
          {{ result.name }} - {{ result.address }}
        </li>
      </ul>

      <!-- 定位结果展示 -->
      <div v-if="selectedLocation" class="result">
        <p>已选择：{{ selectedLocation.address }}</p>
        <p>经纬度：{{ selectedLocation.lng }}, {{ selectedLocation.lat }}</p>
      </div>

      <!-- 操作按钮 -->
      <van-button
        size="small"
        @click="confirmLocation"
        text="确认选择"
      ></van-button>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  data() {
    return {
      map: null,
      visabled: false,
      marker: null,
      AMapRef: null,
      searchText: "",
      selectedLocation: null,
      searchResults: [], // 搜索结果列表
    };
  },
  methods: {
    async initMap() {
      try {
        this.visabled = true;
        this.selectedLocation = null;
        this.searchText = "";
        // 加载高德地图JS API
        AMapLoader.load({
          key: "487c977753dd211e731f1d13d9322f09",
          version: "2.0",
          securityJsCode: "2403bc79e3493aa796277092566cda59",
          plugins: ["AMap.Geocoder", "AMap.PlaceSearch", "AMap.AutoComplete"],
        }).then((AMap) => {
          this.AMapRef = AMap;
          // 初始化地图
          this.map = new AMap.Map("map-container", {
            zoom: 15,
          });

          // 添加点击选点事件
          this.map.on("click", (e) => {
            this.updateMarkerPosition(e.lnglat);
            this.getAddress(e.lnglat.lng, e.lnglat.lat);
          });

          // 初始化标记点
          this.marker = new AMap.Marker({
            position: this.map.getCenter(),
            map: this.map,
          });
        });
      } catch (error) {
        console.error("地图初始化失败:", error);
      }
    },

    // 更新标记位置
    updateMarkerPosition(lnglat) {
      this.marker.setPosition(lnglat);
      this.map.setCenter(lnglat);
    },

    getAddress(long, lat) {
      fetch(
        `https://restapi.amap.com/v3/geocode/regeo?location=${long},${lat}&key=74d5aa7c4270effe9a18d9cfa6149abf`
      )
        .then((res) => res.json())
        .then((data) => {
          let address = data.regeocode.addressComponent;
          this.selectedLocation = {
            address: data.regeocode.formatted_address,
            lng: long,
            lat: lat,
          };
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 搜索地点
    handleSearch() {
      fetch(
        `https://restapi.amap.com/v3/place/text?keywords=${this.searchText}&key=74d5aa7c4270effe9a18d9cfa6149abf`
      )
        .then((res) => res.json())
        .then((data) => {
          this.searchResults = data.pois.map((poi) => ({
            name: poi.name,
            address: poi.address,
            location: poi.location,
          }));
          this.$refs.searchInput.blur(); // 收起键盘
        })
        .catch((error) => {
          console.log(error);
        });
    },

    // 选择搜索结果
    selectSearchResult(result) {
      this.updateMarkerPosition([
        result.location.split(",")[0],
        result.location.split(",")[1],
      ]);

      this.selectedLocation = {
        lng: result.location.split(",")[0],
        lat: result.location.split(",")[1],
        address: result.name + result.address,
      };
      this.searchResults = []; // 清空搜索结果
    },

    // 确认选择
    confirmLocation() {
      if (this.selectedLocation) {
        this.$emit("selected", this.selectedLocation);
        this.visabled = false;
      } else {
        alert("请先在地图上选择位置");
      }
    },
  },
};
</script>

<style scoped>
#map-container {
  width: 100%;
  height: 400px;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}

.confirmLocation {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 240px;
  /* width: calc(100% - 40px); */
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.location-picker {
  position: fixed;
  z-index: 999;
  width: 100%;
  top: 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
  background: rgba(255, 255, 255, 0.95);
  padding: 10px;
}

input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
  width: 100%;
  box-sizing: border-box;
}

.search-results {
  list-style: none;
  padding: 0;
  margin: 10px 0 0;
  border: 1px solid #ccc;
  border-radius: 4px;
  max-height: 200px;
  overflow-y: auto;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-results li {
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.search-results li:last-child {
  border-bottom: none;
}

.search-results li:hover {
  background: #f7f7f7;
}

.result {
  font-size: 14px;
  color: #333;
  margin-top: 10px;
}

.result p {
  margin: 5px 0;
}

.van-button {
  width: 100%;
  background-color: #007bff;
  color: #fff;
  border-radius: 4px;
  font-size: 16px;
  padding: 10px;
  text-align: center;
  cursor: pointer;
}

.van-button:hover {
  background-color: #0056b3;
}
</style>
