<template>
  <el-dialog
    title="地图选点"
    :visible.sync="dialogVisible"
    width="1200px"
    :before-close="dialogVisible == false"
    :destroy-on-close="true"
  >
    <div>
      <el-input
        placeholder="请输入内容"
        v-model="input"
        class="input-with-select"
        id="input"
        style="width: 90%"
      >
      </el-input>
      <el-button type="primary" icon="el-icon-search" @click="autoInput"></el-button>
    </div>

    <!-- <el-select v-model="value" filterable placeholder="请选择" :filter-method="autoInput">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select> -->

    <div style="margin-top: 10px">已选择地址:{{ address }}</div>
    <div id="container" style="margin-top: 10px"></div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="SubmitMapPoint">确 定</el-button>
    </span>
  </el-dialog>
</template>

<style scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 600px;
}
</style>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
export default {
  data() {
    return {
      map: null,
      marker: null,
      geocoder: null,
      dialogVisible: false,
      input: "",
      markers: [],
      address: "",
      addressParams: {},
    };
  },
  mounted() {
    this.initAMap();
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    loadMap() {
      this.dialogVisible = true;
      this.initAMap();
    },
    closeMap() {
      this.address = "";
      this.input = "";
      this.dialogVisible = false;
      this.map?.destroy();
    },
    SubmitMapPoint() {
      this.$emit("address", this.addressParams);
    },
    // 获取搜索信息
    autoInput() {
      let that = this;
      var keywords = this.input;

      if (this.markers.length > 0) {
        this.map.remove(this.markers);
      }
      AMap.plugin(["AMap.PlaceSearch"], function () {
        //构造地点查询类
        var placeSearch = new AMap.PlaceSearch({
          pageSize: 5, // 单页显示结果条数
          pageIndex: 1, // 页码
          map: that.map, // 展现结果的地图实例
          // panel: "panel", // 结果列表将在此容器中进行展示。
          autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        placeSearch.search(keywords);
        placeSearch.on("markerClick", function (e) {
          e.data.address =
            e.data.pname +
            "" +
            e.data.cityname +
            "" +
            e.data.adname +
            "" +
            e.data.address +
            "" +
            e.data.name;

          console.log("s", e.data);
          e.data.cityCode = e.data.adcode.substring(0, 4) + "00";
          that.addressParams = e.data;
          console.log("z", that.addressParams);
          that.address = e.data.address;
        });
      });
    },

    getLocation() {
      const _this = this;
      AMap.plugin("AMap.CitySearch", function () {
        var citySearch = new AMap.CitySearch();
        citySearch.getLocalCity(function (status, result) {
          if (status === "complete" && result.info === "OK") {
            console.log(result.rectangle.split(";"));
            let xy = result.rectangle.split(";")[0].split(",");
            console.log("xxx", _this.map.getCenter());
            _this.map.setCenter(xy);
          }
        });
      });
    },
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "aae243a4d33170d5331abec91fe2cd0c",
      };
      let that = this;
      AMapLoader.load({
        key: "2e75f4c22217359628e22c2e170b4778", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.Geocoder",
          "AMap.Autocomplete",
          "AMap.PlaceSearch",
          "AMap.Scale",
          "AMap.OverView",
          "AMap.Geolocation",
          "AMap.ToolBar",
          "AMap.MapType",
          "AMap.PolyEditor",
          "AMap.CircleEditor",
        ], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
        .then((AMap) => {
          that.map = new AMap.Map("container", {
            // 设置地图容器id
            viewMode: "2D", // 是否为3D地图模式
            zoom: 11, // 初始化地图级别.
            resizeEnable: true,
          });
          that.geocoder = new AMap.Geocoder();
          that.map.on("click", that.handleMapClick);

          setTimeout(() => {
            that.getLocation();
          }, 500);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    handleMapClick(e) {
      console.log(e);
      if (this.marker) {
        if (this.marker) {
          this.marker.setMap(null);
          this.marker = null;
        }
      }
      if (!this.marker) {
        this.marker = new AMap.Marker({
          icon:
            "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          position: [e.lnglat.lng, e.lnglat.lat],
          imageSize: new AMap.Size(12, 12),
          offset: new AMap.Pixel(-13, -30),
        });
        this.marker.setMap(this.map);
        this.regeoCode(e.lnglat);
      }
    },
    markerBlur(e) {
      console.log(e);
    },
    regeoCode(lnglat) {
      console.log(lnglat);
      let that = this;
      this.map.add(this.marker);
      this.marker.setPosition(lnglat);
      // 创建高德地图的 Geocoder 实例
      this.geocoder.getAddress(lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          var address = result.regeocode.formattedAddress;
          result.regeocode.addressComponent.location = lnglat;
          result.regeocode.addressComponent.address = address;

          let addrs = result.regeocode.addressComponent;
          result.regeocode.addressComponent.pname = addrs.province;
          result.regeocode.addressComponent.cityname = addrs.city;
          result.regeocode.addressComponent.adname = addrs.district;

          result.regeocode.addressComponent.pcode =
            result.regeocode.addressComponent.adcode.substring(0, 3) + "000";

          result.regeocode.addressComponent.cityCode =
            result.regeocode.addressComponent.adcode.substring(0, 4) + "00";
          console.log("zxczxczx", result);
          that.address = address;
          console.log("cccc", that.address);
          that.$forceUpdate();
          that.addressParams = result.regeocode.addressComponent;
        } else {
          that.$message.error("根据经纬度查询地址失败");
        }
      });
    },
  },
};
</script>
<style>
html,
body,
#container {
  height: 100%;
  width: 100%;
}

.amap-icon img,
.amap-marker-content img {
  width: 25px;
  height: 34px;
}

.marker {
  position: absolute;
  top: -20px;
  right: -118px;
  color: #fff;
  padding: 4px 10px;
  box-shadow: 1px 1px 1px rgba(10, 10, 10, 0.2);
  white-space: nowrap;
  font-size: 12px;
  font-family: "";
  background-color: #25a5f7;
  border-radius: 3px;
}

.input-card {
  width: 18rem;
  z-index: 170;
}

.input-card .btn {
  margin-right: 0.8rem;
}

.input-card .btn:last-child {
  margin-right: 0;
}
</style>
