<template>
	<div class="map-container">
		<div class="container" id="mapBox"></div>
	</div>
</template>

<script setup lang="tsx">
import { nextTick, onMounted, shallowRef } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
/*在Vue3中使用时,需要引入Vue3中的shallowRef方法(使用shallowRef进行非深度监听,
因为在Vue3中所使用的Proxy拦截操作会改变JSAPI原生对象,所以此处需要区别Vue2使用方式对地图对象进行非深度监听,
否则会出现问题,建议JSAPI相关对象采用非响应式的普通对象来存储)*/

const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const map: any = shallowRef(null);
let AMapObj, marker;
const initMap = () => {
	window._AMapSecurityConfig = {
		securityJsCode: import.meta.env.VITE_AMAP_SECURITYJSCODE, //安全密钥
	};
	AMapLoader.load({
		key: import.meta.env.VITE_AMAP_KEY, // 申请好的Web端开发者Key，首次调用 load 时必填
		version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
	})
		.then((AMap) => {
			AMapObj = AMap;
			map.value = new AMap.Map('mapBox', {
				center: themeConfig.value.locationCenter, //初始化地图中心点位置
				zoom: 15, //初始化地图级别
			});

			AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.Geocoder'], () => {
				// 缩放条
				const toolbar = new AMap.ToolBar();
				// 比例尺
				const scale = new AMap.Scale();
				// 定位
				const geolocation = new AMap.Geolocation({
					enableHighAccuracy: true, //是否使用高精度定位，默认:true
					timeout: 10000, //超过10秒后停止定位，默认：5s
					position: 'RT', //定位按钮的停靠位置
					buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
					zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
				});
				map.value.addControl(geolocation);
				map.value.addControl(toolbar);
				map.value.addControl(scale);
				if (themeConfig.value.isIsDark) {
					const styleName = 'amap://styles/' + 'dark';
					map.value.setMapStyle(styleName);
				} else {
					const styleName = 'amap://styles/' + 'normal';
					map.value.setMapStyle(styleName);
				}
			});
		})
		.catch((e) => {
			console.log(e);
		});
};
/*
 * 监听坐标改变，重新绘制地图设置中心点 添加标点
 */
const addMarker = (data: any) => {
	const { longitude, latitude } = data;
	if (longitude && latitude) {
		marker = new AMapObj.Marker({
			position: new AMapObj.LngLat(longitude, latitude),
			anchor: 'bottom-center',
			map: map.value,
		});
		map.value.add(marker);
		map.value.setCenter([longitude, latitude]);
	}
};
onMounted(() => {
	nextTick(()=>{
		initMap();
	})
});
defineExpose({
	initMap,
	addMarker,
});
</script>

<style scoped>
.map-container {
	position: relative;
	width: 100%;
	height: 400px;
	.container {
		width: 100%;
		height: 100%;
	}
}
</style>
