<template>
	<view id="mapDiv" class="mapDiv" :apikey="apiKey" :prop="option" :change:prop="Trenderjs.initTMap">
		<view class="tool-btn">
			<view v-if="isGetLocation" class="position" @click.stop="Trenderjs.onPosition">
				<image class="position-icon" src="@/static/images/position.png" mode="aspectFit"></image>
			</view>
			<view class="position" @click.stop="$emit('openHint')">
				<image class="position-icon" src="@/static/images/hint.png" mode="aspectFit"></image>
				<text class="position-text">声明</text>
			</view>
			<view v-if="isFeedback" class="position" @click.stop="$emit('openFeedback')">
				<image class="position-icon" src="@/static/images/feedback.png" mode="aspectFit"></image>
				<text class="position-text">反馈</text>
			</view>
		</view>
	</view>
</template>

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

		created() {
			console.log('===== ', this.option)
		},
		mounted() {

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


			},
			initCharts(lng, lat, iconPng) {
				this.option = {
					...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'
	import dotPath from '@/static/images/dot.png'
	import locationPath from '@/static/images/location.png'
	import $confog from "@/config/index.js"
	import { mapGetters } from "vuex"
	const { type } = $confog
	var Tmap = null;
	const left = -(uni.upx2px(150));
	export default {
		props: {
			// 点位列表
			siteListArr: {
				type: Array,
				default: () => {

				}
			},
			searchDot: {
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				options: {},
				markerList: [],
				labelLsit: [],
				MyLngLat: {
					lng: '',
					lat: ''
				},
				// 中心点位
				centreDot: null,
				// 中心点位地址解析
				centreText: null,
				// 中心点信息
				centreMarker: '',
				// 我的点位信息
				MyMarker: null

			}
		},

		computed: {
			...mapGetters(['useLocation'])
		},
		mounted() {

		},
		beforeDestroy() {
			this.removeMapEvent()
		},

		watch: {
			siteListArr: {
				handler(newL, oldL) {
					this.handleSiteList(newL)
				},
				deep: true,
				immediate: true
			},
			centreText: {
				handler(newL, oldL) {
					if (newL && newL !== oldL) {
						this.$emit("centre-text-callback", newL)
					}
				},
				deep: true
			},
			useLocation: {
				handler(newL, oldL) {
					if (this.MyMarker) this.setMyIcon()
				},
				deep: true
			}
		},
		methods: {
			handleSiteList(newArr) {
				this.clearIcon().then(async (res) => {
					const dotArr = []
					if (Tmap) await this.getMapCenter();

					const { Lng, Lat } = this.centreDot || {};

					let maxIcon = false;
					(newArr || []).forEach((el, index) => {
						el.maxIcon = false;
						// 通过搜索自动移动到收索返回的第一个点位
						if (index === 0 && this.searchDot) {
							this.SelectedDot(el, true, 12)
						}
						const { longitude, latitude, mapTypeIcon } = el;
						if (Lng == longitude && Lat == latitude) {
							el.maxIcon = true;
							maxIcon = true;
						};
						this.setIcon(el);
					});
					// 是否标记中心点
					if (!maxIcon) this.setCentre()
					this.setMyIcon()

				})

				// console.log('siteListArr = ', newL)
				// if (this.siteListArr && this.siteListArr.length) {
				// 	setTimeout(() => {
				// 		console.log("this.centreDot 1 = ", this.centreDot)
				// 		const { longitude, latitude, mapTypeIcon } = el;
















				// 	}, 10);
				// }




			},
			getMapCenter() {
				return new Promise((resolve) => {
					const Fn = () => {
						if (Tmap) {
							const c = Tmap.getCenter();
							this.centreDot = {
								Lng: c.getLng(),
								Lat: c.getLat()
							};
							this.dotParse(c);
							resolve()
						} else {
							setTimeout(() => {
								Fn()
							}, 100);
						}
					};
					Fn()
				})

			},
			// 中心点位逆解析
			dotParse(v) {
				try {
					const geocode = new T.Geocoder();
					geocode.getLocation(v, (result) => {
						if (result.getStatus() == 0) {
							let t = '';
							const { poi } = result.getAddressComponent()
							try {
								if (poi && poi.indexOf('湖北省武汉市') === 0) {
									const lo = poi.split('湖北省武汉市')
									lo.forEach((el, index) => {
										if (index >= 1) {
											t = `${t}${el}`
										}
									})
								}
							} catch (error) {
								//TODO handle the exception
							}
							this.centreText = t || poi
						} else {
							this.centreText = null
						}
					});
				} catch (error) {
					this.centreText = null
				}
			},
			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 || {};
					if (longitude && latitude) {
						this.SelectedDot({ longitude, latitude })
					}

					// 	// this.SelectedDot({ longitude, latitude })
					// 	// this.MyLngLat = {
					// 	// 	lng: longitude,
					// 	// 	lat: latitude
					// 	// }
					// 	// this.clearIcon()
				})

			},
			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.handleZoomEvent);
					}
				} catch (error) {
					//TODO handle the exception
				}
			},
			// 移动地图,获取中心点
			MapMoveend(e) {
				try {
					// if (type === 'H6') {
					// 	const v = e.target.getCenter()
					// 	// 自然缩放移动，刷新接口
					// 	const Lng = v.getLng();
					// 	const Lat = v.getLat();
					// 	this.$emit("moveMap", { Lng, Lat })
					// } else {
					// 	// 地图移动，判断是否缩放/移动地图，还是通过点位定位
					// 	if (!this.checkedDot) {
					// 		const v = e.target.getCenter()
					// 		// 自然缩放移动，刷新接口
					// 		const Lng = v.getLng();
					// 		const Lat = v.getLat();
					// 		this.$emit("moveMap", { Lng, Lat })
					// 	} else {
					// 		// 点位移动，做处理
					// 		this.$nextTick(() => {
					// 			this.checkedDot = false;
					// 		})
					// 	}
					// }
					// 地图移动，判断是否缩放/移动地图，还是通过点位定位
					if (!this.checkedDot) {
						const v = e.target.getCenter()
						// 自然缩放移动，刷新接口
						if (v) {
							const Lng = v.getLng();
							const Lat = v.getLat();
							this.$emit("moveMap", { Lng, Lat })
						}
					} else {
						// 点位移动，做处理
						this.$nextTick(() => {
							this.checkedDot = false;
						})
					}


				} catch (error) {
					//TODO handle the exception
				}
			},

			// 点击地图标注的点位
			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;
				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) {
					console.log('Tmap error= ', error)
					//TODO handle the exception
				}
			},
			setViewport() {
				try {
					console.log('window.devicePixelRatio = ', window.devicePixelRatio)
					console.log('window.getResolution 1 = 1 ', Tmap, window.screen.width * window.devicePixelRatio)
					const w = window.screen.width * window.devicePixelRatio
					const meta = document.createElement('meta')
					meta.name = 'viewport'
					meta.content =
						`width=device-width,initial-scale=1.0, maximum-scale=1.0,minimum-scale=1.0, user-scalable=no`
					// meta.content = `initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no` 
					// meta.media = `(device-height: 568px)` 

					document.head.appendChild(meta)


				} catch (err) {
					console.log('---------- ', err)
				}
			},

			initTMap(newValue, oldValue, ownerInstance, instance) {
				this.options = newValue
				if (newValue.type === 'open' && newValue.apikey) {
					if (!window.T) {
						// this.setViewport() 
						const script = document.createElement('script')
						// script.src = "https://tile0.tianditu.gov.cn/vts?t=vt&pk=ag1adgmgd&tk=92053ec7c4309bf20d822b28f150f33d&v=1.0"
						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) => {
							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.$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, max = false) {
			setIcon(row) {
				const { longitude, latitude, mapTypeIcon, locationName, maxIcon } = row

				// const w = uni.upx2px(54)
				// const h = uni.upx2px(54)
				const icon = new T.Icon({
					iconUrl: mapTypeIcon || this.options.png,
					iconSize: maxIcon ? new T.Point(60, 60) : new T.Point(45, 45),
					iconAnchor: new T.Point(15, 45)
				});
				const marker = new T.Marker(new T.LngLat(longitude, latitude), {
					icon
				});
				// 点位注册点击事件
				try {
					marker.removeEventListener("click", this.clickMapSite);
				} catch (error) {}
				marker.addEventListener("click", this.clickMapSite);
				// 缓存注册点击事件的点位
				this.markerList.push(marker)
				Tmap.addOverLay(marker);
				if (locationName) {
					try {
						var label = new T.Label({
							// text: this.setLable(locationName),
							text: locationName,
							position: marker.getLngLat(),
							offset: new T.Point(left, 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 = [];
						this.centreMarker = null;
						this.MyMarker = null;
						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, dot = false, level = 16) {
				this.checkedDot = dot
				const { longitude, latitude } = res;
				Tmap.panTo(new T.LngLat(longitude, latitude), level); // 移动到选中的点位
				setTimeout(function() {
					this.checkedDot = false
				}, 40);
			},
			setMaxIcon() {

			},
			setMyIcon() {
				const { longitude, latitude } = this.useLocation || {}
				if (!Tmap || !longitude || !latitude) return;
				// const w = uni.upx2px(54)
				// const h = uni.upx2px(54)
				const icon = new T.Icon({
					iconUrl: locationPath,
					iconSize: new T.Point(30, 30)
				});
				const marker = new T.Marker(new T.LngLat(longitude, latitude), {
					icon
				});

				Tmap.addOverLay(marker);
				try {
					marker.removeEventListener("click", () => {});
				} catch (error) {}
				marker.addEventListener("click", () => {});
				this.MyMarker = marker

			},
			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>`
			},
			// setTcon
			// centreDot
			// 设置中心点坐标
			setCentre() {
				if (type !== 'H6') return
				// siteListArr
				if (this.centreDot) {
					try {
						const { Lng, Lat } = this.centreDot || {};
						// const w = uni.upx2px(54)
						// const h = uni.upx2px(92)
						const icon = new T.Icon({
							iconUrl: dotPath,
							iconSize: new T.Point(27, 46)
						});
						const d_ = new T.Marker(new T.LngLat(Lng, Lat), {
							icon,
							zIndexOffset: 666
						});
						Tmap.addOverLay(d_);
						this.centreMarker = d_
					} catch (error) {
						//TODO handle the exception
						console.log('this.centreDot error ', error)
					}


				}
			}
		},
	}
</script>
<style lang="scss">
	.mapDiv {
		width: 100%;
		height: 100%;
	}

	.tool-btn {
		position: fixed;
		right: 30rpx;
		bottom: 45vh;
		z-index: 1000;
	}

	.position {

		width: 94rpx;
		// height: 99rpx;
		background-color: #fff;
		padding: 10rpx;
		border-radius: 22rpx;
		padding: 23rpx 20rpx 22rpx 20rpx;

		.position-icon {
			width: 54rpx;
			height: 54rpx;

			path {
				fill: #3291F8;
			}

		}
		.position-text{
			display: inline-block;
			width: 100%;
			text-align: center;
			font-size: 26rpx;
			color: #3291F8;
			line-height: 1.2;
		}
		&+.position{
			margin-top: 20rpx;
		}
	}
</style>