<template>
<div class="el-bd-map">
  <div class="map-box">
    <div v-show="mapError">
      百度地图不能正常运行，请检查秘钥是否正确！
    </div>
    <div class="search" v-if="showSearchBar">
      <input
        type="text"
        placeholder="请输入关键字"
        v-model="searchKey"
        @blur="handlebulr"
      />
      <button type="button" @click="handleSearch">搜索</button>
      <div class="search-result" v-if="showSearch && searchList.length > 0">
        <div
          v-for="(item, index) in searchList"
          :key="index"
          class="search-result-item"
          @click="chooseLocation(item)"
        >
          {{ item.title }}
        </div>
      </div>
      <!-- <div class="search-result" v-if="showSearch && searchList.length === 0">
        没有数据
      </div> -->
    </div>
    <div id="bd-container" class="map"></div>
  </div>
</div>
</template>

<script>
import MapLoader from './loadMapFn';

export default {
  name: 'cc-bd-map',
  props: {
    mapkey: {
      type: String
    },
    zoom: {
      type: Number,
      default: 13
    },
    showSearchBar: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    zoom() {
      this.mapObject.setZoom(this.zoom);
    },
    searchKey() {
      this.handleSearch();
    }
  },
  data() {
    return {
      mapError: false,
      showSearch: false, // 展示搜索信息
      searchKey: '', // 搜索关键字
      searchList: [], // 搜索结果列表
      mapObject: null,
      marker: null,
      geocoder: null
    };
  },
  methods: {
    // 输入框失去焦点
    handlebulr() {
      if (this.searchKey.length === 0) {
        this.showSearch = false;
      } else {
      }
    },
    // 选择位置后，跳转至定位点
    chooseLocation(item) {
      // console.log(item);
      let that = this;
      this.infomation = {
        name: item.title,
        district: '',
        address: item.address,
        lng: item.point.lng,
        lat: item.point.lat
      };
      this.$emit('chooseLocation', this.infomation);
      // 设置缩放级别和中心点
      /* eslint-disable no-undef */
      that.mapObject.centerAndZoom(new BMap.Point(item.point.lng, item.point.lat), 14);
      // 在新中心点添加 marker
      var marker = new BMap.Marker(item.point); // 创建标注
      that.mapObject.clearOverlays();
      that.mapObject.addOverlay(marker);
      this.showSearch = false;
    },
    // 根据关键字搜索位置列表
    handleSearch() {
      var keywords = this.searchKey;
      let that = this;
      /* eslint-disable no-undef */
      var options = {
        onSearchComplete: function(results) {
          // 判断状态是否正确
          if (local.getStatus() === BMAP_STATUS_SUCCESS) {
            var arr = [];
            for (var i = 0; i < results.getCurrentNumPois(); i++) {
              arr.push(results.getPoi(i));
            }
            // console.log(arr);
            that.searchList = arr;
            that.showSearch = true;
          }
        }
      };
      var local = new BMap.LocalSearch(that.mapObject, options);
      local.search(keywords);
    },
    createMap() {
      let that = this;
      // 创建Map实例
      /* eslint-disable no-undef */
      that.mapObject = new BMap.Map('bd-container', { enableMapClick: false });
      that.mapObject.disableBizAuthLogo();
      // 初始化地图,设置中心点坐标和地图级别
      /* eslint-disable no-undef */
      that.mapObject.centerAndZoom(new BMap.Point(116.404, 39.915), that.zoom);
      // 添加地图类型控件
      //   that.mapObject .addControl(new BMap.MapTypeControl({
      //     mapTypes:[BMAP_NORMAL_MAP, BMAP_HYBRID_MAP]
      //   }))
      // 设置地图显示的城市 此项是必须设置的
      that.mapObject.setCurrentCity('北京');
      // 开启鼠标滚轮缩放
      that.mapObject.enableScrollWheelZoom(true);
      that.mapObject.addEventListener('zoomend', function() {
        that.$emit('changeZoom', that.mapObject.getZoom());
        var center = that.mapObject.getCenter();
        that.getAddressCode('dragend', center);
      });
      // 地图拖拽事件
      that.mapObject.addEventListener('dragend', function() {
        var center = that.mapObject.getCenter();
        that.getAddressCode('dragend', center);
      });
      // 定义解析
      that.geocoder = new BMap.Geocoder({ extensions_town: true });
      var center = that.mapObject.getCenter();
      that.getAddressCode('dragend', center);
      //   点击事件
      that.mapObject.addEventListener('click', function(e) {
        var marker = new BMap.Marker(e.point); // 创建标注
        that.mapObject.clearOverlays();
        that.mapObject.addOverlay(marker); // 将标注添加到地图中
        that.getAddressCode('click', e.point);
      });
      // 创建定位控件
      /* eslint-disable no-undef */
      var locationControl = new BMap.GeolocationControl({
        // 控件的停靠位置（可选，默认左上角）
        anchor: BMAP_ANCHOR_BOTTOM_LEFT,
        // 控件基于停靠位置的偏移量（可选）
        offset: new BMap.Size(20, 20)
      });
      // 将控件添加到地图上
      that.mapObject.addControl(locationControl);

      // 添加定位事件
      locationControl.addEventListener('locationSuccess', function(e) {
        var address = '';
        address += e.addressComponent.province;
        address += e.addressComponent.city;
        address += e.addressComponent.district;
        address += e.addressComponent.street;
        address += e.addressComponent.streetNumber;
        alert('当前定位地址为：' + address);
      });
      locationControl.addEventListener('locationError', function(e) {
        alert(e.message);
      });
    },
    getAddressCode(type, lnglat) {
      let that = this;
      let addrStr;
      that.geocoder.getLocation(lnglat, function(rs) {
        var addComp = rs.addressComponents;
        addrStr =
          addComp.province +
          ', ' +
          addComp.city +
          ', ' +
          addComp.district +
          ', ' +
          addComp.street +
          ', ' +
          addComp.streetNumber;
        if (type === 'click') {
          that.$emit('updatePoint', addrStr, lnglat);
        } else if (type === 'dragend') {
          that.$emit('updateCenter', addrStr, lnglat);
        }
      });
    }
  },
  mounted() {
    let key = this.mapkey;
    let that = this;
    if (key.length === 0) {
      that.mapError = true;
    } else {
      MapLoader(key, 'Bmap').then(
        (BMap) => {
          console.log('地图加载成功', BMap);
          that.createMap();
        },
        (e) => {
          console.log('地图加载失败', e);
        }
      );
    }
  }
};
</script>
