<template>
	<view class="content">
		<view id="container">
			<view :style="{width:width,height:height}" :keyId='keyId' :change:keyId='keyId' :id="`mapModule` + keyId"
				:prop="mapData" :change:prop="mapModule.update" :lngLat="myLocations"
				:change:lngLat="mapModule.initAmap"></view>

		</view>
	</view>
</template>
<script module="mapModule" lang="renderjs">
	var common = require("@/common/common.js");
	var transform = require('../../common/transform.js');
	export default {
		data() {
			return {
				trackPolyline: null,
				polylines: {},
				zoom: 14,
				keyId: '',
				types: 1,
				Markers: [],
				markersArray: [],
				infoWindow: {},
				selectedMarker: null,
				markerData: {},
				markersIcon: '',
				markersIconActive: '',
				ownerInstance: null,
				map: null,
			};
		},
		mounted() {

		},
		methods: {
			initAmap(lngLat, _, ownerInstance) {
				lngLat = {
					lat: lngLat.latitude,
					lng: lngLat.longitude
				}
				lngLat = transform.wgs_gcj_encrypts(lngLat)
				let _this = this
				const script = document.createElement('script')
				script.src =
					'https://map.gpsall.cc/maps/api/js?key=AIzaSyCWxFJPWgJP8hb2cTbvfZb13tbm2rlhxgs&callback=initMap&v=weekly&loading=async';
				script.async = true; // 异步加载
				script.defer = true; // 延迟执行
				document.head.appendChild(script)
				window.initMap = function() {
					 // 延迟执行以确保元素已加载
					  // const elements = document.querySelectorAll(".gm-style-cc, .gmnoprint[role='menubar']");
					  // elements.forEach(el => el.style.display = "none");
					_this.loadAmap(lngLat)
				};

			},

			loadPanTo(lngLat, _, ownerInstance) {
				lngLat = {
					lat: lngLat.latitude,
					lng: lngLat.longitude
				}
				lngLat = transform.wgs_gcj_encrypts(lngLat)

				this.map.panTo(new google.maps.LatLng(lngLat.latitude, lngLat.longitude))
			},

			loadAmap(lngLat) {
				let _this = this
				var myOptions = {
					center: {
						lat: parseFloat(lngLat.latitude),
						lng: parseFloat(lngLat.longitude)
					},
					gestureHandling: "greedy", // 强制单指拖动
					fullscreenControl: false,
					draggable: true, // 显式启用拖拽
					zoom: _this.zoom,
					 keyboardShortcuts: false, // 禁用键盘快捷键
					panControl: false,
					zoomControl: false,
					scaleControl: false,
					streetViewControl: false,
					mapTypeControl: false,
					clickableIcons: false,
				}

				// 存储当前选中的 Marker
				_this.selectedMarker = null;
				_this.map = new google.maps.Map(document.getElementById("mapModule" + this.keyId), myOptions);

				//地图绑定事件
				new google.maps.event.addListener(_this.map, "click", function(event) {
					_this.$ownerInstance.callMethod('bindTapMap')
				});
				
				//如果有polylines则添加
				if (_this.polylines?.points?.length > 0) {
					let path = _this.polylines.points.map(item => {
						return {
							lng: item.lng,
							lat: item.lat
						}
					})

					_this.trackPolyline = new google.maps.Polyline({
						path: path,
						// geodesic: true,          // 沿地球曲率连线
						strokeColor: _this.polylines.color, // 轨迹线颜色
						strokeOpacity: 1.0, // 透明度
						strokeWeight: 3 // 线宽
					});
					// 更新轨迹线的路径
					_this.trackPolyline.setMap(_this.map);

					// 可选：自动移动地图中心到最新位置
					_this.map.panTo(path[path.length - 1]);
				}
				
				//如果有Markers则添加
				if (_this.Markers.length > 0) {
					_this.addMarkers(_this.$ownerInstance)
				}
				// console.log("render初始化数据")
				_this.$ownerInstance.callMethod('loadInitData')
			},

			//添加标记
			addMarkers() {
				if (this.markersArray.length > 0) this.clearMarkers() //添加前先删除所有标记
				console.log(this.Markers)
				this.Markers.map((item, index) => {
					this.AddMarker(item)
				})
			},
			AddMarker(item) {
				let label = null
				if (this.types == 2 && item.id != 50000) {
					label = {
						text: item.content,
						className: "map-label-num",
					}
				}
				let _this = this
				const marker = new google.maps.Marker({
					id: item.id,
					map: _this.map,
					data: item,
					label,
					position: new google.maps.LatLng(parseFloat(item.latitude), parseFloat(item.longitude)),
					icon: {
						url: item.iconPath, // 默认图标路径
						size: new google.maps.Size(item.width, item.height),
						scaledSize: new google.maps.Size(item.width, item.height)
					},
					zIndex: 20
				});
				marker.addListener('click', function(event) {
					_this.loadMarkertap(marker, item)
				})
				this.markersArray.push(marker)
			},

			//删除所有标记
			clearMarkers() {
				this.selectedMarker = null
				this.defaultIcon = {}
				this.selectedIcon = {}
				this.markersArray.forEach(marker => {
					marker.setMap(null)
				});
				this.markersArray = [];
			},

			update(newValue, _, ownerInstance) {
				console.log('过来了')
				console.log(newValue)
				if (newValue.zoom) this.zoom = newValue.zoom || 14
				if (newValue.polylines && newValue.polylines.points && newValue.polylines.points.length > 0) this
					.polylines = newValue.polylines
				if (newValue.markers && newValue.markers.length < 1) return
				this.Markers = newValue.markers || []
				this.types = newValue.type
				if (!this.map) return
				this.addMarkers()
			},
			//点击marker触发
			loadMarkertap(marker, item) {
				let markerId = marker.data.id
				if (markerId == 50000) return
				if (this.types == 1) this.shopMarkerFn(marker, item)
				if (this.types == 2) this.nearCabinetMarkerFn(marker, item)
				// if(this.type == 3) this.shopMarkerFn(marker)
				this.$ownerInstance.callMethod('onMarkertap', marker.data)
			},
			//换电柜
			nearCabinetMarkerFn(marker, item) {
				if (this.selectedMarker) {
					this.selectedMarker.setIcon({
						url: item.iconPath, // 默认图标路径
						size: new google.maps.Size(item.width, item.height),
						scaledSize: new google.maps.Size(item.width, item.height)
					});
				}
				marker.setIcon({
					url: item.iconPathActive, // 默认图标路径
					size: new google.maps.Size(item.width, item.height),
					scaledSize: new google.maps.Size(item.width, item.height)
				});
				this.selectedMarker = marker;

			},

			//门店Marker逻辑
			shopMarkerFn(marker, item) {
				if (this.selectedMarker) {
					this.selectedMarker.setIcon({
						url: item.iconPath, // 默认图标路径
						size: new google.maps.Size(item.width, item.height),
						scaledSize: new google.maps.Size(item.width, item.height)
					});
					this.selectedMarker.setOptions({
						label: null
					});
				}
				marker.setIcon({
					url: item.iconPathActive, // 默认图标路径
					size: new google.maps.Size(item.width, item.height),
					scaledSize: new google.maps.Size(item.width, item.height)
				});
				let distance = common.getFlatternDistance(this.myLocations.longitude, this.myLocations
					.latitude, item.longitude, item.latitude)
				let time = Math.ceil(Number(((distance - 0) / 1000).toFixed(2)) * 25 / 10)
				let content = `${common.formatDistance(Number(distance))} 骑行${time}分钟`
				marker.setOptions({
					label: {
						text: content,
						className: "map-label",
					}
				})
				this.selectedMarker = marker;
			},

			//typeFn
			typeFn(e, __, ownerInstance) {
				this.types = e[0]
			},
		}
	}
</script>

<script>
	export default {
		props: {
			keyId: {
				type: String,
				default: '0'
			},
			id: {
				type: String,
				default: 'mapModule'
			},
			width: {
				type: String,
				default: '100%'
			},
			height: {
				type: String,
				default: '100%'
			},
			/**
			 * @param type  1 //1门店  2 换电柜  3其他 
			 * @param Markers   //Markers数据 
			 * @param * 后续数据随便添加
			 **/
			mapData: {
				type: Object,
				required: true //必填项
			},
			myLocations: {
				type: Object,
				required: true //必填项
			},

		},
		data() {
			return {

			};
		},
		mounted() {
		},
		methods: {
			onMarkertap(marker) {
				this.$emit('changMarkertap', marker)
			},
			bindTapMap() {
				console.log('点击事件!')
			},
			loadInitData() {
				console.log('初始化成功!')
			},
		}
	}
</script>

<style scoped>
	#container {
		width: 100%;
		height: 100%;
	}
</style>