<template>
	<div :style="{width:'100%',height:height}">
		<div class="divBtn" @click="getLoalcationPoint">
			<uni-icons custom-prefix="iconfont" type="icon-ebikedingwei2" color="#6f7777" size="16" />
			<div>定位</div>
		</div>
		<map id="mapRef" ref="mapRef" show-location :style="{width:'100%',height:height}" :scale="scale"
			:longitude="longitude" :latitude="latitude" :markers="markers" @tap="ontap" />
	</div>
</template>

<script setup>
	import AMapWX from "@/utils/amap-wx.130.js";
	import {
		ref,
		onMounted,
		getCurrentInstance
	} from "vue";
	import * as map from "@/utils/usermap.js";
	import {
		findIndex
	} from "lodash";

	var amapsdk = new AMapWX({
		key: map.sdkKey
	});

	const {
		lng,
		lat,
		height
	} = defineProps(["lng", "lat", "height"]);
	const emit = defineEmits(["change"]);

	const mapRef = ref("mapRef");
	let oMap = null;
	const latitude = ref(lat);
	const longitude = ref(lng);
	const scale = ref(15);
	const point = lng && lat ? [map.addMarker(1, lng, lat, "point.png")] : null;
	const markers = ref(point);

	onMounted(() => {
		oMap = map.getMap("mapRef", getCurrentInstance());
	});

	const ontap = (e) => {
		const {
			detail: {
				latitude: lat,
				longitude: lng
			}
		} = e;
		changPoint(lng, lat);
	}

	const getLoalcationPoint = () => {
		map.getLoalcation( (res) => {
			const {
				longitude: lng,
				latitude: lat
			} = res;
			latitude.value = lat;
			longitude.value = lng;
			changPoint(lng, lat);
			oMap.moveToLocation();
		});
	}

	const changPoint = (lng, lat) => {
		const arrPoint = markers.value;
		let index = findIndex(arrPoint, {
			id: 1
		});
		index = index == -1 ? arrPoint.length : index;
		arrPoint[index] = map.addMarker(1, lng, lat, "point.png");
		markers.value = arrPoint;
		map.reverseGeocoder(amapsdk, lng, lat, (res) => {
			emit('change', res);
		}, (res) => {

		})
	}

	
</script>

<style>
	.divBtn {
		position: absolute;
		z-index: 100;
		top: 50%;
		left: 10px;
		background-color: white;
		border-radius: 5px;
		width: 40px;
		text-align: center;
		font-size: 12px;
		padding: 10px 5px;
		border: 1px solid #80808061;
	}
</style>