<template>
  <div id="map"></div>
  <div class="address">
    <span class="lng">请输入地址:</span>
    <el-input id="suggestId" v-model="address" placeholder="请输入地点" />
  </div>
  <div class="address">
    <span class="lng">地址：{{ address }}</span>
    <span class="lng">lng:{{ lng }}</span>
    <span class="lat">lat:{{ lat }}</span>
  </div>
  <div class="options">
    <el-button
      color="rgba(9, 101, 98, 1)"
      class="queding"
      type="primary"
      @click="mapAddress(true)"
    >
      确定
    </el-button>
    <el-button @click="mapAddress(false)">取消</el-button>
  </div>
</template>

<script setup>
import loadBMap from "@/utils/loadMap.js";
import {
  ref,
  reactive,
  onBeforeMount,
  onMounted,
  watch,
  watchEffect,
  nextTick,
} from "vue";
const mapInit = loadBMap("jmkawuXGwcepLcsAqcAi3FeDMfaLhnOE");// 公司
// const mapInit = loadBMap("jLS6RW3GdIGVIr555yfGGCaFK7otIGDl");

const props = defineProps({
  fatherMessage: {},
});

const lng = ref("--");
const lat = ref("--");
const address = ref("");
const map = ref();

const emit = defineEmits(["mapClick"]);

// 确定按钮
const mapAddress = (flag) => {
  let data = {
    address: address.value,
    lng: lng.value,
    lat: lat.value,
    flag: flag,
  };
  emit("mapClick", data);
};

const getList = () => {
  console.log("调用了", address.value);
  mapInit.then((BMap) => {
    //创建地图实例,位于BMap命名空间下的Map类表示地图，通过new操作符可以创建一个地图实例。其参数可以是元素id也可以是元素对象。
    map.value = new BMap.Map("map");
    console.log(map.value);
    
    var points;
    // 创建点坐标
    if (props.fatherMessage.lat && props.fatherMessage.lng) {
      points = new BMap.Point(props.fatherMessage.lat, props.fatherMessage.lng);
      lng.value = props.fatherMessage.lng;
      lat.value = props.fatherMessage.lat;
      address.value = props.fatherMessage.position;
    } else {
      points = "江西";
    }
    map.value.centerAndZoom(points, 20); // 初始化地图,设置城市和地图级别
    map.value.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
    map.value.addOverlay(new BMap.Marker(points)); // 添加标注

    const ac = new BMap.Autocomplete({
      input: "suggestId",
      location:map.value,
    });
    ac.setInputValue(address.value)
    //建立一个自动完成的对象
    ac.addEventListener("onconfirm", function (e) {
      //鼠标点击下拉列表后的事件
      console.log(e);
      const tempValue = e.item.value;
      const searchValue =
        tempValue.province +
        tempValue.city +
        tempValue.district +
        tempValue.street +
        tempValue.business;
      console.log(searchValue, "输入框选中的值");

      setPlace(BMap, map.value, searchValue);
    });
    // 点击地图(获取当前点击点的经纬度)
    map.value.addEventListener("click", function handleClick(e) {
      map.value.clearOverlays(); //清除地图上所有覆盖物
      console.log(e);
      address.value = "";
      console.log("点击的经纬度：" + e.Af.lng + ", " + e.Af.lat);
      lat.value = e.Af.lat.toFixed(8);
      lng.value = e.Af.lng.toFixed(8);
      map.value.addOverlay(
        new BMap.Marker({
          lng: e.Af.lng.toFixed(8),
          lat: e.Af.lat.toFixed(8),
        })
      );
      // 地址逆解析（无法获取精确地址）
      var geoc = new BMap.Geocoder();
      var pt = e.Af;
      var marker = new BMap.Marker(new BMap.Point(pt.lng, pt.lat));
      map.value.addOverlay(marker);
      geoc.getLocation(pt, function (rs) {
        var addComp = rs.addressComponents;
        console.log(
          addComp.province +
            ", " +
            addComp.city +
            ", " +
            addComp.district +
            ", " +
            addComp.street +
            ", " +
            addComp.streetNumber
        );
        address.value =
          addComp.province +
          addComp.city +
          addComp.district +
          addComp.street +
          addComp.streetNumber;
      });
    });
    // map.value.removeEventListener("click", handleClick); // 移除当前点击点的经纬度事件监听
  });
};

// 搜索下拉框数据展示
const dataList = () => {
  console.log("下拉框数据展示");
  mapInit.then((BMap) => {
    // const ac = new BMap.Autocomplete({
    //   input: "suggestId",
    //   location: map.value,
    // });
    //建立一个自动完成的对象
    // ac.addEventListener("onconfirm", function (e) {
    //   //鼠标点击下拉列表后的事件
    //   console.log(e);

    //   const tempValue = e.item.value;
    //   const searchValue =
    //     tempValue.province +
    //     tempValue.city +
    //     tempValue.district +
    //     tempValue.street +
    //     tempValue.business;
    //   console.log(searchValue, "输入框选中的值");

    //   setPlace(BMap, map.value, searchValue);
    // });
  });
};
const movePoint = (BMap, map, latlng) => {
  console.log("移动标记点");

  map.clearOverlays(); //清除地图上所有覆盖物
  //使用BMap命名空间下的Point类来创建一个坐标点
  const point = new BMap.Point(latlng.lng, latlng.lat);
  const marker = new BMap.Marker(point, {
    enableDragging: true,
  });
  map.addOverlay(marker);
  latlngToAddress(BMap, latlng);

  // 覆盖物拖拽开始事件
  marker.addEventListener("dragstart", function (e) {
    // 清除一些覆盖物
    console.log("[开始]", e);
  });
  // 覆盖物拖拽事件
  marker.addEventListener("dragend", function () {
    const nowPoint = marker.getPosition(); // 拖拽完成之后坐标的位置(经纬度)
    latlngToAddress(BMap, nowPoint);
  });
};
/**
 * 根据输入框的值在地图上添加标记点
 * @param
 *   BMap：地图对象
 *   searchValue：输入框下拉数据选中的值
 * **/
const setPlace = (BMap, map, searchValue) => {
  console.log("根据输入框的值在地图上添加标记点");

  map.clearOverlays(); //清除地图上所有覆盖物
  const local = new BMap.LocalSearch(map, {
    //智能搜索
    onSearchComplete: (res) => {
      console.log(res);

      const pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
      console.log(pp);

      map.centerAndZoom(pp, 21);
      map.addOverlay(new BMap.Marker(pp)); //添加标注
      movePoint(BMap, map, res.Wr[0].point);
    },
  });
  local.search(searchValue);
};
/**
 * 移动标记点
 * @param
 *   BMap：地图对象
 *   latlng：经纬度
 * **/

/**
 * 地址解析
 * @param
 *   BMap：地图对象
 *   latlng：经纬度
 * **/
const latlngToAddress = (BMap, latlng) => {
  console.log("地址解析");
  const geoc = new BMap.Geocoder();
  geoc.getLocation(latlng, function (rs) {
    console.log(rs.surroundingPois[0]);
    address.value = rs.surroundingPois[0].address + rs.surroundingPois[0].title;
    lat.value = rs.surroundingPois[0].point.lat.toFixed(8);
    lng.value = rs.surroundingPois[0].point.lng.toFixed(8);
  });
};
onBeforeMount(async () => {
  address.value = props.fatherMessage.position;
  lat.value = props.fatherMessage.lat;
  lng.value = props.fatherMessage.lng;
  getList();
  console.log(props.fatherMessage);
});
</script>

<style lang="scss" scoped>
#map {
  border: 1px solid red;
  box-sizing: border-box;
  width: 100%;
  height: 600px;
}
#suggestId {
  // border: 1px solid red;
  width: 120px !important;
  height: 30px;
}
.el-input {
  width: 350px;
}
.address {
  margin: 10px 20px;
}
.lng {
  margin-right: 20px;
}
.options {
  width: 98%;

  .queding {
    margin-left: 20px;
    color: #fff;
  }
  display: flex;
  flex-direction: row-reverse;
}
</style>
