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

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

export default {
  name: 'cc-gg-map',
  props: {
    mapkey: {
      type: String
    },
    zoom: {
      type: Number,
      default: 13
    },
    showSearchBar: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    zoom() {
      this.mapObject.setZoom(this.zoom);
    },
    searchKey() {
      if (this.searchKey.length === 0) {
        this.showSearch = false;
        return false;
      } else {
        this.handleSearch();
      }
    }
  },
  data() {
    return {
      mapError: false,
      showSearch: false, // 展示搜索信息
      searchKey: '', // 搜索关键字
      searchList: [], // 搜索结果列表
      mapObject: null,
      geocoder: null,
      marker: null,
      infomation: {}
    };
  },
  methods: {
    // 输入框失去焦点
    handlebulr() {
      if (this.searchKey.length === 0) {
        this.showSearch = false;
      } else {
      }
    },
    // 选择位置后，跳转至定位点
    chooseLocation(item) {
      // console.log(item);
      this.infomation = {
        name: item.name || this.searchKey,
        district: item.district,
        address: item.formatted_address,
        lng: item.geometry.location.toJSON().lng,
        lat: item.geometry.location.toJSON().lat
      };
      this.$emit('chooseLocation', this.infomation);
      this.showSearch = false;
      this.$emit('changeZoom', 14);
      this.mapObject.setCenter(item.geometry.location);
      this.postCenterInfo(item.geometry.location);
      this.marker.setPosition(item.geometry.location);
    },
    // 根据关键字搜索位置列表
    handleSearch() {
      var addr = this.searchKey;
      let that = this;
      that.geocoder
        .geocode({ address: addr })
        .then((result) => {
          const { results } = result;
          that.searchList = results;
          that.showSearch = true;
        })
        .catch((e) => {
          console.log(
            'Geocode was not successful for the following reason: ' + e
          );
        });
    },
    createMap() {
      let that = this;
      /* eslint-disable no-undef */
      that.mapObject = new google.maps.Map(
        document.getElementById('gg-container'),
        {
          center: { lng: 116.404, lat: 39.915 },
          zoom: that.zoom,
          // scrollwheel: false, // 滚轮
          disableDefaultUI: true // 禁用默认ui
        }
      );
      /* eslint-disable no-undef */
      that.geocoder = new google.maps.Geocoder();
      that.postCenterInfo(that.mapObject.center);
      // 地图缩放
      that.mapObject.addListener('zoom_changed', () => {
        // console.log('缩放后后的中心点经纬度', that.mapObject.center.toJSON());
        that.postCenterInfo(that.mapObject.center);
        that.$emit('changeZoom', that.mapObject.getZoom());
      });
      /* eslint-disable no-undef */
      that.marker = new google.maps.Marker({
        position: that.mapObject.center,
        map: that.mapObject,
        title: 'Click to zoom'
      });
      that.mapObject.addListener('click', (mapsMouseEvent) => {
        // console.log('点击位置的经纬度', mapsMouseEvent.latLng.toJSON());
        addMarker(mapsMouseEvent.latLng, that.mapObject);
      });
      function addMarker(latLng, map) {
        that.marker.setPosition(latLng);
        that.postPointInfo(latLng);
      }
      that.mapObject.addListener('dragend', () => {
        // console.log('拖拽后后的中心点经纬度', that.mapObject.center.toJSON());
        that.postCenterInfo(that.mapObject.center);
      });
      that.mapObject.addListener('center_changed', () => {});
      // 标记点击事件
      that.marker.addListener('click', () => {
        that.mapObject.setZoom(16);
        that.mapObject.setCenter(that.marker.getPosition());
        that.postCenterInfo(that.marker.getPosition());
      });
    },
    postPointInfo(latLng) {
      let that = this;
      let addr = '';
      that.geocoder
        .geocode({ location: latLng })
        .then((response) => {
          if (response.results[0]) {
            // console.log(response.results[0]);
            addr = response.results[0].formatted_address;
          } else {
            addr = 'No results found';
          }
          this.$emit('updatePoint', addr, latLng.toJSON());
        })
        .catch((e) => {
          addr = 'Geocoder failed due to: ' + e;
          this.$emit('updatePoint', addr, latLng.toJSON());
        });
    },
    postCenterInfo(latLng) {
      let that = this;
      let addr = '';
      that.geocoder
        .geocode({ location: latLng })
        .then((response) => {
          if (response.results[0]) {
            // console.log(response.results[0]);
            addr = response.results[0].formatted_address;
          } else {
            addr = 'No results found';
          }
          this.$emit('updateCenter', addr, latLng.toJSON());
        })
        .catch((e) => {
          addr = 'Geocoder failed due to: ' + e;
          this.$emit('updateCenter', addr, latLng.toJSON());
        });
    }
  },
  mounted() {
    let key = this.mapkey;
    let that = this;
    if (key.length === 0) {
      that.mapError = true;
    } else {
      MapLoader(key, 'Gmap').then(
        (map) => {
          console.log('地图加载成功', map);
          that.createMap();
        },
        (e) => {
          console.log('地图加载失败', e);
        }
      );
    }
  }
};
</script>


