<template>
	<view class="map-container">
		<map id="map" :style="{ width: '100%', height: '100vh' }" :latitude="latitude" :longitude="longitude" :zoom="13"
			:markers="markers" :custom-style-file="customStyleFile" @markertap="onMarkerTap" @callouttap="onCalloutTap">
		</map>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				latitude: 30.592,
				longitude: 114.305,
				markers: [],
				// 为自定义基座提供样式文件路径
				customStyleFile: ''
			}
		},
		onLoad() {
			// #ifdef APP-PLUS
			this.customStyleFile = plus.io.convertLocalFileSystemURL("_www/static/native-res/raw/mapstyle_grey.json");
			// #endif
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('MapData', (data) => {
				if (data && data.points) {
					this.processMapData(data.points);
				} else {
					this.addDefaultMarkers();
				}
			});
			// In case no data is received
			setTimeout(() => {
				if (this.markers.length === 0) {
					this.addDefaultMarkers();
				}
			}, 1000);
		},
		methods: {
			processMapData(points) {
				const newMarkers = points.map((point, index) => ({
					id: index,
					latitude: point.lnglat[1],
					longitude: point.lnglat[0],
					iconPath: '/static/images/biao.png',
					width: 30,
					height: 30,
					callout: {
						content: point.name,
						color: '#ffffff',
						fontSize: 14,
						borderRadius: 10,
						bgColor: '#000000',
						padding: 10,
						display: 'BYCLICK'
					}
				}));

				if (newMarkers.length > 0) {
					this.latitude = newMarkers[0].latitude;
					this.longitude = newMarkers[0].longitude;
					this.markers = newMarkers;
				}
			},
			addDefaultMarkers() {
				const wuhanPoints = [{
						lnglat: [114.404, 30.507],
						name: "华中科技大学"
					},
					{
						lnglat: [114.428, 30.476],
						name: "光谷金融港"
					},
					{
						lnglat: [114.433, 30.504],
						name: "武汉东站"
					}
				];
				this.processMapData(wuhanPoints)
			},
			onMarkerTap(e) {
				console.log('marker tapped', e.detail.markerId);
			},
			onCalloutTap(e) {
				console.log('callout tapped', e.detail.markerId);
			}
		}
	}
</script>

<style>
	.map-container {
		width: 100%;
		height: 100vh;
	}
</style>
