<template>
	<el-dialog title="经纬度选择" v-model="visible" :width="850" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="true">
		<div class="map">
			<el-input v-model="address" placeholder="搜索地名" @change="searchMapHandle" style="width: 300px;"/>
			<el-button type="primary" style="margin-left: 20px" @click="searchMapHandle">搜索</el-button>
			<el-button type="primary" style="margin-left: 10px" @click="submit">确定</el-button>
			<div id="map-container">
				<div class="input">
					<el-input v-model="location.lng" size="small" placeholder="经度"></el-input>
					<el-input v-model="location.lat" size="small" placeholder="纬度"></el-input>
				</div>
			</div>
		</div>
	</el-dialog>
</template>

<script setup>
import AMapLoader from '@amap/amap-jsapi-loader';
import {ref} from "vue";

defineExpose({
	open,
	setData
})

defineOptions({
	name: "piMap"
})

const emit = defineEmits(['success', 'closed'])
let AMap = ref(null)
let location = ref({
	lat: '',
	lng: ''
})
let markers = ref([])
let map = ref(null)
let visible = ref(false)
let address = ref("")

//显示
function open(){
	visible.value = true;
	initMap()
}

function initMap(){
	window._AMapSecurityConfig = {
		securityJsCode: "1d4ec5360562473b31ffd4925995fe5c"
	}
	AMapLoader.load({
		key: "90960616a710a55eebb2cdfb0a959ede",
		version:"2.0",
		plugins: ['AMap.Scale', 'AMap.PlaceSearch', 'AMap.AutoComplete']
	}).then((a)=>{
		map.value = new a.Map("map-container",{
			viewMode: "3D",
			zoom: 15
		})
		// 地图点击事件
		map.value.on('click', clickMapHandler)
		AMap.value = a
		searchMapHandle()
	})
}

// 点击地图事件
function clickMapHandler(e) {
	location.value.lng = e.lnglat.getLng()
	location.value.lat = e.lnglat.getLat()
	map.value.remove(markers.value)
	let marker = new AMap.value.Marker({
		position: [location.value.lng, location.value.lat],
	});
	marker.setMap(map.value)
	markers.value.push(marker)
}

function searchMapHandle() {
	AMap.value.plugin('AMap.PlaceSearch', function () {
		const autoOptions = {
			map: map.value,
			pageSize: 1,
			pageIndex: 1,
			autoFitView: true
		};
		const placeSearch = new AMap.value.PlaceSearch(autoOptions);
		placeSearch.search(address.value, function (status, result) {
			if (status == 'complete') {
				if (result.poiList.pois.length > 0) {
					location.value.lng = result.poiList.pois[0].location.lng;
					location.value.lat = result.poiList.pois[0].location.lat;
				}
			}
		})
	})
}

function submit() {
	emit('success', location.value)
	visible.value = false;
}

function setData(a) {
	address.value = a
}

</script>

<style scoped>

.map #map-container {
	padding: 0;
	margin: 20px auto;
	width: 100%;
	height: 500px;
}

.el-input {
	width: 150px;
	margin: 10px 0 0 10px;
	z-index: 5;
}
</style>
