<template>
	<view id="mapDiv" class="mapDiv" :apikey="apiKey" :prop="option" :change:prop="Trenderjs.initTMap">
		<view class="position" @click.stop="Trenderjs.onPosition">
			<svg t="1734080022350" class="position-icon" viewBox="0 0 1024 1024" version="1.1"
				xmlns="http://www.w3.org/2000/svg" p-id="4287" xmlns:xlink="http://www.w3.org/1999/xlink">
				<path d="M512 512m-80 0a80 80 0 1 0 160 0 80 80 0 1 0-160 0Z" p-id="4288"></path>
				<path
					d="M960 480h-33.632C910.752 276.16 747.84 113.248 544 97.632V64a32 32 0 1 0-64 0v33.632C276.16 113.248 113.248 276.16 97.632 480H64a32 32 0 0 0 0 64h33.632C113.248 747.84 276.16 910.752 480 926.368V960a32 32 0 1 0 64 0v-33.632C747.84 910.752 910.752 747.84 926.368 544H960a32 32 0 1 0 0-64zM544 862.368V800a32 32 0 1 0-64 0v62.368C311.424 847.104 176.896 712.576 161.632 544H224a32 32 0 1 0 0-64H161.632C176.896 311.424 311.424 176.896 480 161.632V224a32 32 0 0 0 64 0V161.632c168.576 15.296 303.104 149.792 318.368 318.368H800a32 32 0 1 0 0 64h62.368c-15.264 168.576-149.792 303.104-318.368 318.368z"
					p-id="4289"></path>
			</svg>

		</view>
	</view>
</template>

<script>
	import tools from './tools.js'
	import iconPath from '@/static/images/point.png'
	import { EventBus } from "@/utils/vueBus.js"
	export default {
		name: "tianditu",
		props: {
			apiKey: {
				type: String,
				require: true,
				default: ''
			},
		},
		data() {
			return {
				Tmap: null,
				option: {
					type: '',
					apikey: '',
					lng: '',
					lat: '',
					png: iconPath
				}
			};
		},

		created() {

		},
		mounted() {

		},
		beforeDestroy() {
			// EventBus.$off('someEvent'); // 确保在组件销毁前移除事件监听
		},
		methods: {
			compliteonLoadTianDiTu() {
				this.$emit('onLoadTianDiTu')

			},
			initCharts(lng, lat, iconPng) {
				this.option = {
					apikey: this.apiKey,
					lng,
					lat,
					png: iconPng || this.option.png,
					type: 'open'
				}
				// setTimeout(() => {
				// 	this.Trenderjs.getLocation()
				// }, 5000)
			},
			upDataCharts(lng, lat) {
				this.option = {
					...this.option,
					type: 'Icon',
					lng,
					lat,
					png: this.customIcon || this.option.png,
					type: 'update'
				}
			},
			async nextPoint(lnglat) {
				var that = this;
				let params = {
					postStr: JSON.stringify({
						lon: lnglat.lng,
						lat: lnglat.lat,
						ver: 1,
					}),
					type: 'geocode',
					tk: that.apiKey
				}
				let resData = await tools.createRequest('https://api.tianditu.gov.cn/geocoder', params, true)
				if (resData.status === '0') {
					const info = tools.formatterAdressLocation(resData.result, 1)
					this.option = {
						...this.option,
						apikey: this.apiKey,
						lng: lnglat.lng,
						lat: lnglat.lat,
						png: this.customIcon || this.option.png,
						type: 'update'
					}
					this.$emit('onSelect', info)
				} else {
					tools.createMessage('数据异常', 1000, false, 'error')
				}
			},
		}
	}
</script>
<script module="Trenderjs" lang="renderjs">
	import { EventBus } from "@/utils/vueBus.js"
	import iconPath from '@/static/images/point.png'
	var Tmap = null;
	export default {
		data() {
			return {
				options: {},
				markerList: [],
				labelLsit: [],
				MyLngLat: {
					lng: '',
					lat: ''
				}
			}
		},
		mounted() {

		},
		beforeDestroy() {
			this.removeMapEvent()
		},
		methods: {
			onPosition() {
				// const { longitude, latitude } = { longitude: 114.414431, latitude: 30.482926 };
				// 	this.SelectedDot({ longitude, latitude })
				// 	this.MyLngLat = {
				// 		lng: longitude,
				// 		lat: latitude
				// 	}
				// 	console.log("this.MyLngLat = " , this.MyLngLat)
				// 	this.setMyIcon()
				EventBus.$emit('TianDiTuSearch', (res) => {
					const { longitude, latitude } = res;
					this.SelectedDot({ longitude, latitude })
					this.MyLngLat = {
						lng: longitude,
						lat: latitude
					}
					this.setMyIcon()
				})

			},
			addMapEvent() {
				//移除地图的移动停止事件
				this.getLocation()
				this.removeMapEvent()
				if (Tmap) {
					Tmap.addEventListener("moveend", this.MapMoveend);
					Tmap.addEventListener('zoomend', this.handleZoomEvent);
				}
			},
			removeMapEvent() {
				//移除地图的移动停止事件
				try {
					if (Tmap) {
						Tmap.removeEventListener("moveend", this.MapMoveend);
						Tmap.removeEventListener("zoomend", this.MapMoveend);
					}
				} catch (error) {
					//TODO handle the exception
				}
			},
			// 移动地图,获取中心点
			MapMoveend(e) {
				try {
					const v = e.target.getCenter()
					const Lng = v.getLng();
					const Lat = v.getLat();
					this.$emit("moveMap", { Lng, Lat })
				} catch (error) {
					//TODO handle the exception
				}
			},

			// // 移动地图,获取中心点
			// MapMoveend: throttle((e) => {
			// 	console.log("防抖防抖防抖1111", e.target.getCenter(), this)
			// 	const v = e.target.getCenter()
			// 	const Lng = v.getLng();
			// 	const Lat = v.getLat();
			// 	this.$emit("moveMap", { Lng, Lat })
			// }, 500),

			// 点击地图标注的点位
			clickMapSite({ type, target, lnglat, containerPoint }) {
				const Lng = lnglat.getLng();
				const Lat = lnglat.getLat();
				this.$emit('handleMapSite', { Lng, Lat })

			},
			// 天地图缩放事件
			handleZoomEvent(event) {
				if (!this.labelLsit || this.labelLsit.length === 0) return;
				// let currentZoom = event.target.getZoom();
				// console.log("handleZoomEvent = 天地图缩放事件  " , currentZoom)
				this.labelLsit.forEach(el => {
					this.labelShowOrHide(el)
				})
			},
			// 标签的显示与隐藏
			labelShowOrHide(label) {
				if (!Tmap) return
				let currentZoom = Tmap.getZoom();
				if (currentZoom >= 16) {
					label.show()
				} else {
					label.hide()
				}
			},

			initTmap() {
				try {
					Tmap = null;
					Tmap = new T.Map('mapDiv', {
						projection: 'EPSG:4326',
					});
				} catch (error) {
					//TODO handle the exception
				}
			},


			initTMap(newValue, oldValue, ownerInstance, instance) {
				this.options = newValue
				if (newValue.type === 'open' && newValue.apikey) {
					if (!window.T) {
						const script = document.createElement('script')
						script.src = 'https://api.tianditu.gov.cn/api?v=4.0&tk=' + this.options.apikey
						script.onload = this.initChartsRender.bind(this)
						document.head.appendChild(script) 
					} else {
						const {
							lng,
							lat
						} = this.options
						this.initTmap()
						Tmap.centerAndZoom(new T.LngLat(lng, lat), 15);
						this.$ownerInstance.callMethod('nextPoint', {
							lng,
							lat
						})
						Tmap.addEventListener('click', (e) => {
							console.log("nextPoint", e.lnglat)
							this.$ownerInstance.callMethod('nextPoint', e.lnglat)
						});
					}
				} else {
					// 选点，更新
					// const {
					//     lng,
					//     lat
					// } = newValue
					// this.upDataChartsRender(lng, lat)
					this.$emit("clickMap")
				}
			},
			initChartsRender() {
				this.$ownerInstance.callMethod('compliteonLoadTianDiTu')
				const {
					lng,
					lat
				} = this.options
				var that = this;
				this.initTmap()
				Tmap.centerAndZoom(new T.LngLat(lng, lat), 15);
				this.setIcon(lng, lat, true)
				this.$ownerInstance.callMethod('nextPoint', {
					lng,
					lat
				})
				Tmap.addEventListener('click', (e) => {
					this.$ownerInstance.callMethod('nextPoint', e.lnglat)
				});

				// Tmap.addEventListener("moveend", (e) => {
				// 	console.log('addEventListener  = ' , e)
				// });
				this.addMapEvent()
				this.$emit("handleSearch")
			},
			upDataChartsRender(lng, lat) {
				if (!Tmap) return
				this.setIcon(lng, lat, true)
				Tmap.centerAndZoom(new T.LngLat(lng, lat), 15);
			},
			setIcon(lng, lat, isClear, iconU, info) {
				if (isClear) {
					this.clearIcon()
				}
				const icon = new T.Icon({
					iconUrl: iconU || this.options.png,
					iconSize: new T.Point(45, 45),
					iconAnchor: new T.Point(15, 30)
				});
				const marker = new T.Marker(new T.LngLat(lng, lat), {
					icon
				});
				// 点位注册点击事件
				try {
					marker.removeEventListener("click", this.clickMapSite);
				} catch (error) {}
				marker.addEventListener("click", this.clickMapSite);
				// 缓存注册点击事件的点位
				this.markerList.push(marker)
				Tmap.addOverLay(marker);
				if (info) {
					try {
						var label = new T.Label({
							// text: this.setLable(info.locationName),
							text: info.locationName,
							position: marker.getLngLat(),
							offset: new T.Point(-50, 30)
						});
						Tmap.addOverLay(label);
						label.setLngLat(marker.getLngLat());
						label.setBorderLine(0);
						// label.setBackgroundColor ('transparent');
						label.setFontSize(10);
						this.labelLsit.push(label)
						// 判断当前是否显示
						this.labelShowOrHide(label)
					} catch (error) {
						//TODO handle the exception
						console.log("info = error ", error)
					}
				}
			},
			// 移除点位，并注销点位绑定的点击事件
			clearIcon() {
				return new Promise((resolve, reject) => {
					try {
						(this.markerList || []).forEach(el => {
							try {
								el.removeEventListener("click", this.clickMapSite);
							} catch (error) {}
						});
						this.markerList = [];
						this.labelLsit = [];
						Tmap.clearOverLays();
						this.setMyIcon()
					} catch (error) {
						//TODO handle the exception
					} finally {
						resolve()
					}
				})

			},
			getLocation() {
				var lo = new T.Geolocation();
				console.log("天地图获取定位 = ", lo, lo.getStatus())
				try {

					lo.getCurrentPosition((res) => {
						console.log('获取定位', res)

					});
				} catch (error) {
					//TODO handle the exception
					console.log("天地图获取定位 = error ", error)
				}
			},
			SelectedDot(res) {
				const { longitude, latitude } = res;
				Tmap.panTo(new T.LngLat(longitude, latitude), 16); // 移动到选中的点位
			},
			setMyIcon() {
				const { lng, lat } = this.MyLngLat || {}
				if (!Tmap || !lng || !lat) return;
				const icon = new T.Icon({
					iconUrl: iconPath,
					iconSize: new T.Point(45, 45),
					iconAnchor: new T.Point(15, 30)
				});
				const marker = new T.Marker(new T.LngLat(lng, lat), {
					icon
				});

				Tmap.addOverLay(marker);
				try {
					marker.removeEventListener("click", () => {});
				} catch (error) {}
				marker.addEventListener("click", () => {});
			},
			setLable(locationName) {
				let el = '';
				for (let i = 0; i < locationName.length; i++) {
					if (!i || i % 10) {
						el += `${locationName[i]}`
					} else {
						el += `<br>${locationName[i]}`
					}
				};
				return `<p class='map-label'>${el}<p>`
			}
		},
	}
</script>
<style lang="scss">
	.mapDiv {
		width: 100%;
		height: 100%;
	}

	.position {
		position: fixed;
		right: 30rpx;
		bottom: 40vh;
		z-index: 1000;
		width: 80rpx;
		height: 80rpx;
		background-color: #fff;
		padding: 10rpx;

		.position-icon {
			width: 100%;
			height: 100%;

			path {
				fill: #3291F8;
			}

		}
	}
</style>