<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 {
    page,
    addObj,
    getObj,
    delObj,
    putObj
  } 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() {
    },
    watch: {
      provinceName(newValue, oldValue) {
        console.log(this.provinceName);
        if(this.map){
          if(this.provinceName == "兰州"){
            this.map.centerAndZoom("兰州",4);
          } else {
            this.map.centerAndZoom(this.provinceName,6);
          }
        }
      },
    },
    methods: {
      getList() {
        page(this.listQuery)
          .then(response => {
            let listTemp = response.data.data;
            //一次读入所有涉及地区，防止多次读取
            if (!this.$utils.isEmpty(listTemp)) {
              let allRegions = new Set();
              for (let index in listTemp) {
                allRegions.add(listTemp[index].addrProvince);
                allRegions.add(listTemp[index].addrCity);
                allRegions.add(listTemp[index].addrTown);
                let regions = getRegionByCodes([listTemp[index].addrProvince, listTemp[index].addrCity, listTemp[index].addrTown]);
                listTemp[index].address = regions[0].name + ' ' + regions[1].name + ' ' + regions[2].name + ' ';
              }
              getRegionByCodes([...allRegions]);
            }
            let arr = this.list;
            listTemp.map(function(item){
              arr.push(item);
            });
            this.list = arr;
          })
      },
      handler({map}) {
        this.map = map;
        let list = this.toSonData;
        // 定位
        this.geolocation(map);
        // 产生随机点
        const bounds = map.getBounds();
        for (let i = 0; i < list.length; i++) {
          const point = {
            title: "",//list[i].name
            point: {
              lng: list[i].longitude,
              lat: list[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);//根据经纬度获取省市信息
      },
      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) {
        for (const item of this.pointList) {
          const point = new BMap.Point(item.point.lng, item.point.lat);
          const 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>
