<template>
  <div class="xd-baidu">
    <div class="xd-baidu__btn" v-if="isShowEdit">
      <div class="xd-baidu__btn-left" v-if="!isEditStatus">
        <div>类型：</div>
        <el-radio-group v-model="type">
          <el-radio label="2" :disabled="start || userDrawTypeStatus">画地图</el-radio>
          <el-radio label="1" :disabled="start || userDrawTypeStatus">画距离</el-radio>
          <el-radio label="3" :disabled="start || userDrawTypeStatus">画包含地图</el-radio>
        </el-radio-group>
        <div v-if="type === '1'">
          <span>设置半径（公里）</span>
          <el-input size="small" type="number" v-model="startCircleR" @change="circleChangeR()"></el-input>
        </div>
      </div>
      <div class="xd-baidu__btn-right">
        <div>
          <el-button size="small" type="primary" v-if="isEditStatus" @click="handleDone">编辑完成</el-button>
        </div>
        <div>
          <el-button size="small" v-if="isEditStatus" @click="handleDel">删除选中区域</el-button>
        </div>
        <div>
          <el-button size="small" type="primary" v-if="!isEditStatus" @click="handleStart"
                     :disabled="start || !mapLaoded">开始绘制
          </el-button>
        </div>
        <div>
          <el-button size="small" type="primary" v-if="!isEditStatus" @click="handleEnd" :disabled="!start">完成绘制
          </el-button>
        </div>
      </div>
    </div>
    <div
      class="xd-baidu__content"
      id="xd-baidu__content"
    ></div>
    <div class="xd-baidu__map-search">
      <el-input placeholder="请输入关键字" v-model="keyword" @input="handleInput"></el-input>
    </div>
    <div class="xd-baidu__map-result" v-if="keyword">
      <div class="xd-baidu__map-result-box" id="xd-baidu__map-result" :class="{overflow : show }"></div>
      <div class="xd-baidu__map-result-btn">
        <el-button
          @click="handleShow"
          type="primary"
          size="mini"
        >{{!show? '收起': '展开' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
  /**
   * @description 百度覆盖物操作,  备注：使用到BMapGLLib，该工具自行下载并引入
   * BMapGLLib工具 库https://github.com/huiyan-fe/BMapGLLib
   * 参考网站如下：
   * https://lbsyun.baidu.com/cms/jsapi/reference/jsapi_webgl_1_0.html#a3b0
   * https://lbsyun.baidu.com/index.php?title=jspopularGL/guide/addOverlay
   * https://lbs.baidu.com/jsdemo.htm#fEditOverlay
   * 需要加载依赖:npm install --save gxd-helper --registry=https://registry.npm.taobao.org
   * 文档：https://www.npmjs.com/package/gxd-helper
   *
   * @property {Array} center 设置中心点坐标 （选填） 默认：[116.404, 39.915]天安门
   * @property {Boolean} cityControl 使用城市选中控件 （选填） 默认：true
   * @property {Boolean} isCityDraw 是否使用城市画覆盖物 （选填） 默认：false
   * @property {Number} level 缩放级别 （选填） 默认：15
   * @property {Boolean} edit 地图编辑状态 （选填） 默认：false
   * @property {Boolean} draw 地图绘画状态 （选填） 默认：false
   * @property {Array} defaultOverlays 覆盖物对象 （选填） 默认：[]
   * @property {Number} isShowEdit 是否可编辑与创建覆盖物 （选填） 默认：true
   * @property {Number|String} drawType 用户指定画图方式,如果指定方式就不可更改画图方式 （选填） 默认不指定: null, 1=>画圆 2=>画多边型
   *
   * @event {Function} onDone 编辑或者创建覆盖物完成事件 参数：overlays(覆盖物对象)， overlaysSource(覆盖物数据)
   */


  export default {
    name: "XdBaiduOverlay",
    props: {
      edit: {
        type: Boolean,
        default: false
      },
      draw: {
        type: Boolean,
        default: false
      },
      center: {
        type: Array,
        default() {
          return [116.404, 39.915]
        }
      },

      drawType: {
        type: Number | String | null,
        default: null, //用户指定画图方式 默认不指定: null, 1=>画圆 2=>画多边型 3=>包含面（镂空面）
      },

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

      isCityDraw: {
        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: '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]
                ]
              ]
            }
          ]
        }
      },

      isShowEdit: {
        type: Boolean,
        default: true
      },
      emptyClear: {
        type: Boolean,
        default: true
      },


    },

    data() {
      return {
        /**
         * @description 百度API对象
         * @var {BMapGL.Map|null}
         */
        map: null, //百度对象
        mapLaoded: false, //地图加载完成
        stroke: {
          strokeColor: '#f00',
          strokeWeight: 2,
          fillColor: 'blue',
          fillOpacity: 0.4,
          strokeOpacity: .8
        },

        typeList: [{name: '画范围', value: 0}, {name: '画区域', value: 1,}],
        btnList: [{name: '开始绘制', value: 0}, {name: '完成绘制', value: 1,}],

        //圆，多边形，锚点，线，城市 绘制
        overlaysArray: [], //当前已确认可绘制覆盖物原始数组
        overlaysObject: [], //当前已绘制覆盖物对象
        overlaysEdit: {}, //当前正在编辑绘制覆盖物的对象
        type: "2", //绘制类型
        start: false, //开始绘制
        startOverlay: {}, //当前绘制对象
        lastIndex: null, //最后操作索引位置
        firstOverlayEvent: null, //画区域时候保存第一个点event事件
        startCircle: null, //画区域时候设置第一个点的圆心
        polygonCircleStroke: {//画区域时候设置第一个点的圆样式
          strokeColor: '#f00',
          strokeOpacity: .8,
          strokeWeight: 2,
          fillColor: '#f00',
          fillOpacity: 0.8,
        },
        startCircleR: 5, //用户画圆半径(公里)
        circleR: 150, //画区域时候设置第一个点的圆心半径
        isEditStatus: false, //是否有编辑模块
        userDrawTypeStatus: false, //是否用户指定画覆盖物状态
        isOverlaysEditStatus: false, //当前正在编辑圆，线，多边形面


        //镂空面
        startOverlayBoundaryIndex: null, //镂空索引
        startOverlayBoundary: [], //记录画镂空面数组
        startBoundaryCircle: null, //第一个点画区域
        startBoundarycircleR: 150, //第一个点画圆心
        overlaysBoundaryObject: [],
        overlaysBoundaryEdit: {},
        isOverlaysBoundaryEditStatus: false, //是否有镂空面编辑(当有镂空面绘制，其他模式不可编辑)
        keyword: '', //搜索关键值
        show: false,
      }
    },
    watch: {
      overlaysEdit(val) {
        console.log('overlaysEdit', val);
        if (this.$xdHelper.isEmpty(val)) {
          this.isEditStatus = false
        } else {
          this.isEditStatus = true;
        }
        this.$emit('update:edit', this.isEditStatus);
      },
      drawType() {
        this.setDrawType();
      },
      start(val) {
        this.$emit('update:draw', val);
      },
      isEditStatus(val) {
        this.$emit('update:edit', val)
      }
    },
    created(){
      if ($xdHelper && typeof $xdHelper.isPC === 'function') {
        if (!$xdHelper.isPC()) this.show = true;
      }
    },
    mounted() {
      this.$nextTick(() => {
        if (typeof BMapGL === "undefined" || typeof BMapGLLib === 'undefined') {
          throw new Error('//api.map.baidu.com/api?type=webgl&v=1.0&ak=您的密钥 and //api.map.baidu.com/getscript?ak=your_ak&services=&t=20181204112130')
        }
        this.setDrawType();
        this.overlaysArray = this.overlaysArray.concat(this.defaultOverlays);
        this.initMap();
        this.$emit('update:edit', this.isEditStatus);
        this.$emit('update:draw', this.start);
      })

    },

    destroyed(){
      this.map.destroy()
      this.map=null
    },

    methods: {
      setDrawType() {
        if (this.drawType !== null) {
          let num = String(this.drawType);
          if (num === '1' || num === '2' || num === '3') {
            this.type = num;
            this.userDrawTypeStatus = true;
          }
        }
      },

      /**
       * @description 初始化地图
       */
      initMap() {
        this.map = new BMapGL.Map('xd-baidu__content');
        this.map.centerAndZoom(new BMapGL.Point(...this.center), this.level);
        this.map.enableScrollWheelZoom();
        this.setCityControl();
        this.map.addControl(new BMapGL.ScaleControl());// 添加比例尺控件
        this.map.addControl(new BMapGL.ZoomControl());// 添加比例尺控件
        this.drawOverlay();
        this.map.addEventListener('tilesloaded', () => {
          this.mapLaoded = true;
        });

        /**
         * @description 绑定地图右键
         */
        this.map.addEventListener('rightclick', () => {
          //画图结束操作
          if (this.start) {
            this.handleEnd();
          }

          //编辑结束操作
          if (this.isEditStatus) {
            this.handleDone();
          }

        });

        /**
         * @description 绑定地图点击事件
         */
        this.map.addEventListener('click', (e) => {
          if (this.start) {

            //画圆
            if (this.type === '1') {
              this.createUserCircle(e);
              return;
            }

            //画镂空面
            if (this.type === '3') {
              this.createUserBoundary(e);
              return;
            }

            //画面
            //判断最后一个点与第一个点是否重合直接生产面
            if (this.checkHit(e)) {
              this.handleEnd();
              return;
            }

            let value = this.startOverlay.value || [];
            value = value.concat([[e['latlng']['lng'], e['latlng']['lat']]]);
            this.$set(this.startOverlay, 'value', value);


            //与地图放大缩小设置放大倍数
            let level = (this.map.getZoom() - 15) < 0 ? 0 : (this.map.getZoom() - 15);
            let zoom = this.map.getZoom() + Math.pow(level, 3);
            if (zoom < 14 && zoom >= 11) zoom = zoom / ((15 - zoom) * 1.2);
            else if (zoom < 11) zoom = zoom / ((15 - zoom) * 1.5);

            //与地图放大缩小设置默认半径
            this.circleR = 150 * this.level / zoom;
            this.map.removeOverlay(this.startCircle);
            this.startCircle = null;
            this.startCircle = new BMapGL.Circle(new BMapGL.Point(...value[0]), this.circleR, this.polygonCircleStroke);

            //大于两个点
            if (value.length > 1) {
              this.$set(this.startOverlay, 'type', 'Polyline');
              this.overlaysArray.splice(this.lastIndex, 1, this.$xdHelper.cloneDeep(this.startOverlay));
              this.clearOverlay();
              this.drawOverlay();
            }
            //第一个点直接追加记录
            else {
              this.overlaysArray.push(this.$xdHelper.cloneDeep(this.startOverlay));
              this.clearOverlay();
              this.drawOverlay();
            }

            //记录第一个点
            if (this.firstOverlayEvent === null) this.firstOverlayEvent = e;
          }
        })

      },


      /**
       * @description 用户画圆
       * @param e {}
       */
      createUserCircle(e) {
        let value = this.startOverlay.value || [];
        value = [[e['latlng']['lng'], e['latlng']['lat']]];
        this.$set(this.startOverlay, 'type', 'Circle');
        this.$set(this.startOverlay, 'value', value);
        this.$set(this.startOverlay, 'r', this.startCircleR * 1000);
        this.$set(this.startOverlay, 'isUser', true);
        this.overlaysArray.splice(this.lastIndex, 1, this.$xdHelper.cloneDeep(this.startOverlay));
        console.log('createUserCircle', this.startOverlay);
        this.clearOverlay();
        this.drawOverlay();
      },


      /**
       * 检查画图第一个点与最后一个点是否重合
       * @param e
       */
      checkHit(e) {
        let temp = false;
        if (this.firstOverlayEvent === null && this.startOverlay.value.length <= 2) return temp;
        let lastPoint = new BMapGL.Point(e.latlng.lng, e.latlng.lat);
        return BMapGLLib.GeoUtils.isPointInCircle(lastPoint, this.startCircle);
      },

      handleDel() {
        this.$confirm('您确定要删除选中的区域, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            let overlaysIndex = [];
            let overlays = [];
            let overlaysArray = this.$xdHelper.cloneDeep(this.overlaysArray);
            Object.keys(this.overlaysEdit).map((index) => {
              overlaysIndex.push(Number(index));
            });
            overlaysArray.map((item, index) => {
              if (!this.$xdHelper.inArray(overlaysIndex, [index])) {
                overlays.push(item);
              }
            });
            this.overlaysArray = this.$xdHelper.cloneDeep(overlays);
            this.clearOverlay();
            this.drawOverlay();
          })
          .catch(() => {
          });
      },

      /**
       * @description 绘制结束
       */
      handleEnd() {
        //绘制镂空面结束判断
        if (this.type === '3') this.handleBoundaryEnd();

        if (this.type === '2' && this.startOverlay['system']) {
          if (this.startOverlay.value.length <= 2) {
            alert('绘制区域面最少需要三个坐标')
            return;
          }
          ;
          this.$set(this.startOverlay, 'type', 'Polygon');
          this.overlaysArray.splice(this.lastIndex, 1, this.$xdHelper.cloneDeep(this.startOverlay));
        }
        this.clearOverlay();
        this.drawOverlay();
        this.start = false;
        this.lastIndex = null;
        this.firstOverlayEvent = null;
        this.startOverlay = {};
        this.startCircle = null;
        this.show = true;
      },


      /**
       * @description 开始绘制
       */
      handleStart() {
        if (this.start) return;
        this.start = true;
        this.handleDone();
        if (this.type === '2') {
          this.$set(this.startOverlay, 'type', 'Circle');
          this.$set(this.startOverlay, 'value', []);
          this.$set(this.startOverlay, 'system', true);

        }
        if (this.type === '1') {
          this.$set(this.startOverlay, 'type', 'Circle');
          this.$set(this.startOverlay, 'value', []);
        }
        if (this.type === '3') {
          this.$set(this.startOverlay, 'type', 'Boundary');
          this.$set(this.startOverlay, 'value', []);

          //设置绘制面索引
          if (this.startOverlayBoundaryIndex === null) {
            this.startOverlayBoundaryIndex = 0;
          }
        }

        this.lastIndex = this.overlaysArray.length;
      },

      /**
       * @description 设置城市区域画面
       * @param  e
       */
      setCityOverlay(e) {
        this.overlaysArray.push({type: 'city', value: e['city']});
        this.clearOverlay();
        this.drawOverlay();
        this.start = false;
        this.lastIndex = null;
        this.firstOverlayEvent = null;
        this.startOverlay = {};
        this.startCircle = null;

      },

      /**
       * @description 画图结束事件
       */
      handleDone() {
        //当前完成正在编辑的事件
        Object.keys(this.overlaysEdit).map((index) => {

          //标记无编辑模式
          if (this.overlaysEdit[index].type !== 'Marker') {
            this.overlaysEdit[index]['isEdit'] = false;
            this.overlaysObject[index].disableEditing();
          }

          //重置绘制覆盖物原始数组
          if (this.overlaysEdit[index].type !== 'city') {
            let temp = this.$xdHelper.cloneDeep(this.overlaysEdit[index]);
            let value = [];
            this.overlaysObject[index].getPath().map(item => {
              value.push([item.lng, item.lat]);
            });
            temp.value = value;
            this.overlaysArray.splice(index, 1, temp);
          }

          //编辑圆重置半径
          if (this.overlaysEdit[index].type === 'Circle') {
            let temp = this.$xdHelper.cloneDeep(this.overlaysEdit[index]);
            temp.r = this.overlaysObject[index].radius;
            this.overlaysArray.splice(index, 1, temp);
          }

          this.$emit('onDone', {overlays: this.overlaysObject, overlaysSource: this.overlaysArray});
        });
        this.overlaysEdit = {};
        this.isOverlaysEditStatus = false;
      },

      /**
       * @description 初始化城市选择控件
       */
      setCityControl() {
        if (this.cityControl) {
          let addControl = new BMapGL['CityListControl']({
            anchor: BMAP_ANCHOR_TOP_LEFT,
            offset: new BMapGL.Size(10, 5),
            onChangeSuccess: (e) => {
              console.log('onChangeSuccess', e)
              if (this.start && this.isCityDraw) {
                this.setCityOverlay(e);
              }
            }
          });
          this.map.addControl(addControl);
        }
      },

      /**
       * @description 点击覆盖物事件
       * @param e 事件
       * @param item 覆盖物对象原始数据
       * @param overlay {BMapGL.Polygon} 覆盖物对象
       * @param index 覆盖物对象索引位置
       */
      handleClickOverlay(e, item, overlay, index) {
        //编辑圆，线，多边形面 与 镂空面只能存在一种编辑
        if (!item.isEdit) {

          //镂空面编辑
          if (item.type === 'Boundary') {

            //正在编辑圆，线，多边形面
            if (this.isOverlaysEditStatus) {
              this.$message({
                message: '当前正在编辑画距离，画线，画地图操作'
              });
              return;
            }

            console.log(e, item, overlay, index);
            this.isOverlaysBoundaryEditStatus = true;
          }

          //编辑圆，线，多边形
          else {

            //正在编辑镂空面
            if (this.isOverlaysBoundaryEditStatus) {
              this.$message({
                message: '当前正在编辑包含地图操作'
              });
              return;
            }

            if (item.type !== 'Marker' && item.type !== 'city') {
              overlay.enableEditing();
              item['isEdit'] = true;
              this.$set(this.overlaysEdit, index, item);
              this.isOverlaysEditStatus = true;
            }

          }
        }
      },

      /**
       * @description 覆盖物绑定事件
       * @param item 覆盖物对象原始数据
       * @param overlay {BMapGL.Polygon|BMapGL.Circle|BMapGL.Polyline} 覆盖物对象
       * @param index 覆盖物对象索引位置
       */
      bindOverlayEvent(item, overlay, index) {
        if (overlay) {
          item['isEdit'] = false;
          overlay.addEventListener('click', (e) => {
            if (!this.start) {
              this.handleClickOverlay(e, item, overlay, index);
            }
          });
          overlay.addEventListener('mouseover', (e) => {
            if (!this.start) {
              overlay.setFillOpacity(.2)
            }
          });
          overlay.addEventListener('mouseout', (e) => {
            if (!this.start) {
              overlay.setFillOpacity(.4)
            }
          });

        }
      },

      /**
       * @description 创建覆盖物对象
       * @param item 覆盖物对象原始数据
       * @param index 覆盖物对象索引位置
       */
      handleCreateOverlay(item, index) {
        return new Promise((resolve, reject) => {
          let overlay = null;

          //画城市
          if (item.type === 'city') {
            let bd = new BMapGL.Boundary();

            /**
             * @var rs {BMapGL.Boundary}
             */
            bd.get(item.value, (rs) => {
              let overlay = new BMapGL.Polygon(rs['boundaries'], this.$xdHelper.cloneDeep(this.stroke));
              this.bindOverlayEvent(item, overlay, index);
              resolve(overlay)
            });

          }

          //画镂空面
          else if (item.type === 'Boundary') {
            let bounds = [];
            item.value.map((tempArr) => {
              let temp = [];
              tempArr.map((arr) => {
                temp.push(new BMapGL.Point(...arr))
              });
              bounds.push(temp)
            });
            let overlay = new BMapGL.Polygon(bounds, this.$xdHelper.cloneDeep(this.stroke));
            this.bindOverlayEvent(item, overlay, index);
            overlay.enableEditing();
            resolve(overlay)
          }

          //画圆
          else if (item.type === 'Circle') {
            let stroke = null, circleR = null;
            //画面时候首点使用画圆
            if (this.start && this.type === '2' && item['system']) {
              stroke = this.polygonCircleStroke;
              circleR = this.circleR;
            } else {
              stroke = this.stroke;
              circleR = item.r || Number(this.startCircleR) * 1000;
            }
            overlay = new BMapGL.Circle(new BMapGL.Point(...item.value[0]), circleR, stroke);
            this.bindOverlayEvent(item, overlay, index);
            resolve(overlay)
          }

          //画线，画面
          else {
            console.log(item['type'], item.value);
            if (item['type'] === 'Marker') {
              overlay = new BMapGL[item['type']](new BMapGL.Point(...item.value[0]));
            } else {
              let point = [];
              item.value.map(itm => {
                point.push(new BMapGL.Point(...itm))
              });
              overlay = new BMapGL[item['type']](point, this.$xdHelper.cloneDeep(this.stroke));
            }

            this.bindOverlayEvent(item, overlay, index);
            resolve(overlay)
          }
        })
      },

      /**
       * @description 绘制事件（圆心与面绘制）
       */
      drawOverlay() {
        let promiseArr = [];
        this.overlaysArray.map((item, index) => {
          promiseArr.push(this.handleCreateOverlay(item, index));
        });

        Promise.all(promiseArr)
          .then(res => {
            console.log(res);
            this.overlaysObject = res;
            this.overlaysObject.map((item) => {
              this.map.addOverlay(item)
            });

            //画面时候
            if (this.start && this.startCircle !== null && this.type === '2') {
              this.map.addOverlay(this.startCircle)
            }

            //画圆
            if (this.start && this.type === '1') {
              let radius = 150 * this.level / this.map.getZoom();
              let crcle = new BMapGL.Circle(new BMapGL.Point(...this.startOverlay.value[0]), radius, this.polygonCircleStroke)
              this.map.addOverlay(crcle)
            }
            this.$emit('onDone', {overlays: this.overlaysObject, overlaysSource: this.overlaysArray});
          })
          .catch();
      },

      /**
       * @description 清空绘制（圆心与面绘制清除）
       */
      clearOverlay() {
        this.overlaysObject = [];
        this.overlaysEdit = {};
        this.map.clearOverlays()
      },

      /**镂空面绘制********************/
      handleBoundaryEnd() {
        let value = [];
        this.startOverlayBoundary.map((item) => {
          value.push(item.value)
        });

        this.overlaysArray.push({
          type: 'Boundary',
          value: value
        });

        this.overlaysBoundaryObject.map((item) => {
          this.map.removeOverlay(item);
        });
        this.startOverlayBoundaryIndex = null;
        this.overlaysBoundaryObject = [];
        this.startOverlayBoundary = [];
        this.startBoundaryCircle = null;
      },

      hiteBoundary(e) {
        let temp = false;
        if (!this.startOverlayBoundary[this.startOverlayBoundaryIndex]
          || this.startOverlayBoundary[this.startOverlayBoundaryIndex].value.length <= 2
        ) return temp;
        let lastPoint = new BMapGL.Point(e.latlng.lng, e.latlng.lat);
        return BMapGLLib.GeoUtils.isPointInCircle(lastPoint, this.startBoundaryCircle);
      },

      boundaryOneDrawDone() {
        this.map.removeOverlay(this.startBoundaryCircle);
        this.startBoundaryCircle = null;
        let item = this.$xdHelper.cloneDeep(this.startOverlayBoundary[this.startOverlayBoundaryIndex]);
        item['type'] = 'Polygon';
        this.$set(this.startOverlayBoundary, this.startOverlayBoundaryIndex, item);
        this.startOverlayBoundaryIndex++;
        this.drawBoundaryOverlay();
      },

      /**
       * @description 用户画镂空面
       */
      createUserBoundary(e) {
        //判断最后一个点与第一个点是否重合直接生产面
        if (this.hiteBoundary(e)) {
          this.boundaryOneDrawDone();
          return;
        }

        //设置绘制点
        let item = this.$xdHelper.cloneDeep(this.startOverlayBoundary[this.startOverlayBoundaryIndex] || {});
        if (this.$xdHelper.isEmpty(item)) {
          item['type'] = 'Polyline';
          item['value'] = [[e['latlng']['lng'], e['latlng']['lat']]];
        } else {
          item['value'] = item['value'].concat([[e['latlng']['lng'], e['latlng']['lat']]])
        }
        this.$set(this.startOverlayBoundary, this.startOverlayBoundaryIndex, item);

        // //与地图放大缩小设置放大倍数
        let level = (this.map.getZoom() - 15) < 0 ? 0 : (this.map.getZoom() - 15);
        let zoom = this.map.getZoom() + Math.pow(level, 3);
        if (zoom < 14 && zoom >= 11) zoom = zoom / ((15 - zoom) * 1.2);
        else if (zoom < 11) zoom = zoom / ((15 - zoom) * 1.5);

        //与地图放大缩小设置默认半径
        this.startBoundarycircleR = 150 * this.level / zoom;
        this.map.removeOverlay(this.startBoundaryCircle);
        this.startBoundaryCircle = null;
        this.startBoundaryCircle = new BMapGL.Circle(
          new BMapGL.Point(...this.startOverlayBoundary[this.startOverlayBoundaryIndex]['value'][0]),
          this.startBoundarycircleR,
          this.polygonCircleStroke
        );
        this.drawBoundaryOverlay();
      },

      /***
       * @description 绘制镂空面
       */
      drawBoundaryOverlay() {
        let promiseArr = [];
        this.startOverlayBoundary.map((item, index) => {
          promiseArr.push(this.handleCreateOverlay(item, index));
        });

        //画第二个面的时候，需要去掉已绘制的面
        if (this.overlaysBoundaryObject.length > 0) {
          this.overlaysBoundaryObject.map((item) => {
            this.map.removeOverlay(item);
          })
        }

        Promise.all(promiseArr)
          .then(res => {
            this.overlaysBoundaryObject = res;
            this.overlaysBoundaryObject.map((item) => {
              this.map.addOverlay(item)
            });

            //画面时候
            if (this.start && this.startBoundaryCircle !== null) {
              this.map.addOverlay(this.startBoundaryCircle)
            }
          })
          .catch();
      },
      /**抛出半径**/
      circleChangeR() {
        this.$emit('circleRadius', this.startCircleR);
      },

      /**镂空面绘制********************/
      handleInput() {
        if (this.timeer) clearTimeout(this.timeer);
        this.timeer = setTimeout(() => {
          this.handleSearch(this.keyword)
        }, 600)
      },

      handleShow() {
        this.show = !this.show;
      },
      handleSelect(result) {
        let uiCenter = [result['point']['lng'], result['point']['lat']];
        this.map.centerAndZoom(new BMapGL.Point(...uiCenter), 15);
      },
      handleSearch(value) {
        if (value === ''&&this.emptyClear) {
          this.map.clearOverlays();
        }

        let local = new BMapGL.LocalSearch(this.map, {
          renderOptions: {
            map: this.map,
            panel: "xd-baidu__map-result",
            selectFirstResult: false,
          },
          pageCapacity: Math.floor((this.height - 180) / 50), //动态获取每页显示条数
          onInfoHtmlSet: (result) => {
            console.log('result', result);
            if (this.isFirst) this.handleSelect(result);
            else {
              this.$emit('onSelect', {
                address: this.defaultValue,
                longitude: this.uiCenter[0],
                latitude: this.uiCenter[1],
                sourceData: null
              })
            }
            if (!this.isFirst) this.isFirst = true;
          },

          onSearchComplete: (result) => {
            let select = null;
            //查找地址是否有相同，没有相同返回第一条
            if (result&&result['_pois']) {
              result['_pois'].map((item, index) => {
                if (index === 0) {
                  select = item
                  this.initIndex = index;
                } else {
                  if (value === item.address) {
                    select = item;
                    this.initIndex = index;
                  }
                }
              })
            }
          },

          onResultsHtmlSet: (result) => {
            let li = result.getElementsByTagName('li');
            this.isFirst = true;
            li[this.initIndex]['click']();

          }
        });
        local.search(value);
      },
    },

  }
</script>

<style scoped lang="scss">
  .xd-baidu {
    min-width: 600px;
    overflow-x: auto;

    &__content {
      width: 100%;
      min-width: 600px;
      min-height: 600px;
      overflow: hidden;
      margin: 0;
      font-family: "微软雅黑";
    }

    &__btn {
      display: flex;
      justify-content: space-between;
      align-items: center;

      & > div {
        flex: 1;
      }

      &-left {
        padding: 10px 0;
        display: flex;
        justify-content: flex-start;
        align-items: center;

        & > div:first-child {
          font-weight: bold;
        }

        & > *:nth-child(2) {
          padding-top: 2px;
        }

        & > * {
          flex-shrink: 0;

          &:nth-child(3) {
            margin-left: 20px;
            width: 200px;
            display: flex;
            justify-content: flex-start;
            align-items: center;

            & > span {
              flex-shrink: 0;
              font-weight: bold;
            }

            & > *:last-child {
              flex: 1;
            }
          }
        }
      }

      &-right {
        padding: 10px 0;
        display: flex;
        justify-content: flex-end;
        align-items: center;


        & > div {
          margin-left: 10px;
        }

      }
    }
  }

  .xd-baidu__map {
    border: 1px solid #333;
    height: 100%;

    &-search {
      width: 30%;
      background: #fff;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
      padding: 5px;
      border-radius: 5px;
      position: absolute;
      left: 100px;
      top: 60px;
      z-index: 10;
    }

    &-result {
      width: 30%;
      min-width: 300px;
      background: #fff;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
      padding: 5px;
      border-radius: 5px;
      position: absolute;
      left: 100px;
      top: 106px;
      z-index: 10;


      &-box {
        &.overflow {
          & > div {
            overflow-y: auto;
            overflow-x: hidden;
            height: 100px;
          }
        }
      }

      &-btn {
        padding: 10px 0 0;
        text-align: right;
      }
    }
  }

  .overflow {
      overflow-y: auto;
      overflow-x: hidden;
      height: 100px;
  }
</style>
