<template>
  <baidu-map
    class="xd-baidu__content"
    v-if="ak && initStatus"
    :key="refushKey"
    :style="{top: top, background:bgc}"
    :center="uiCenter"
    :zoom="uiLevel"
    :ak="ak"
    @ready="handleReady"
    @tilesloaded="handleTilesloaded"
  >
    <bm-label
      v-if="showLocation && LocationContent && uiGeolocation"
      :content="LocationContent"
      :position="uiGeolocation"
      :labelStyle="{color: 'red', fontSize : '12px', padding: '5px 10px'}"
      title="我的坐标"/>
    <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT" type="NavigationControlType"></bm-navigation>
    <bm-geolocation
      @locationSuccess="handleLocationSuccess"
      class="xd-baidu__content-geolocation"
      anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
      :showAddressBar="true"
      :autoLocation="true"
    ></bm-geolocation>
    <bm-marker
      v-if="uiGeolocation !== null"
      :position="uiGeolocation"
      :dragging="false"
      animation="BMAP_ANIMATION_BOUNCE"
    ></bm-marker>
  </baidu-map>
</template>

<script>

/**
 * @description 仅仅支持H5端
 * https://dafrok.github.io/vue-baidu-map/#/zh/start/usage
 * https://lbsyun.baidu.com/cms/jsapi/reference/jsapi_reference.html#a0b0
 * 文档：https://www.npmjs.com/package/gxd-helper
 *
 * @property {Array} center 设置中心点坐标 （选填） 默认：null
 * @property {String} ak 百度Ak （选填） 默认：''
 * @property {Number} level 缩放级别 （选填） 默认：15
 * @event {Function} onLocationSuccess 返回成功对象（location）
 */
  import BaiduMap from 'vue-baidu-map/components/map/Map.vue';
  import BmMarker from 'vue-baidu-map/components/overlays/Marker';
  import BmGeolocation from 'vue-baidu-map/components/controls/Geolocation';
  import BmNavigation from 'vue-baidu-map/components/controls/Navigation';
  import BmLabel from 'vue-baidu-map/components/overlays/Label';

  export default {
    name: "XdBaiduMap",
    components:{
      BaiduMap,
      BmMarker,
      BmGeolocation,
      BmNavigation,
      BmLabel
    },
    props:{
      center: {
        type: Array,
        default(){
          return null
        }
      },
      ak: {
        type: String,
        default: ''
      },
      level: {
        type:Number,
        default: 15
      },
    },
    data(){
      return {
        count: 0,
        location: {},
        uiLevel: 15, //放大缩小级别
        uiCenter: null, //设置定位点
        uiGeolocation: null, //获取定位点
        top: '-9999px', //开启地图调试模式
        bgc: 'none', //开启地图显示背景
        showLocation: null,//是否显示坐标
        LocationContent: null, //坐标信息
        refushKey: 'baidu',//刷新
        initStatus: true, //是否新刷新状态

        //百度定位
        BMap: null, //百度SDK对象
        BMapLoaded: false, //地图加载完成状态
        map: null, //百度SDK对象实例化对象
      }
    },
    watch:{
      BMap(){
        if(this.BMap !== null && this.BMapLoaded) {
          this.handleInitDone({BMap: this.BMap});
        }
      },
      BMapLoaded(){
        if(this.BMap !== null && this.BMapLoaded) {
          this.handleInitDone({BMap: this.BMap});
        }
      }
    },
    created() {
      if(!this.ak) throw new Error('请传入百度AK值');
      else{
        let page = this.$xdUniHelper.parseURL();
        if(page && page.params && page.params.top) {
          this.top = '0';
          this.bgc = '#fff';
          this.showLocation = true;
        }
      }

    },
    methods:{
      handleReady({BMap,map}){
        this.BMap = BMap;
        this.map = map;
      },

      handleTilesloaded(){
        this.BMapLoaded = true;
      },

      handleLocationSuccess(location){
        let point = this.$xdUniHelper.cloneDeep(location.point);
        delete point['of']
        this.uiGeolocation = point;
        this.uiLevel = 15;
        this.uiCenter = point;
        this.location = location;
        this.$emit('onLocationSuccess',location);
      },

      reLoad(){
        if(this.count > 10) {
          return;
        }
        this.initStatus = false;
        this.BMapLoaded = false;
        this.BMap = null;
        this.map = null;
        this.refushKey = this.$xdUniHelper.randomChar(20);

        setTimeout(()=>{
          this.initStatus = true;
          this.count++;
        },100)
      },

      handleInitDone({BMap}){
        let geolocation = new BMap['Geolocation']();
        geolocation['enableSDKLocation']();
        geolocation.getCurrentPosition(
          (location) => {
            console.log('handleInitDone',location)
            let point = this.$xdUniHelper.cloneDeep(location.point);
            delete point['of']
            this.uiGeolocation = point;
            this.uiLevel = 15;
            this.uiCenter = point;
            this.location = location;
            this.LocationContent = `我的坐标:{lat:${location.latitude}, lng:${location.longitude}}`
            this.$emit('onLocationSuccess',location);
          },
          (error) => {
            this.reLoad();
            //百度定位失败
            if (typeof getApp()['saveLogs'] === 'function') {
              getApp()['saveLogs']({
                location: this.location,
                status: 'fail',
                baiduStatus: geolocation.getStatus(),
                result: res,
                locationType: 'baidu.com',
                pos: 'XdCityLocation'
              }, 'info');
            }
            this.$emit('onLocationSuccess',this.location);
          }
        )
      },
    }
  }
</script>

<style scoped lang="less">
  .xd-baidu__content {
    position: fixed;
    left: 0;
    width: 100%;
    height: 50%;
    z-index: 3000;
  }
</style>
