<template>
  <div class="xd-baidu" v-if="defaultValue !== null || uiCenter.length === 2">
    <div class="xd-baidu__tips" v-if="showInfo && keyword">
      <div>位置：</div>
      <div>{{address}} </div>
      <div v-if="uiCenter && uiCenter.length === 2">({{uiCenter|centerFilter}})</div>
    </div>
    <div :style="{height: height + 'px'}" class="xd-baidu__box">
      <div id="xd-baidu__map" class="xd-baidu__map"></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>
  </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.84395113992449, 39.96233347062578]天安门
   * @property {String | null} defaultValue 设置查询值 （选填） 默认：null 例如: 味多美(燕高路店)@河北省三河市学院大街与燕高路交叉口
   * @property {Number} height 设置地图显示高度 （选填） 默认：500  单位：px
   * @property {Number} level 缩放级别 （选填） 默认：15
   *
   * @event {Function} onSelect 选择地址
   * 参数：{address: '', longitude: this.uiCenter[0], latitude: this.uiCenter[1], sourceData: null}
   */


  export default {
    name: "XdBaiduSearch",
    props:{
      showInfo:{
        type:Boolean,
        default: true
      },
      cityName: {
        type:String,
        default: ''
      },
      isBackOne:{
        type:Boolean,
        default: true
      },
      defaultValue: {
        type: String | null,
        default: null //keyword@address //味多美(燕高路店)@河北省三河市学院大街与燕高路交叉口
      },
      height: {
        type: Number,
        default: 500
      },
      center: {
        type:Array,
        default(){
          return []
        }
      },
      level: {
        type: Number,
        default: 15
      },
    },

    filters:{
      centerFilter(center){
        console.log(center);
        if(center && center.length === 2) {
          return center.join(',')
        }
        return ''
      },
    },
    watch: {
      'keyword'(n,o){
        this.handleInput()
      },
      cityName(){
        this.handleInput()
      },
    },

    data(){
      return {
        map: null,
        search : null,
        keyword: '', //搜索关键值
        address: '', //定位地址
        uiCenter: null, //定位经纬度
        show: false,
        isFirst: false,
        timer: null,
        initIndex: -1
      }
    },

    created(){
      if(this.defaultValue !== null) {
        let str = this.defaultValue.split('@');
        this.keyword = str[0];
        this.address = str[1]||'';
      }
      if(this.center.length === 2) {
        this.uiCenter = this.center
      }
      else {
        this.uiCenter = [116.41338729034514, 39.910923647957596]
      }

      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')
        }
        if(this.defaultValue !== null || this.uiCenter.length === 2) {
          this.initMap();
        }
      })
    },

    methods: {
      initMap(){
        this.map = new BMapGL.Map('xd-baidu__map');
        this.map.centerAndZoom(new BMapGL.Point(...this.uiCenter), this.level);
        this.map.enableScrollWheelZoom();
        this.map.addControl(new BMapGL.ScaleControl());// 添加比例尺控件
        this.map.addControl(new BMapGL.ZoomControl());// 添加比例尺控件

        //初始化显示
        if(this.keyword) this.handleSearch(this.keyword);

        //只有经纬度么有地址
        else {
          if(this.uiCenter.length === 2){
            this.addMarker()
          }
        }
      },

      handleShow(){
        this.show = !this.show;
      },

      /**
       * @description 添加编辑点
       */
      addMarker(){
        let point = new BMapGL.Point(...this.uiCenter);
        let myGeo = new BMapGL.Geocoder();
        let marker = new BMapGL.Marker(point);
        this.map.addOverlay(marker);

        myGeo.getLocation(point, (rs)=> {
          marker.setLabel(new BMapGL.Label(rs.address, {offset: new BMapGL.Size(15, -20)}));
          this.address = rs.address;
          this.$emit('onSelect', {
            address: '',
            longitude: this.uiCenter[0],
            latitude: this.uiCenter[1],
            sourceData: null
          })
        });
      },

      handleInput(){
        if(this.timer) clearTimeout(this.timer);
        this.timer = setTimeout(()=>{
          this.handleSearch(`${this.cityName}${this.keyword}`)
        }, 800)
      },

      handleSelect(result){
        this.uiCenter = [result['point']['lng'], result['point']['lat']];
        this.address = result['address'];
        this.$emit('onSelect', {
          address: `${this.keyword.trim()}@${this.address}`,
          longitude: result['point']['lng'],
          latitude: result['point']['lat'],
          sourceData: result,
        })
      },

      handleSearch(value){
        if(value === '') {
          this.map.clearOverlays();
          return
        }

        //搜索关键词
        this.initIndex = -1;
        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)=>{
            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) => {
            //查找地址是否有相同，没有相同返回第一条
            if (result && result['_pois'] &&  result['_pois'].length > 0) {
              result['_pois'].map((item, index) => {
                //是否设置返回第一条
                if(this.isBackOne) {
                  if (index === 0) {
                    this.initIndex = index;
                  }
                }

                //返回地址相同的数据
                if (this.address.trim() === item.address) {
                  this.initIndex = index;
                }
              });
            }
          },

          onResultsHtmlSet: (result)=>{
            if(this.initIndex >= 0) {
              let li = result.getElementsByTagName('li');
              this.isFirst = true;
              li[this.initIndex]['click']();
            }
          }
        });
        local.search(value.trim());
      },
    },
  }
</script>

<style lang="scss">
  .xd-baidu {
    &__tips {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      line-height: 20px;
      flex-wrap: wrap;
      padding-bottom: 10px;
      font-size: 14px;

      & > div:nth-child(2) {
        color: #666;
      }

      & > div:last-child {
        color: #c00;
      }
    }

    &__box {
      position: relative;
    }

    &__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:10px;
        top: 10px;
        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: 10px;
        top: 60px;
        z-index: 10;


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

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

  @media screen and (max-width: 768px) {
    .xd-baidu {
      &__map {
        &-search {
          width: 90%;
        }
        &-result {
          width: 90%;
          min-width: 50%;
        }
      }
    }
  }
</style>
