/**
* Description: 自定义高德地图
*
* Created by longyihuang on 2021/5/1
*
* Location: shenzhen
*/

<template>
  <div class="amap-container" :style="{height: `${height}px`, width:`${width}px`}">
    <div :id="mapContainerId" class="amap"/>
    <div class="search-place-box" v-if="!config.liteStyle">
      <el-input id="search-place-input" v-model="searchPlaceText" size="mini" placeholder="请输入位置搜索"></el-input>
      <div id="search-place-result"></div>
    </div>
  </div>
</template>
<script>
	/* eslint-disable */
	const mapConfig = {
		width: 300,
		height: 300,
		zoom: 15,
		lng: undefined,
		lat: undefined,
		address: '',
		center: [114.0295, 22.609875],
		liteStyle: false
	}
	import AMapLoader from '@amap/amap-jsapi-loader';
	export default {
		name: "AMapComponent",
		props: {
			amapKey: {
				type: String,
				required: true
      },
			config: {
				type: Object,
				default: function () {
					return mapConfig
				}
			}
		},

		data() {
			const lng = this.config.lng
			const lat = this.config.lat
			const zoom = this.config.zoom || mapConfig.zoom
			const height = this.config.height || mapConfig.height
			const width = this.config.width || mapConfig.width
			return {
				map: undefined,
				marker: undefined,
				lng,
				lat,
        width,
        height,
				address: this.config.address,
				center: lng != undefined && lat != undefined ? [lng, lat] : mapConfig.center,
				zoom,
				liteStyle: this.config.liteStyle,  // 精简版
				pluginGeocoder: undefined,
        pluginPlaceSearch: undefined,
				searchPlaceText: '',
			}
		},


		mounted() {
			this.initMapLoader()
		},

    beforeDestroy() {
			if (this.map) {
				this.map.destroy()
      }
    },

    computed: {
	    mapContainerId() {
	    	return `map-container${this.config.id}`
      }
    },

		methods: {
			initMapLoader() {
				let that = this
        if (window.AMap) {
        	if (window.AMap.User.key == this.amapKey ) {
		        this.initMap(window.AMap)
		        return;
          }
	        AMapLoader.reset()
        }
				AMapLoader.load({
					"key": this.amapKey, // 申请好的Web端开发者Key，首次调用 load 时必填
				}).then((AMap)=>{
					that.initMap(AMap)
				}).catch(e => {
					console.log(e);
				})
			},

      initMap(AMap) {
				if (AMap) {
					this.map = new AMap.Map(this.mapContainerId, {
						resizeEnable: true,
						center: this.center,
						zoom: this.zoom
					});
					this.initPlugin();
					this.initLocation();
					if (this.config.liteStyle) {
						return
					}
					let that = this
					this.map.on('click', function (ev) {
						if (ev && ev.lnglat) {
							const {lng, lat} = ev.lnglat
							that.map.setCenter([lng, lat])
							that.selectPlace(lng, lat)
						}
					})
        }
      },


			initPlugin() {
				let self = this
        if (this.config.liteStyle) {
        	return
        }
				AMap.plugin('AMap.Geolocation', function () {
					let geolocation = new AMap.Geolocation({
						enableHighAccuracy: true,   //是否使用高精度定位，默认:true
						timeout: 10000,             //超过10秒后停止定位，默认：5s
						zoomToAccuracy: false,   //定位成功后是否自动调整地图视野到定位点
						panToLocation: true    //定位成功后将定位到的位置作为地图中心点
					});
					self.map.addControl(geolocation);
					AMap.event.addListener(geolocation, 'complete', self.onLocationComplete)
				});
				AMap.plugin('AMap.ToolBar', function () {
					let toolbar = new AMap.ToolBar({
						liteStyle: true
          })
					self.map.addControl(toolbar);
				});
				AMap.plugin('AMap.Geocoder', function () {
					self.pluginGeocoder = new AMap.Geocoder()
				})
				AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'],function(){
					const autoOptions = {
						// 使用联想输入的input的id
						input: "search-place-input",
						output: "search-place-result"
					}
					let autocomplete= new AMap.Autocomplete(autoOptions)

					let placeSearch = new AMap.PlaceSearch({
						map: self.map
					})
					AMap.event.addListener(autocomplete, 'select', function(e){
						const {district, name, address} = e.poi
						const place = `${district||''}${address||''}${name||''}`
						placeSearch.search(place)
					})
					AMap.event.addListener(placeSearch, 'markerClick', function(e){
						if (e && e.data && e.data.location) {
							const {location, name, cityname, adname, address} = e.data
							const {lng, lat} = location
							const place = `${cityname||''}${adname||''}${address||''}${name||''}`
							self.selectPlace(lng, lat, place)
						}
					})
				})
			},

			initLocation() {
				// 位置标记
				let self = this
				let markIcon = new AMap.Icon({
					size: new AMap.Size(25, 34),
					image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
					imageSize: new AMap.Size(25, 34),
				});
				this.marker = new AMap.Marker({
					icon: markIcon,
					offset: new AMap.Pixel(-12, -30)
				});

				if (this.lng != undefined && this.lat != undefined) {
					let lnglat = [this.lng, this.lat]
					this.makeMarker(lnglat)
          if (this.pluginGeocoder) {
	          this.pluginGeocoder.getAddress(lnglat, function (status, result) {
		          if (status === 'complete' && result.info === 'OK') {
			          const {formattedAddress} = result.regeocode
			          self.address = formattedAddress
		          }
	          })
          }
				}
			},

			onLocationComplete(data) {
			},



			makeMarker(lnglat) {
				if (this.marker) {
					this.marker.setPosition(lnglat)
					this.map.add(this.marker);
				}
			},


			selectPlace(lng, lat, address = undefined, isMark = true) {
				this.lng = lng
				this.lat = lat
				this.center = [lng, lat]
				isMark && this.makeMarker(this.center)
        if (address) {
	        this.$emit('change', {
		        lng,
		        lat,
		        address
	        })
        } else if (this.pluginGeocoder) {
	        let self = this
	        this.pluginGeocoder.getAddress(this.center, function (status, result) {
		        if (status === 'complete' && result.info === 'OK') {
			        const {formattedAddress} = result.regeocode
			        self.address = formattedAddress
			        self.$emit('change', {
				        lng,
				        lat,
				        address: self.address
			        })
		        }
	        })
        }
      }
		}
	}
</script>

<style lang="scss" scoped>
  .amap-container{
     position: relative;
    .amap{
      width: 100%;
      height: 100%;
    }
    .search-place-box{
      background: #ffffff;
      padding: 0px 4px;
      border-radius: 4px;
      position: absolute;
      top: 16px;
      right: 16px;
      .panel{
        margin-top: 8px;
        width: 200px;
      }
    }
  }

</style>
