<template>
  <el-dialog width="800px" title="地图编辑" :visible.sync="visible" append-to-body @close="closeDialog">
    <div id="dialogMap" class="dialog-map" style="height: 400px; width: 100%;" />
    <el-input id="search" v-model="searchBody" class="search-body" placeholder="请输入..." />

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="handleMapSave">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import AMap from 'AMap';
export default {
  data() {
    return {
      dialogMap: null,
      visible: false,
      placeSearch: null,
      currentPoint: undefined,
      marker: null,
      searchBody: undefined
    }
  },
  beforeDestroy() {
    console.log("mapdialog----beforeDestroy")
    this.marker = null;
    this.placeSearch = null;

    this.dialogMap && this.dialogMap.destroy();
    this.dialogMap = null;
  },
  mounted() {
    console.log("mounted")
    // this.initData()
  },
  created() {
    console.log("created")
  },
  methods: {
    initData(point = undefined) {
      console.log(point)
      this.visible = true
      this.$nextTick(() => {
        this.resetData();
        if (point) {
          this.currentPoint = point;
        }
        this.initMap()
      });
    },
    resetData() {
      this.currentPoint = undefined;
      this.dialogMap && this.marker && this.dialogMap.remove(this.marker);
      this.marker = null;
      this.placeSearch = null;
      this.searchBody = null
    },
    initMap() {
      console.log("初始化地图")
      if (!this.dialogMap) {
        this.dialogMap = new AMap.Map('dialogMap', {
          zoom: 12,
          resizeEnable: true,
          center: [117.283042, 31.86119]
        });
        this.dialogMap.on('click', ev => {
          this.currentPoint.lat = ev.lnglat.lat;
          this.currentPoint.lng = ev.lnglat.lng;
          this.regeoCode();
          this.marker && this.dialogMap.remove(this.marker);
          this.marker = new AMap.Marker({
            position: [this.currentPoint.lng, this.currentPoint.lat],
            icon: require(`@/assets/images/place/flag_red.png`)
          });
          this.dialogMap.add(this.marker);
        });
        this.dialogMap.addControl(new AMap.Scale());
        const auto = new AMap.Autocomplete({
          input: 'search', // 前端搜索框
        })
        this.placeSearch = new AMap.PlaceSearch({
          map: this.dialogMap,
          pageSize: 10, // 单页显示结果条数
          pageIndex: 1, // 页码
          autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        })
        AMap.event.addListener(auto, 'select', this.select)
        this.geocoder = new AMap.Geocoder();
      }

      this.initMapCenter();

    },
    // 初始化编辑地图的中心点
    initMapCenter() {
      if (this.currentPoint && this.currentPoint.lat && this.currentPoint.lng) {
        this.searchBody = this.currentPoint.address;
        this.marker = new AMap.Marker({
          map: this.dialogMap,
          position: [this.currentPoint.lng, this.currentPoint.lat],
          icon: require(`@/assets/images/place/flag_red.png`)
        });
        this.dialogMap.setCenter([this.currentPoint.lng, this.currentPoint.lat]);
        this.dialogMap.setZoom(14);
      }
    },
    // 选择查询结果
    select(e) {
      this.placeSearch.setCity(e.poi.adcode);
      this.placeSearch.search(e.poi.name, (status, result) => {
        // 搜索成功时，result即是对应的匹配数据
        if (result && result.info && result.info === 'OK' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
          this.currentPoint.lat = result.poiList.pois[0].location.lat;
          this.currentPoint.lng = result.poiList.pois[0].location.lng;
          this.currentPoint.address = e.poi.name;
          this.dialogMap.clearMap();
          this.marker && this.dialogMap.remove(this.marker);
          this.marker = new AMap.Marker({
            map: this.dialogMap,
            position: [this.currentPoint.lng, this.currentPoint.lat],
            icon: require(`@/assets/images/place/flag_red.png`)
          });
          this.dialogMap.setZoom(14);
          this.dialogMap.setCenter([this.currentPoint.lng, this.currentPoint.lat]);
        }
      });
    },
    //定位地址
    regeoCode() {
      this.geocoder.getAddress(
        [this.currentPoint.lng, this.currentPoint.lat],
        (status, result) => {
          if (status === 'complete' && result.regeocode) {
            this.currentPoint.address = result.regeocode.formattedAddress;
            this.searchBody = result.regeocode.formattedAddress;
          }
        }
      );
    },
    handleMapSave() {
      if (this.currentPoint.lat && this.currentPoint.lng) {
        //通知父组件
        this.$emit("handleMapDialogPoint", this.currentPoint);
        this.visible = false;
        this.$emit('update:mapDialogVisible', false);

      } else {
        this.$message.error('请在地图上选择位置后保存！');
      }
    },
    closeDialog() {
      this.$emit('update:mapDialogVisible', false);
    }
  },
}
</script>

<style scoped>
.dialog-map {
  width: 100%;
  height: 400px;
}
.search-body {
  position: absolute;
  top: 90px;
  left: 25px;
  width: 350px;
}
</style>