<template>
	<view class="map-box">
		<search ref="searchRef" :mapConfig="mapConfig" @handleSearch="handleSearch" v-show="showMap" />

		<tiandituMap ref="tiandituMapRefs" @handleSearch="$refs.searchRef.onSearchFocus()" @clickMap="handleClickMap"
			@moveMap="moveMapSearch" @onLoadTianDiTu="initMaps" @onSelect="selectPoint" :apiKey="apiKey"
			@handleMapSite="handleMapSite" @centre-text-callback="e => centreText = e" :siteListArr='siteListArr'
			:searchDot="searchDot" @openHint="$refs.HintContentRef.open()" @openFeedback="goPages('feedback')" />


		<Touchbox ref="TouchboxRef" :maxHeight="0.8" v-show="showMap && siteListArr && siteListArr.length > 0"
			:zIndex="1001" @currentHeight="e => TouchHeight = e">
			<template #touchSlot>
				<!-- 	<view class="centre-box" v-if="SearchText">
					<text class="text">为您展示</text>
					<text class="text-val one-row">{{SearchText}}</text>
					<text class="text">相关的大厅</text>
				</view> -->
				<view class="centre-box" v-if="SearchText || centreText">
					<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>
					<text class="text">为您展示</text>
					<text class="text-val one-row">{{SearchText || centreText}}</text>
					<text class="text">{{ SearchText ? '相关的大厅' : '附近的大厅'}}</text>
				</view>
			</template>
			<template #contentSlot>
				<!-- <scroll-view :style="{'height': getScrollHeight(TouchHeight , centreText)}" scroll-y="true" -->
				<scroll-view :style="{'height': TouchHeight + 'px'}" scroll-y="true" :show-scrollbar="false">
					<template v-for="(item , index) in siteListArr">
						<siteListModel :index="index" :info="item" @checkSiteDetails="handleMapSite" />
					</template>
				</scroll-view>
			</template>
		</Touchbox>

		<siteDetails ref="siteDetailsRef" />
		<!-- 提示 -->
		<HintContent ref="HintContentRef" :mapConfig="mapConfig" />
	</view>
</template>
<script>
	import search from "./model/search.vue"
	import siteListModel from "./model/siteList.vue";
	import tools from '@/components/tiandituMap/tools.js'
	import {
		getMapCenterPoint_Api,
		getMapList_Api,
		getMapConfig_Api,
		getVisituvpv_Api
	} from "@/api/map.js"
	import siteDetails from "./model/siteDetails.vue"
	import $config from "@/config/index.js"
	import {
		EventBus
	} from "@/utils/vueBus.js"
	import {
		getLocation
	} from "@/utils/tool.js"
	import serviceCenter from "./model/service-center.vue"
	import HintContent from "./model/hint.vue"
	import {
		getUUID
	} from "@/utils/tool.js";
	export default {
		name: 'tdtmap',
		components: {
			search,
			siteListModel,
			serviceCenter,
			siteDetails,
			HintContent,
		},
		data() {
			return {
				//是否通过搜索查询点位
				searchDot: false,
				// 是否显示地图
				showMap: false,
				SearchText: '',
				longitude: '114.28944',
				latitude: '30.66195',
				apiKey: $config.tianKey,
				winWidth: 0,
				winHeight: 0,
				winTop: 0,
				datalist: [],
				startY: 0,
				selectItem: {},
				iStatusBarHeight: 0,


				siteListArr: [],
				TouchHeight: 0,
				centreText: null,
				centreTextHeight: uni.upx2px(80),


				searchContent: null,
				mapConfig: {},
			}
		},
		created() {
			// getLocation();

			// this.getMapCenterPoint()
		},
		mounted() {
			this.getMapConfig()
			const userLabel = getUUID();
			const refererStr = document.referrer;
			getVisituvpv_Api({
				userLabel,
				refererStr,
			})
			// setTimeout(() => {
			// 	console.log("this.$refs.SelectMapNavigationRef = " , this.$refs.SelectMapNavigationRef)
			// 	this.$refs.SelectMapNavigationRef.open()
			// }, 3000)
			this.disableScroll();
			this.open(this.longitude, this.latitude);
		},
		beforeDestroy() {
			try {
				document.removeEventListener('touchmove');
				document.body.removeEventListener('mousewheel');
				document.body.removeEventListener('DOMMouseScroll');
				document.removeEventListener('onmousewheel', function() {
					window.event.returnValue = false;
				});
			} catch (error) {
				//TODO handle the exception
			}
		},
		watch: {

		},
		methods: {
			async getMapConfig() {
				const res = await getMapConfig_Api()
				console.log('地图配置',res)
				this.mapConfig = res || {}
			},
			async initMaps() {
				console.warn('--------天地图加载完成--------');
				this.$emit('onLoad') 
				try {
					uni.showLoading()
					const { longitude, latitude } = await getLocation();
					// console.log("longitude, latitude = " , longitude, latitude)
					if(longitude && latitude){
						this.longitude = longitude;
						this.latitude = latitude;
						this.movePT({longitude , latitude} , true)
						uni.hideLoading()
						this.handleSearch()
					}else{
						throw new Error()	
					}
						// this.longitude = '114.25497';
						// this.latitude = '30.62832';
						// this.movePT({longitude:this.longitude , latitude:this.latitude} , true)
						// uni.hideLoading()
						// this.handleSearch()
				} catch (error) {
					uni.hideLoading()
					this.getMapCenterPoint()
				} finally{
					this.showMap = true;
				}
			},
			/**
			 * 移动到中心点
			 * PT 点位
			 * refresh 移动之后是否刷新获取数据
			*/
			movePT(PT , refresh = false){
				this.$refs.tiandituMapRefs.SelectedDot({longitude:this.longitude , latitude:this.latitude} , !refresh)
			},
			// 获取地图中心点
			getMapCenterPoint() {
				uni.showLoading()
				getMapCenterPoint_Api().then(res => {
					const {
						longitude,
						latitude,
						mapTypeIcon
					} = res || {};
					this.longitude = longitude;
					this.latitude = latitude;
					this.movePT({longitude , latitude} , true)
					this.handleSearch()
				}).catch(err => {
					this.open(null, null)
				}).finally(() => {
					uni.hideLoading()
				})
			},
			open(lon, lat, mapTypeIcon) {
				if (lon && lat) {
					this.$nextTick(() => {
						this.$refs.tiandituMapRefs.initCharts(lon, lat, mapTypeIcon)
					})
				} else {
					uni.showModal({
						title: '提示',
						content: '地图中心点获取错误，请联系管理员！',
						success: res => {
							// console.log("showModal == ", res)
							if (res.confirm) {}
						}
					})
				}

			},
			handleSearch(val = {}) {
				this.showMap = true;
				const parms = {
					...val,
					longitude: this.longitude,
					latitude: this.latitude,
					radius: 5000
				};
				// 记录搜索框中的内容
				this.SearchText = parms.locationName;
				// 判断是否通过收索
				this.searchDot = parms.search
				// 如果存在收索条件，则去掉 范围 和 中心点
				if (parms.locationName || parms.mapTypeId || parms.areaCode) {
					delete parms.radius
					// delete parms.latitude
					// delete parms.longitude
				}
				delete parms.search;
				this.searchContent = parms
				getMapList_Api(parms).then(res => {
					if (!res || res.length === 0) {
						uni.showToast({
							title: "当前区域无办理点位",
							icon: 'none'
						})
					}
					this.siteListArr = res || [];
					// this.$store.dispatch('map/updateDotInfo')
					// this.$store.dispatch('updateDotInfo')
				}).catch(err => {
					this.siteListArr = [];
				}).finally(() => {
					clearTimeout(this.SearchTimeout)
					this.SearchTimeout = null;
				})
			},


			getScrollHeight(TouchHeight, centreText) {
				const h = centreText ? this.centreTextHeight : 0
				return TouchHeight - h - 15 + 'px'
			},
			disableScroll() {
				if (typeof window.addEventListener === 'function') {
					document.addEventListener('touchmove', function(e) {
						e.preventDefault();
					}, {
						passive: false
					});
					document.body.addEventListener('mousewheel', function(e) {
						e.preventDefault();
					});
					document.body.addEventListener('DOMMouseScroll', function(e) {
						e.preventDefault();
					});
				} else {
					document.attachEvent('onmousewheel', function() {
						window.event.returnValue = false;
					});
				}
			},
			// 点击地图
			handleClickMap() {
				if (this.$refs.TouchboxRef) {
					this.$refs.TouchboxRef.concealList()
				}
			},
			// 点击地图标注点位
			handleMapSite(parmas = {}) {
				// const { Lng, Lat } = parmas;
				const Lng = parmas.Lng || parmas.longitude;
				const Lat = parmas.Lat || parmas.latitude;
				// const item = (this.siteListArr || []).find(el => el.longitude == Lng && el.latitude == Lat);
				// this.checkSiteDetails(item)
				const item = (this.siteListArr || []).find(el => el.longitude == Lng && el.latitude == Lat);

				if (item) {
					this.checkSiteDetails(item);
					this.$refs.tiandituMapRefs.Trenderjs.handleSiteList(this.siteListArr)
				}

			},
			// 查看点位详情
			checkSiteDetails(info) {
				if (info) {
					this.$refs.tiandituMapRefs.Trenderjs.SelectedDot(info, true)
					this.handleClickMap();
					this.$refs.siteDetailsRef.openDetails(info)
				}
			},

			moveMapSearch(parms) {
				console.log('moveMapSearch = ' ,1 )
				const {
					Lng,
					Lat
				} = parms;
				this.longitude = Lng;
				this.latitude = Lat;
				
				if(this.$refs.searchRef){
					this.$refs.searchRef.onSearchFocus()
				}else{
					this.handleSearch()
				}
				// 
				// console.log("moveMapSearch", Lng, Lat)
			},

			// //普通搜索
			// handleSearch(val = {}) {
			// 	const parms = {
			// 		...val,
			// 		longitude: this.longitude,
			// 		latitude: this.latitude,
			// 		radius: 5000
			// 	};
			// 	getMapList_Api(parms).then(res => {
			// 		if (!res || res.length === 0) {
			// 			uni.showToast({
			// 				title: "当前区域无办理点位",
			// 				icon: 'none'
			// 			})
			// 		}
			// 		this.siteListArr = res || [];
			// 	}).catch(err => {
			// 		this.siteListArr = [];
			// 	})
			// },

			close() {
				this.visible = false
			},
			onConfirm() {
				if (Object.keys(this.selectItem).length) {
					this.visible = false
					this.$emit('onSelect', this.selectItem)
				} else {
					tools.createMessage('请选择位置')
				}
			},
			upDateLonLat(lon, lat) {
				if (lon && lat) {
					this.$refs.tiandituMapRefs.upDataCharts(lon, lat)
				} else {
					console.error('请传入lon, lat')
				}
			},
			tianidtuSearch(value) {
				if (value.city) {
					this.cityInfoSearch(value)
				} else {
					this.infoSearch(value)
				}
			},
			async infoSearch(value) { // 地理编码查询
				let params = {
					ds: {
						"keyWord": value.keyword,
					},
					tk: this.apiKey,
				}
				let resData = await tools.createRequest('https://api.tianditu.gov.cn/geocoder', params, true)
				if (resData.status === '0') {
					const location = resData.location
					const formateOne = tools.formatterAdressLocation(resData, 3)
					this.datalist = [formateOne]
					this.selectItem = datalist
					this.$refs.tiandituMapRefs.upDataCharts(location.lon, location.lat)
				}
			},
			async cityInfoSearch(value) { // 地名搜索2.0
				let params = {
					postStr: {
						"keyWord": value.keyword,
						"queryType": 12,
						"start": 0,
						"count": 10,
						"specify": value.city.value
					},
					type: 'query',
					tk: this.apiKey,
				}
				let resData = await tools.createRequest('https://api.tianditu.gov.cn/v2/search', params, true)
				if (resData.status.infocode === 1000) {
					const {
						pois: aPoints,
						count
					} = resData
					if (count === '0' || !aPoints || !aPoints.length) {
						return tools.createMessage('没有找到该地址')
					}
					const {
						pois,
						keyWord,
						lonlat
					} = aPoints[0]
					const formateData = aPoints.map((item) => tools.formatterAdressLocation(item, 2))
					this.datalist = formateData
					this.selectItem = formateData[0]
					const [lon, lat] = lonlat.split(',')
					this.$refs.tiandituMapRefs.upDataCharts(lon, lat)
				} else {
					tools.createMessage('数据异常', 1000, false, 'error')
				}
			},
			selectListItem(item) {
				this.$refs.tiandituMapRefs.upDataCharts(item.location.lon, item.location.lat)
			},
			selectPoint(e) {
				this.domMinHeight = '0vh'
				this.datalist = [e]
				this.selectItem = e
			},

			// start(e) {
			// 	const clientY = e.changedTouches[0].clientY
			// 	this.startY = clientY
			// },
			// end(e) {
			// 	const transformY = e.changedTouches[0].clientY - this.startY;
			// 	switch (true) {
			// 		case transformY > 50:
			// 			console.log('下划')
			// 			this.domMaxHeight = '20vh'
			// 			this.domMinHeight = '0vh'
			// 			break;
			// 		case transformY < -50:
			// 			console.log('上划')
			// 			this.domMaxHeight = '50vh'
			// 			this.domMinHeight = '50vh'
			// 			break;
			// 		default:
			// 			break;
			// 	}

			// },
			selectCard(item) {
				this.domMaxHeight = '20vh'
				this.domMinHeight = '0vh'
				this.selectItem = item
				this.selectListItem(item)
			},



			setTouchHeight(val) {
				// console.log('setScrollHeight = ', val)
				// 实时返回的滑动组件高度
				this.TouchHeight = val;
			},
			setScrollMaxHeight(val) {
				//最大高度
				this.scrollMaxHeight = val;
			},

			// 页面跳转
			goPages() {
				// 'feedback'
				uni.navigateTo({
					url: "/pages/feedback/feedback"
				})
			}

		}
	}
</script>



<style lang="scss" scope>
	.map-box {
		width: 100vw;
		height: 100vh;
		/* 		position: fixed;
		left: 0;
		top:0;
		right: 0;
		bottom: 0; */
	}



	.mask {
		/* overflow: hidden; */
		position: fixed;
		left: 0;
		background-color: #FFFFFF;
		z-index: 399;
	}

	/* footer */
	.list-boxd {
		position: absolute;
		bottom: 0;
		left: 0;
		z-index: 401;
		right: 0;
		border-radius: 14px 14px 0 0;
		background: #FFFFFF;
		transition: all 1s;
	}

	.list-header {
		height: 20px;
		position: relative;
		border-bottom: 1px solid #f3f4f6;
		cursor: pointer;
	}

	.list-header::after {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		content: '';
		height: 6px;
		width: 60px;
		border-top: 1px solid #e8e8e8;
		border-bottom: 1px solid #e8e8e8;
	}

	.list-content {
		max-height: 50vh;
		overflow-y: scroll;
	}

	.card {
		min-height: 44px;
		padding: 12px;
		position: relative;
		display: flex;
		justify-content: space-between;
		align-items: center;

	}

	.card-left {
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.card-right {
		padding-right: 10px;
	}

	.arrow {
		border-top: 2px solid #666666;
		border-right: 2px solid #666666;
		width: 10px;
		height: 10px;
		transform: rotate(45deg);
	}


	.card:active {
		background-color: #f3f4f6;
	}


	.card::after {
		position: absolute;
		content: '';
		bottom: 0;
		height: 1px;
		background-color: #e8e8e8;
		width: 90%;
	}

	.card:last-child::after {
		height: 0;
		background-color: #FFFFFF;
	}

	.card-title {
		font-size: 18px;
	}

	.card-text {
		color: #e8e8e8;
		font-size: 13px;
	}

	.centre-box {
		max-width: 100%;
		height: 77rpx;
		padding: 0 30rpx;
		display: inline-flex;
		align-items: center;

		.position-icon {
			flex-shrink: 0;
			width: 36rpx;
			margin-right: 10rpx;

			path {
				fill: #929292;
			}
		}

		text {
			flex-shrink: 0;
			font-size: 26rpx;
			color: #666666;
			font-weight: 700;
		}

		.text-val {
			flex: 1;
			flex-shrink: 0;
			color: #0090FF;
			padding: 0 5rpx;
			// display: flex;
			// align-items: center;

			// .text {
			// 	flex-shrink: 0;
			// 	flex: 1;
			// 	color: #329BF9;
			// 	padding: 0 5rpx;
			// }

			// font-size: 24rpx; 
			// color: #329BF9;
			// padding: 0 5rpx; 
			// // .one-row{
			// // 	width: auto;
			// // flex: 1;
			// // }
		}

	}
</style>