<template>
  <baidu-map id="map" class="map" style="height: 350px;" :center="center" :zoom="zoom" @ready="handler" @click="mapClick(this, $event)">
    <!--  缩放  -->
    <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
  </baidu-map>
</template>
<script src="http://api.map.baidu.com/api?v=2.0&ak=iSEprDCqtYn5aC06Y3cDyGCEOP1hydwR"></script>

<script>
  import BaiduMap from 'vue-baidu-map';
  import {
    getSonRegionByCodes,
    getRegionByCodes,
  } from 'api/base_info/region/';
  import {
    campsiteAllPage,
  } from 'api/base_info/campsite';
  import {
    allPage,
  } from 'api/base_info/branch_company';
  export default {
    props: ["toSonData","provinceName"],
    data() {
      return {
        center: {
          lng: 108.9462765501,
          lat: 34.3474989219
        },  // 经纬度
        zoom: 4, // 地图展示级别
        pointList: [],
        map: null,
        pickPoint: null,
        listQuery: {
          page: 1,
          limit: 10000,
          addrProvince: undefined,
          addrCity: undefined,
          addrTown: undefined
        },
      }
    },
    mounted() {
//      let that = this;
//      if(this.map){
//        this.map.addEventListener("zoomend", function(e){
//          var ZoomNum = that.map.getZoom();
//          this.addMarker(map);
//        });
//      }
    },
    watch: {
      provinceName(newValue, oldValue) {
        let that = this;
        console.log(this.provinceName);
        if(this.map){
          if(this.provinceName == "兰州"){
            this.map.centerAndZoom("兰州",4);
          } else {
            this.map.centerAndZoom(this.provinceName,6);
          }
        }
//        this.map.addEventListener("zoomend", function(e){
//          var ZoomNum = that.map.getZoom();
//          that.map.clearOverlays();//清空地图上标注点
//          that.addMarker(this,map);
//        });
      },
    },
    methods: {
      handler({map}) {
        this.map = map;
        if(this.toSonData =="campsite"){
          campsiteAllPage(this.listQuery)
            .then(response => {
              let listTemp = response.data.data;
              let arr = [];
              listTemp.map(function(item){
                arr.push(item);
              });
              this.list = arr;
              // 定位
              this.geolocation(map);
              // 产生随机点
              const bounds = map.getBounds();
              for (let i = 0; i < arr.length; i++) {
                const point = {
                  title: "",//list[i].name
                  point: {
                    lng: arr[i].longitude,
                    lat: arr[i].latitude
                  }
                };
                this.pointList.push(point);
              }
              this.addMarker(map);
            })
        } else {
          allPage(this.listQuery)
            .then(response => {
              let listTemp = response.data.data;
              let arr = [];
              listTemp.map(function(item){
                arr.push(item);
              });
              this.list = arr;
              // 定位
              this.geolocation(map);
              // 产生随机点
              const bounds = map.getBounds();
              for (let i = 0; i < arr.length; i++) {
                const point = {
                  title: "",//list[i].name
                  point: {
                    lng: arr[i].longitude,
                    lat: arr[i].latitude
                  }
                };
                this.pointList.push(point);
              }
              this.addMarker(map);
            })
        }

      },
      mapClick(map, e) {
        const point = e.point;
        if (this.pickPoint) {
          map.removeOverlay(this.pickPoint);
        }
        console.log(point.lng + ',' + point.lat);
        map.panTo(point);
        map.centerAndZoom(point,6);
        const p = new BMap.Point(point.lng, point.lat);
        this.pickPoint = new BMap.Marker(p);
        this.addressDetail(point);//根据经纬度获取省市信息
//        this.addMarker(map);
      },
      addressDetail(point){ //获取地理位置
        let mydata = getSonRegionByCodes(1);
        var self = this;
        var myGeo = new BMap.Geocoder();
        myGeo.getLocation(new BMap.Point(point.lng, point.lat), function(result){
          if (result){
//根据当前位置经纬度解析成地址
//            console.log(result.addressComponents);
            mydata.map(function(item){
              if(result.addressComponents.province.indexOf("北京") !=-1 || result.addressComponents.province.indexOf("重庆") !=-1
                || result.addressComponents.province.indexOf("上海") !=-1 || result.addressComponents.province.indexOf("台湾") !=-1 || result.addressComponents.province.indexOf("天津") !=-1){
                result.addressComponents.province=result.addressComponents.province.substring(0,2);
              }
              if(item.name.indexOf(result.addressComponents.province) !=-1){
                self.$emit('headCallBack', item.agencyId);
              }
            });
          }
        });
      },
      addMarker(map) {
        let  zoom = map.getZoom();
        var myIcon = new BMap.Icon('https://cwmp.upyuns.com/attachment/images/4/2019/05/HnFr78H280dv972KuNZku70297rz7z.png',new BMap.Size(16,16));//这里先不用第三个参数IconOptions;
//        if(zoom <6){
//          myIcon = new BMap.Icon('https://cwmp.upyuns.com/attachment/images/4/2019/05/HnFr78H280dv972KuNZku70297rz7z.png',new BMap.Size(16,16));//这里先不用第三个参数IconOptions
//        }
        for (const item of this.pointList) {
          const point = new BMap.Point(item.point.lng, item.point.lat);
          var mk = new BMap.Marker(point, {icon:myIcon});
//          if(zoom > 6){
//            mk = new BMap.Marker(point);
//          }
          const label = new BMap.Label(item.title);
          label.setOffset(new BMap.Size(15, -15));
          label.setStyle({
            'border-radius': '5px',
            border: '0px',
            'background-color': '#FFFFFF11',
            color: 'red',
            'font-family': '黑体',
            'font-weight': 'bold',
            'font-size': '16px'
          });
          mk.setLabel(label);
          map.addOverlay(mk);
        }
      },
      geolocation(map) {
        const geolocation = new BMap.Geolocation();
        geolocation.enableSDKLocation();
        geolocation.getCurrentPosition(function (r) {
          if (this.getStatus() === BMAP_STATUS_SUCCESS) {
            // const mk = new BMap.Marker(r.point);
            // map.addOverlay(mk);
            var b = new BMap.Bounds(new BMap.Point(116.027143, 39.772348),new BMap.Point(116.832025, 40.126349)); // 范围 左下角，右上角的点位置
//            map.panTo(r.point);
            map.centerAndZoom("兰州",4);
            map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
            console.log('您的位置：' + r.point.lng + ',' + r.point.lat);
          } else {
            alert('failed' + this.getStatus());
          }
        });
      }
    }
  }
</script>

<style scoped>
  .map {
    width: 100%;
    height: 500px;
  }
</style>
