<template>
  <view class="xd-baidu">
    <baidu-map
      v-if="uiAk"
      class="xd-baidu__content"
      :center="uiCenter"
      :zoom="uiLevel"
      :ak="uiAk"
      @ready="handleReady"
      @tilesloaded="handleTilesloaded"
    >
      <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT" type="NavigationControlType"></bm-navigation>
      <bm-geolocation
        v-if="isGeolocation"
        @locationSuccess="handleLocationSuccess"
        class="xd-baidu__content-geolocation"
        anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
        :showAddressBar="true"
        :autoLocation="true"

      ></bm-geolocation>
      <bm-marker
        v-if="isGeolocation && uiGeolocation !== null"
        :position="uiGeolocation"
        :dragging="false"
        animation="BMAP_ANIMATION_BOUNCE"
      ></bm-marker>
      <bm-marker
        v-if="isMaker"
        :position="uiCenter"
        :dragging="false"
        animation="BMAP_ANIMATION_BOUNCE"
      ></bm-marker>
      <template v-if="defaultOverlays !== null" v-for="(item,index) in defaultOverlays">
        <bm-circle
          v-if="item.type === 'Circle'"
          :center="getArrayToObject(item.value[0])"
          :radius="strToNumber(item.r)"
          :stroke-color="stroke.strokeColor"
          :stroke-opacity="stroke.fillOpacity"
          :stroke-weight="stroke.strokeWeight"
          :fill-color="stroke.fillColor"
          :fill-opacity="stroke.fillOpacity"
          :editing="false"
        ></bm-circle>
        <bm-polygon
          v-if="item.type === 'Polygon'"
          :path="getArraysToObjects(item.value)"
          :stroke-color="stroke.strokeColor"
          :stroke-opacity="stroke.fillOpacity"
          :stroke-weight="stroke.strokeWeight"
          :fill-color="stroke.fillColor"
          :fill-opacity="stroke.fillOpacity"
          :editing="false"
        ></bm-polygon>
        <bm-marker
          v-if="item.type === 'Marker'"
          :position="getArrayToObject(item.value[0])"
          :dragging="false"
          animation="BMAP_ANIMATION_BOUNCE"
        ></bm-marker>
        <bm-boundary
          v-if="item.type === 'city'"
          :name="item.value"
          :stroke-color="stroke.strokeColor"
          :stroke-opacity="stroke.fillOpacity"
          :stroke-weight="stroke.strokeWeight"
          :fill-color="stroke.fillColor"
          :fill-opacity="stroke.fillOpacity"
        ></bm-boundary>
      </template>
    </baidu-map>
  </view>
</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 {Boolean} isMaker 完成中心点设置之后是否标记中心点位置 （选填） 默认：false
   * @property {Boolean} isGeolocation 是否启用定位控件 （选填） 默认：true
   * @property {String} ak 百度Ak （选填） 默认：''
   * @property {Number} level 缩放级别 （选填） 默认：15
   * @property {Array} defaultOverlays 覆盖物对象 （选填） 默认：[]
   *
   * @event {Function} onDone 编辑或者创建覆盖物完成事件 参数：overlays(覆盖物对象)， overlaysSource(覆盖物数据)
   */

  import BaiduMap from 'vue-baidu-map/components/map/Map.vue';
  import BmMarker from 'vue-baidu-map/components/overlays/Marker';
  import BmCircle from 'vue-baidu-map/components/overlays/Circle';
  import BmPolygon from 'vue-baidu-map/components/overlays/Polygon';
  import BmGeolocation from 'vue-baidu-map/components/controls/Geolocation';
  import BmBoundary from 'vue-baidu-map/components/others/Boundary';
  import BmNavigation from 'vue-baidu-map/components/controls/Navigation';

  export default {
    name: "XdBaiduOverlay",
    components:{
      BaiduMap,
      BmMarker,
      BmGeolocation,
      BmCircle,
      BmPolygon,
      BmBoundary,
      BmNavigation
    },
    props:{
      center: {
        type: Array | null,
        default(){
          return null
        }
      },

      isGeolocation:{
        type:Boolean,
        default: true
      },

      isMaker: {
        type:Boolean,
        default: false
      },

      level: {
        type:Number,
        default: 15
      },

      defaultOverlays: {
        type: Array | null,
        default(){
          return [
            // {
            //   type: 'Polyline',
            //   value: [[116.399, 39.910],[116.405, 39.920],[116.423493, 39.907445]]
            // },
            // {
            //   type: 'Polygon',
            //   value: [[116.399, 39.910],[116.405, 39.920],[116.423493, 39.907445]]
            // },
            {
              type: 'Polygon',
              value: [
                [116.387112, 39.920977],
                [116.385243, 39.913063],
                [116.394226, 39.917988],
                [116.401772, 39.921364],
                [116.41248, 39.927893]
              ]
            },
            {
              type: 'Circle',
              r: 1000, //1米
              value: [
                [116.423493, 39.907445],
              ]
            },
            {
              type: 'Marker',
              value: [[116.4782359673445, 39.909576462078476]]
            },
            {
              type: 'city',
              value: '贵阳'
            },
            {
              type: 'city',
              value: '山东'
            },

            {
              type: 'Boundary',
              value:[
                [[116.399, 39.910], [116.405, 39.920], [116.423493, 39.907445]],
                [
                  [116.38711199999995, 39.92097707656194],
                  [116.38524299999993, 39.91306307719058],
                  [116.4289369609569, 39.900997411802976],
                  [116.42548746779859, 39.91876314730457],
                  [116.41247999999993, 39.9278930760079],
                  [116.38711199999995, 39.92097707656194]
                ]
              ]
            }
          ]
        }
      },

      ak: {
        type: String,
        default: ''
      },
    },

    watch:{
      BMap(){
        if(this.BMap !== null && this.loaded) {
          this.handleInitDone({BMap: this.BMap});
        }
      },
      loaded(){
        if(this.BMap !== null && this.loaded) {
          this.handleInitDone({BMap: this.BMap});
        }
      }
    },

    data(){
      return {
        uiLevel: 15,
        uiCenter: null,
        uiGeolocation: null,
        uiAk: null,

        stroke: {
          strokeColor: '#f00',
          strokeWeight: 2,
          fillColor: 'blue',
          fillOpacity: 0.4,
          strokeOpacity: .8
        },

        //判断地图是否加载完成
        BMap: null,
        loaded: false,
      }
    },


    created() {
      this.uiAk = this.$settings.baiduAk || this.ak;
      if(!this.uiAk) throw new Error('请传入百度AK值');
      else{
        let uiCenter = '北京';
        if(this.center !== null) {
          if(this.$xdUniHelper.checkVarType(this.center) === 'array'
            && this.center.length === 2
          ) {
            uiCenter = this.getArrayToObject(this.center);
          }
          if(this.$xdUniHelper.checkVarType(this.center) === 'string'){
            uiCenter = this.center;
          }
        }

        //自动定位到第一个覆盖物
        if(this.defaultOverlays && this.defaultOverlays.length > 0) {
          if(this.$xdUniHelper.checkVarType(this.defaultOverlays[0].value) === 'array') {
            uiCenter = this.getArrayToObject(this.defaultOverlays[0].value[0]);
          }
          if(this.$xdUniHelper.checkVarType(this.defaultOverlays[0].value) === 'string'){
            uiCenter = this.defaultOverlays[0].value;
          }
        }
        this.uiCenter = uiCenter;

        if(this.level) this.uiLevel = this.level;
      }
    },

    methods: {
      getArraysToObjects(arr){
        return  arr.map(item=>{
          return {
            lng: Number(item[0]),
            lat: Number(item[1])
          }
        })
      },
      getArrayToObject(arr){
        return {
          lng: Number(arr[0]),
          lat: Number(arr[1])
        }
      },

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

      handleInitDone({BMap}){
        if(this.isGeolocation) {
          let geolocation = new BMap['Geolocation']();
          geolocation['enableSDKLocation']();
          geolocation.getCurrentPosition(
            (location) => {
              console.log('handleInitDone',location)
              if(!this.defaultOverlays || this.defaultOverlays.length === 0) {
                let point = this.$xdUniHelper.cloneDeep(location.point);
                delete point['of']
                this.uiGeolocation = point;
                this.uiLevel = 15;
                this.uiCenter = point;
              }
              this.$emit('onLocationSuccess',location);
            },
            (error) => {
              console.log('handleInitDone',error)
            }
          )
        }
      },

      handleReady({BMap}){
        this.BMap = BMap;
      },

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

      strToNumber(str){
        if(str === '' || str === null || str === undefined) return '';
        if (this.$xdUniHelper.checkVarType(str) === 'string') str = Number(str);
        return str;
      }
    },
  }
</script>

<style scoped lang="less">
  .xd-baidu {
    width: 100%;
    height: 100%;
    box-sizing: border-box;

    &__content {
      height: 100%;
    }

  }

</style>
