<template>
  <div>
    
    <div id="map" ref="map" :style="mapStyle" v-if="isWeb"></div>

    <map ref="map" :style="mapStyle" v-if="isWeb==false" :intervalTime='intervalTimeNative' @locatedSuccess="locatedSuccess" @locatedFail="locatedFail"></map>

  </div>
</template>

<script>
import Utils from "../utils";
// 去除lighting-ui组件内在小程序运行环境中所有引入的weex环境变量
import Light from 'light';
const modal = Light.requireModule("modal");
export default {
  data: function() {
    return {
      isWeb: false,
      longitude: "", //经度
      latitude: "", //纬度
      mapStyle: {
        width: "750px",
        height: this.mapHeight + "px"
      },
      result: "",
      intervalTimeNative: this.intervalTime
    };
  },
  props: {
    // 地图在该视图上的高度
    mapHeight: {
      type: Number,
      default: 500
    },
    description: {
      type: String,
      default: "杭州"
    },
    searchRadius: {
      type: Number,
      default: 1000
    },
    intervalTime: {
      type: Number,
      default: 30000
    },
  },
  methods: {
    //添加定位控件
    /*addLocation(){
      var that = this;
      var map = new BMap.Map("map");

      // 添加带有定位的导航控件
      var navigationControl = new BMap.NavigationControl({
        // 靠左上角位置
        anchor: BMAP_ANCHOR_TOP_LEFT,
        // LARGE类型
        type: BMAP_NAVIGATION_CONTROL_LARGE,
        // 启用显示定位
        enableGeolocation: true
      });
      map.addControl(navigationControl);
      // 添加定位控件
      var opts={enableAutoLocation:true};
      var geolocationControl = new BMap.GeolocationControl(opts);
      map.addControl(geolocationControl);

      geolocationControl.location();//这里是执行定位事件
      geolocationControl.addEventListener("locationSuccess", function(e){
        // 定位成功事件
        console.log(e)
        that.longitude=e.point.lng;
        that.latitude=e.point.lat;
        var point = new BMap.Point(e.point.lng,e.point.lat );
        map.centerAndZoom(point, 13);
        map.addOverlay(new BMap.Marker(new BMap.Point(e.point.lng,e.point.lat )));
      });
      geolocationControl.addEventListener("locationError",function(e){
          // 定位失败事件
          alert(e.message);
      });
    }, */

    // 定位
    relocate() {
      if (this.isWeb == true) {
        var that = this;
        var map = new BMap.Map("map");

        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(
          function(r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
              // 97877 【TS:201809140638-财富业委会-冯洋洋-【需求描述】 需求内容：调用百度地图定位功能 成】
              that.$emit('locatedStatus',"success")
              var mk = new BMap.Marker(r.point);
              var point = new BMap.Point(r.longitude, r.latitude);
              map.centerAndZoom(point, 13);
              map.addOverlay(mk);
              map.panTo(r.point);
              that.longitude = r.longitude;
              that.latitude = r.latitude;
            } else {
              this.$emit('locatedStatus',"failed")
              /* modal.toast({
                message: "定位失败" + this.getStatus(),
                duration: 1
              }); */
            }
          },
          { enableHighAccuracy: true }
        );
      } else {
        this.$refs.map.relocate();
      }
    },

    // 自动定位
    autoRelocate() {
      if (this.isWeb == true) {
        var that = this;

        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(
          function(r) {
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
              that.$emit('locatedStatus',"success")
              that.longitude = r.longitude;
              that.latitude = r.latitude;
              // console.log(that.longitude,that.latitude)
            } else {
              this.$emit('locatedStatus',"failed")
            }
          },
          { enableHighAccuracy: true }
        );
      } else {
        this.$refs.map.relocate();
      }
    },

    //逆地址批量查询
    getLocation() {
      if (this.isWeb == true) {
        var that = this;
        var map = new BMap.Map("map");
        var point = new BMap.Point(this.longitude, this.latitude);

        map.centerAndZoom(point, 13);
        map.enableScrollWheelZoom(true);
        // var adds=[];
        var myGeo = new BMap.Geocoder();
        this.result = "";
        myGeo.getLocation(
          point,
          function(rs) {
            // adds=rs.surroundingPois
            map.addOverlay(
              new BMap.Marker(new BMap.Point(that.longitude, that.latitude))
            );
            /* for(var k = 0; k<adds.length; k++){
              //地图上显示附近点
              //  var marker = new BMap.Marker(adds[k].point);
              //  map.addOverlay(marker);
              //  marker.setLabel(new BMap.Label("附近点:"+(k+1),{offset:new BMap.Size(20,-10)}));
              that.result += adds[k].point.lng + "," + adds[k].point.lat + "："  + "商圈(" + rs.business + ")  结构化数据(" + adds[k].address + ", " + adds[k].title + ")<br/><br/>";
            } */
            var sur = rs.surroundingPois;
            var suround = [];
            for (var i = 0; i < sur.length; i++) {
              suround.push(sur[i].address + sur[i].title);
            }
            that.$emit("getAddInfo", suround);
          },
          { poiRadius: 500, numPois: 10 }
        );
      } else {
        this.$refs.map.getLocation(data => {
          var sur = data.poiList;
          var suround = [];
          for (var i = 0; i < sur.length; i++) {
            suround.push(
              sur[i].city +
                sur[i].district +
                sur[i].streetName +
                sur[i].streetNumber +
                sur[i].name
            );
          }
          this.$emit("getAddInfo", suround);
        });
      }
    },

    //搜索
    // 96931 【TS:201809110307-财富业委会-周文龙-【需求描述】 需求内容：地图定位支持，页面效果见】
    searchLocation(val) {
      if (this.isWeb == true) {
        var that = this;
        var map = new BMap.Map("map"); // 创建Map实例
        var mPoint = new BMap.Point(this.longitude, this.latitude);

        map.enableScrollWheelZoom();
        map.centerAndZoom(mPoint, 15);

        if(this.searchRadius==0){
          var circle = new BMap.Circle(mPoint, 1000, {
            fillColor: "blue",
            strokeWeight: 1,
            fillOpacity: 0.3,
            strokeOpacity: 0.3
          });
        }else{
          var circle = new BMap.Circle(mPoint, this.searchRadius, {
            fillColor: "blue",
            strokeWeight: 1,
            fillOpacity: 0.3,
            strokeOpacity: 0.3
          });
        }
        
        map.addOverlay(circle); //添加圆形区域
        var local = new BMap.LocalSearch(map, {
          renderOptions: { map: map, autoViewport: false }
        });
        if (val == "") return;

        //93005 需求98329：【TS:201809180356-财富业委会-冯洋洋-【需求描述】 需求内容：地图定位添加搜索功能，希】-提供传入搜索范围大小的参数接口
        if(this.searchRadius==0){
          local.searchNearby(val, mPoint, 1000);
        }else{
          local.searchNearby(val, mPoint, this.searchRadius);
        }
        local.setSearchCompleteCallback(function() {
          // 115557 lc-map组件，搜索功能报错，请排查原因，配置包见附件
          // var neb = local.getResults().Br;
          // 205635	【lighting-ui】map组件H5搜索附近位置10个点失效
          var neb = local.xf;
          var nearby = [];
          for (var i = 0; i < neb.length; i++) {
            nearby.push(neb[i].title + neb[i].address);
          }
          if(nearby==''){
            modal.toast({
              message: "暂无搜索结果",
              duration: 1
            })
          }
          that.$emit("getNearby", nearby);
        });
      } else {
        // 115557 lc-map组件，搜索功能报错，请排查原因，配置包见附件
        var that = this;
        this.$refs.map.search(val, function (data) {
          var neb = data.poiList;
          var nearby = [];
          for (var i = 0; i < neb.length; i++) {
            nearby.push(neb[i].name + neb[i].address);
          }
          that.$emit("getNearby", nearby);
        });
      }
    },

    locatedSuccess(){
      this.$emit('locatedStatus',"success")
    },
    locatedFail(){
      this.$emit('locatedStatus',"failed")
    }

  },
  mounted() {
    if (Utils.env.isWeb()) {
      var that = this;
      this.isWeb = true;
      this.$nextTick(function() {
        that.relocate();
        setInterval(that.autoRelocate,that.intervalTime)
      });
    } else {
      this.isWeb = false;
    }
  }
};
</script>
 
<style scoped>
.anchorBL {
  display: none;
}
</style>
