<template>
  <div style="position: relative;">
    <div style="display: flex;">
      <input id="tipinput" class="el-input__inner" placeholder="搜索地址" v-model="address" style="margin-right: 100px;">
      <button class="el-button" @click="startEdit" style="margin-bottom: 5px">编辑区域</button>
      <button class="el-button" @click="closeEdit" style="margin-bottom: 5px">编辑完成</button>
      <button class="el-button" @click="getPath" style="margin-bottom: 5px">保存</button>
    </div>
    <div id="container"  style="height: 500px;display: block;position: relative;">
      <div id="panel" style="position: absolute;top: 0;bottom:0;right: 0;width: 300px;overflow: auto;z-index: 9;"></div>
    </div>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        location:{
          latitude: "39.994257",
          longitude: "116.471354",
        },
        map:null,
        polyEditor:null,
        marker:null,
        polygonPath:[],
        address:'',
      }
    },
    props:['editForm'],
    mounted() {
      let data = this.editForm
      if(data){
        if(data.longitude!==""&&data.latitude!==""){
          this.location.longitude = data.longitude
          this.location.latitude = data.latitude
        }
        if(data.boundaryPath!==""&&data.boundaryPath!==null&&data.boundaryPath!==undefined){
          this.polygonPath = JSON.parse(data.boundaryPath)
        }
      }
      this.initMap()
      this.setMark(this.location)
      this.initPolygon()
      this.initSearch()
    },
    methods:{
      initMap(){
        var _this = this
        this.map = new AMap.Map('container', {
          resizeEnable: true, //是否监控地图容器尺寸变化
          center: [this.location.longitude, this.location.latitude],
          zoom: 16,
        });
        this.map.on('click', function(e) {
          _this.location['longitude'] = e.lnglat.getLng()
          _this.location['latitude'] = e.lnglat.getLat()
          _this.setMark(_this.location)
        });
      },
      setMark(data){
        var _this = this
        if(this.marker){
          this.map.remove(this.marker);
        }
        AMap.plugin('AMap.Geocoder', function() {
          var geocoder = new AMap.Geocoder({})
          var lnglat = [data.longitude, data.latitude]
          geocoder.getAddress(lnglat, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                // result为对应的地理位置详细信息
                let address = result.regeocode.formattedAddress
                _this.marker = new AMap.Marker({
                  position: new AMap.LngLat(data.longitude, data.latitude), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                });
                _this.marker.setLabel({
                    direction:'center top',
                    offset: new AMap.Pixel(10, 0),  //设置文本标注偏移量
                    content: address, //设置文本标注内容
                });
                _this.address = address
                _this.map.add(_this.marker);
            }
          })
        })

      },
      initSearch(){
          var _this = this
          //输入提示
          var autoOptions = {
              input: "tipinput"
          };
          AMap.plugin(['AMap.PlaceSearch','AMap.AutoComplete'], function(){
              var auto = new AMap.AutoComplete(autoOptions);
              var placeSearch = new AMap.PlaceSearch({
                  pageSize: 5, // 单页显示结果条数
                  pageIndex: 1, // 页码
                  map: _this.map, // 展现结果的地图实例
                  panel: "panel", // 结果列表将在此容器中进行展示。
                  autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
              });  //构造地点查询类
              auto.on("select", select);//注册监听，当选中某条记录时会触发
              function select(e) {
                  placeSearch.setCity(e.poi.adcode);
                  placeSearch.search(e.poi.name);  //关键字查询查询
              }
          });
      },
      initPolygon(){
        var _this = this;
        this.polyEditor = new AMap.PolygonEditor(this.map);
        this.setPolygon(this.polygonPath)
        this.polyEditor.on('add', function (data) {
          var polygon = data.target;
          _this.polyEditor.addAdsorbPolygons(polygon);
          // polygon.on('click', (res) => {
          //   console.log(res)
          //   _this.polyEditor.setTarget(polygon);
          //   _this.polyEditor.open();
          // })
        })
      },
      setPolygon(data){
        if(data.length<1)return
        var _this = this
            let polygon = new AMap.Polygon({
              path: data,
              fillColor: '#ccebc5',
              strokeOpacity: 1,
              fillOpacity: 0.5,
              strokeColor: '#2b8cbe',
              strokeWeight: 1,
              strokeStyle: 'dashed',
              strokeDasharray: [5, 5],
            });
            polygon.on('mouseover', () => {
              polygon.setOptions({
                fillOpacity: 0.7,
                fillColor: '#7bccc4'
              })
            })
            polygon.on('mouseout', () => {
              polygon.setOptions({
                fillOpacity: 0.5,
                fillColor: '#ccebc5'
              })
            })
            polygon.on('click', () => {
              this.polyEditor.open();
            })
            this.map.add(polygon);
            this.map.setFitView();
            _this.polyEditor.setTarget(polygon)
      },
      createPolygon() {
        this.polyEditor.close();
        this.polyEditor.setTarget();
        this.polyEditor.open();
      },
      startEdit(){
        this.polyEditor.open();
      },
      closeEdit(){
        this.polyEditor.close();
      },
      getPath(){
        let target = this.polyEditor.getTarget()
        let path = ""
        if(target){
          path = target._opts.path
        }
        if(path!==""&&path!==null&&path!==undefined){
          path = JSON.stringify(path)
        }
        this.editForm.address = this.address
        this.editForm.longitude = this.location['longitude']
        this.editForm.latitude = this.location['latitude']
        this.editForm.boundaryPath = path
        this.$emit('update:editForm', this.editForm)
        this.$emit('update:visible', false)
      }
    }
  }
</script>

<style>
  .amap-sug-result{
        z-index: 999999999;
  }
</style>
