<template lang="html">
  <div class="container-map" style="text-align: right">
    <div class="search-box">
      <input
        v-model="searchKey"
        type="search"
        placeholder="输入关键字进行搜索"
        id="search">
      <div class="tip-box" id="searchTip"></div>
    </div>
    <el-amap class="amap-box"
             :amap-manager="amapManager"
             :vid="'amap-vue'"
             :zoom="zoom"
             :center="center"
             :events="events"
    >
      <!-- 标记 -->
      <el-amap-marker v-for="(marker, index) in markers" :position="marker" :key="index"></el-amap-marker>
      <el-button style="margin-top: 10px" @click="changeView(false)">取消</el-button>
      <el-button type="primary" style="margin-top: 10px" @click="changeView(true)">确定</el-button>
    </el-amap>

  </div>
</template>

<script>

import {AMapManager, lazyAMapApiLoaderInstance} from 'vue-amap'
import {mapGetters, mapActions} from 'vuex';
let polyline = undefined;
let mMap = undefined;
let path = undefined;
let polylineEditor = undefined;
let amapManager = new AMapManager()
export default {
  name:"mapArea",
  // props: ["pCenter","path"],
  props: {
    pCenter: {
      type: Array,
      default: null
    },
    path: {
      type: Array,
      default: null
    },
  },
  data() {
    let self = this
    return {
      address: null,
      searchKey: '',
      amapManager,
      markers: [],
      searchOption: {
        city: '全国',
        citylimit: true
      },
      center: [0,0],
      // center: [120.6668, 31.302732],
      zoom: 16,
      lng: 0,
      lat: 0,
      loaded: false,
      events: {
        init(o) {
          self.mMap = o;
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initSearch()

          })
          AMap.plugin('AMap.Geolocation', function() {
            var geolocation = new AMap.Geolocation({
              enableHighAccuracy: true,//是否使用高精度定位，默认:true
              timeout: 10000,          //超过10秒后停止定位，默认：5s
              buttonPosition:'RB',    //定位按钮的停靠位置
              buttonOffset: new AMap.Pixel(0, 0),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
              zoomToAccuracy: false,   //定位成功后是否自动调整地图视野到定位点
            });
            o.addControl(geolocation);
            if(self.center[0] == 0){
              //如果没有传过来地址就获取城市
              geolocation.getCityInfo((status, result) => {
                console.log(JSON.stringify("--------------"))
                console.log(JSON.stringify(result))
                self.lng = result.center[0];
                self.lat = result.center[1];
                self.center = result.center;
                self.mapCenter = self.center;
                self.markers.push([self.lng, self.lat])
                self.initArea(o);
                self.loaded = true;
                self.$nextTick();
              });
            }else{
              self.markers.push(self.center)
              self.initArea(o);
            }
          });

        },
        // 点击获取地址的数据
        click(e) {
          // console.log(e)
          self.markers = []
          let {lng, lat} = e.lnglat
          self.lng = lng
          self.lat = lat
          self.center = [lng, lat]
          self.markers.push([lng, lat])
          self.initPath()
          this.lng = lng
          this.lat = lat
        }
      },
      // 一些工具插件
      plugin: [
        {
          pName: 'Geolocation',
          events: {
            init(o) {
            }
          }
        },
        {
          // 工具栏
          pName: 'ToolBar',
          events: {
            init(instance) {
              // console.log(instance);
            }
          }
        },
        {
          // 鹰眼
          pName: 'OverView',
          events: {
            init(instance) {
              // console.log(instance);
            }
          }
        },
        {
          // 地图类型
          pName: 'MapType',
          defaultType: 0,
          events: {
            init(instance) {
              // console.log(instance);
            }
          }
        },
        {
          // 搜索
          pName: 'PlaceSearch',
          events: {
            init(instance) {
              // console.log(instance)
            }
          }
        }
      ]
    }
  },

  watch: {
    lng: function (newQuestion, oldQuestion) {
      // console.log("lng change")
      this.$emit('lng', this.lng)
    },
    lat: function (newQuestion, oldQuestion) {
      // console.log("lat change")
      this.$emit('lat', this.lat)
      // console.log( this.$parent.pCenter)
    }
  },
  created(){
    if(!this.pCenter){
      this.center = [0,0]
    }else{
      this.center= this.pCenter;


    }
    console.log(this.path)
    path = this.path
  },
  activated: function(){

  },
  methods: {
    initArea(o) {
      this.mMap = o;
      this.initPath();
    },
    initSearch() {
      let vm = this
      let map = this.amapManager.getMap()
      console.log(AMapUI)
      AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {
        var poiPicker = new PoiPicker({
          input: 'search',
          placeSearchOptions: {
            map: map,
            current: 10
          },
          suggestContainer: 'searchTip',
          searchResultsContainer: 'searchTip'
        })
        vm.poiPicker = poiPicker
        // 监听poi选中信息
        poiPicker.on('poiPicked', function (poiResult) {
          // console.log(poiResult)
          let source = poiResult.source
          let poi = poiResult.item
          if (source !== 'search') {
            poiPicker.searchByKeyword(poi.name)
          } else {
            poiPicker.clearSearchResults()
            vm.markers = []
            let lng = poi.location.lng
            let lat = poi.location.lat
            let address = poi.cityname + poi.adname + poi.name
            vm.center = [lng, lat]
            vm.markers.push([lng, lat])
            vm.lng = lng
            vm.lat = lat
            vm.address = address
            vm.searchKey = address
            vm.initPath()
          }
        })
      })
    },
    initPath() {
      if(polyline != undefined){
        // 开启编辑模式
        polylineEditor.close();
        this.mMap.remove(polyline)
        console.log("-------------------")
      }
      //添加配送范围
      let x1 = this.center[0];
      let y1 = this.center[1];
      //[{"P":31.173389,"O":120.54735800000003,"lng":120.547358,"lat":31.173389},{"P":31.223389,"O":120.52735799999999,"lng":120.527358,"lat":31.223389},{"P":31.273389,"O":120.54735800000003,"lng":120.547358,"lat":31.273389},{"P":31.288389000000002,"O":120.59735799999999,"lng":120.597358,"lat":31.288389},{"P":31.273389,"O":120.647358,"lng":120.647358,"lat":31.273389},{"P":31.223389,"O":120.66735799999998,"lng":120.667358,"lat":31.223389},{"P":31.173389,"O":120.647358,"lng":120.647358,"lat":31.173389},{"P":31.158389,"O":120.59735799999999,"lng":120.597358,"lat":31.158389}]
      if(!path){
        path = [
          [x1-0.0021, y1-0.0021],
          [x1-0.0021, y1+0.0021],
          [x1+0.0021, y1+0.0021],
          [x1+0.0021, y1-0.0021]
        ]
      }else{
        // let mPath = JSON.parse(path);
        try {
          path = JSON.parse(path)
        } catch (e) {
          console.log(e)
          path = [
            [x1-0.0021, y1-0.0021],
            [x1-0.0021, y1+0.0021],
            [x1+0.0021, y1+0.0021],
            [x1+0.0021, y1-0.0021]
          ]
        }

        // for (let i = 0;i < mPath.length; i++){
        //   path.push([mPath[i],mPath[i]])
        // }
      }
      polyline = new AMap.Polygon({
        path: path,
        isOutline: true,
        outlineColor: '#ffeeff',
        borderWeight: 2,
        strokeColor: "#3366FF",
        fillColor: '#1791fc',
        fillOpacity: 0.4,
        strokeOpacity: 1,
        strokeWeight: 3,
        // 折线样式还支持 'dashed'
        strokeStyle: "solid",
        // strokeStyle是dashed时有效
        strokeDasharray: [10, 5],
        lineJoin: 'round',
        lineCap: 'round',
        zIndex: 50,
      })

      this.mMap.add(polyline);

      // 缩放地图到合适的视野级别
      this.mMap.setFitView([ polyline ])
      let that = this;
      AMap.plugin(["AMap.PolyEditor"],function(){
        // 实例化多边形编辑器，传入地图实例和要进行编辑的多边形实例
        polylineEditor = new AMap.PolyEditor(that.mMap, polyline);

        // 开启编辑模式
        polylineEditor.open();
      });
      // this.path = [
      //   [x-0.021, y-0.021],
      //   [x-0.03, y],
      //   [x-0.021, y+0.021],
      //   [x, y+0.026],
      //   [x+0.021, y+0.021],
      //   [x+0.03, y],
      //   [x+0.021, y-0.021],
      //   [x, y-0.026]
      // ]
      // console.log(this.path)
    },
    onSearchResult(pois) {
      let latSum = 0;
      let lngSum = 0;

      if (pois.length > 0) {
        let poi = pois[0];
        this.markers = [],
          this.markers.push([poi.lng, poi.lat]);
        this.center = [poi.lng, poi.lat];
        console.log(this.center)
        path = undefined
        this.initArea(this.mMap);
        this.address = poi.name
        this.changeAddress();
        this.mapCenter = this.center;
      }
    },
    changeAddress:function () {
      // console.log(JSON.stringify("------------"))
      // console.log(JSON.stringify(path))
      // var arg = {
      //   address:this.address,
      //   lng:this.lng,
      //   lon:this.lat,
      //   area:JSON.stringify(path)
      // }
      // this.$emit("changeAddress",arg)
    },

    changeView(res){
      // console.log(JSON.parse(JSON.stringify(path)));
      var arg = {
        flag:res,
        address:this.address,
        lng:this.center[0],
        lon:this.center[1],
        area:JSON.stringify(path)
      }
      this.$emit("changeView",arg)
    }
  }
}
</script>

<style lang="scss" scoped>
.container-map {
  width: 100%;
  height: 600px;
  position: relative;
  /*left: 50%;*/
  /*top: 50%;*/
  /*transform: translate3d(-50%, -50%, 0);*/
  border: 1px solid red;
}

.search-box {
  position: absolute;
  z-index: 5;
  width: 60%;
  left: 13%;
  top: 10px;
  height: 30px;
}


.search-box button {
  float: left;
  width: 20%;
  height: 100%;
  background: #30ccc1;
  border: 1px solid #333333;
  color: #fff;
  outline: none;
}
.amap-demo {
  height: 300px;
}

.search-box {
  position: absolute;
  top: 25px;
  left: 20px;
}

.el-vue-search-box-container{
  position: absolute !important;
  left:80px;
}
.search-box input{
  float: left;
  width: 100%;
  height: 100%;
  border: 1px solid #666666;
  border-radius: 5px;
  box-shadow:0px 0px 5px #666;
  padding: 0 8px;
  outline: none;
}
.searchT{
  float: left;
  width: 20%;
  height: 100%;
  background: #38f;
  border: 1px solid #38f;
  color: #fff;
  text-align: center;
}

.tip-box {
  width: 100%;
  max-height: 260px;
  position: absolute;
  top: 30px;
  overflow-y: auto;
  background-color: #fff;
}
</style>
