<template>
  <div class="el-gd-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.name }}
        </div>
      </div>
      <!-- <div class="search-result" v-if="showSearch && searchList.length === 0">
        没有数据
      </div> -->
    </div>
    <div id="js-container" class="map"></div>
  </div>
  </div>
</template>


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

export default {
  name: 'cc-gd-map',
  props: {
    mapkey: {
      type: String
    },
    zoom: {
      type: Number,
      default: 13
    },
    showSearchBar: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      mapError: false,
      showSearch: false, // 展示搜索信息
      searchKey: '', // 搜索关键字
      searchList: [], // 搜索结果列表
      mapObject: null, // 地图对象
      geocoder: null, // 地图定位解析
      maker: null, // 地图标记
      addrStr: {
        center: '',
        point: ''
      },
      infomation: '' // 展示信息
    };
  },
  watch: {
    zoom() {
      this.mapObject.setZoom(this.zoom);
    },
    searchKey() {
      this.handleSearch();
    }
  },
  methods: {
    // 输入框失去焦点
    handlebulr() {
      if (this.searchKey.length === 0) {
        this.showSearch = false;
      } else {
      }
    },
    // 选择位置后，跳转至定位点
    chooseLocation(item) {
      // console.log(item);
      this.infomation = {
        name: item.name,
        district: item.district,
        address: item.address,
        lng: item.location.lng,
        lat: item.location.lat
      };
      this.$emit('chooseLocation', this.infomation);
      // 设置缩放级别和中心点
      this.mapObject.setZoomAndCenter(14, [
        item.location.lng,
        item.location.lat
      ]);
      // 在新中心点添加 marker
      /* eslint-disable no-undef */
      this.marker = new AMap.Marker({
        map: this.mapObject,
        position: [item.location.lng, item.location.lat]
      });
      this.showSearch = false;
    },
    // 根据关键字搜索位置列表
    handleSearch() {
      var keywords = this.searchKey;
      let that = this;
      this.mapObject.plugin('AMap.Autocomplete', function() {
        // 实例化Autocomplete
        var autoOptions = {
          // city 限定城市，默认全国
          city: '全国'
        };
        /* eslint-disable no-undef */
        var autoComplete = new AMap.Autocomplete(autoOptions);
        autoComplete.search(keywords, function(status, result) {
          // console.log(status, result);
          // 搜索成功时，result即是对应的匹配数据
          if (result.info === 'OK') {
            that.searchList = result.tips;
            that.showSearch = true;
          }
        });
      });
    },
    // 实例化地图
    initMap() {
      let that = this;
      /* eslint-disable no-undef */
      that.mapObject = new AMap.Map('js-container', {
        resizeEnable: true,
        zoom: this.zoom
      });
      // 地址与坐标转换
      /* eslint-disable no-undef */
      that.geocoder = new AMap.Geocoder({
        city: '010', // 城市设为北京，默认：“全国”
        radius: 1000 // 范围，默认：500
      });
      /* eslint-disable no-undef */
      that.marker = new AMap.Marker();

      that.mapObject.on('complete', () => {
        let center = this.mapObject.getCenter();
        let point = [center.getLng(), center.getLat()];
        that.getAddressCode('moveend', point);
      });
      // 点击事件
      that.mapObject.on('click', (e) => {
        let point = [e.lnglat.getLng(), e.lnglat.getLat()];
        that.getAddressCode('click', point);
      });
      // 地图移动
      that.mapObject.on('moveend', () => {
        let object = {
          lng: that.mapObject.getCenter().getLng(),
          lat: that.mapObject.getCenter().getLat()
        };
        let point = [object.lng, object.lat];
        that.getAddressCode('moveend', point);
      });
      // 地图缩放
      that.mapObject.on('zoomchange', () => {
        // console.log(that.mapObject.getZoom()); // 获取当前地图级别
        this.$emit('changeZoom', that.mapObject.getZoom());
      });
    },
    getAddressCode(type, lnglat) {
      let that = this;
      let addrStr;
      this.geocoder.getAddress(lnglat, function(status, result) {
        if (status === 'complete' && result.regeocode) {
          addrStr = result.regeocode.formattedAddress;
        } else {
          addrStr = '高德地图不能正常运行，请检查秘钥是否正确！';
        }
        switch (type) {
          case 'click':
            that.mapObject.add(that.marker);
            that.marker.setPosition(lnglat);
            let lnglatObj = {
              lng: lnglat[0],
              lat: lnglat[1]
            };
            that.$emit('updatePoint', addrStr, lnglatObj);
            break;
          case 'moveend':
            let object = {
              lng: lnglat[0],
              lat: lnglat[1]
            };
            that.$emit('updateCenter', addrStr, object);
            break;
        }
      });
    }
  },
  mounted() {
    let key = this.mapkey;
    let that = this;
    if (key.length === 0) {
      that.mapError = true;
    } else {
      MapLoader(key, 'Amap').then(
        (AMap) => {
          console.log('gd地图加载成功', AMap);
          that.initMap();
        },
        (e) => {
          console.log('地图加载失败', e);
        }
      );
    }
  },
  created() {}
};
</script>


