<template>
	<view class="page" :style="{ height: pageHeight + 'px', flexDirection: flexDirection }">
		<view id="map" :style="{ height: pageHeight + 'px' }" class='map' />

		<!-- <view class="fab">
			<uni-fab ref="fab" :pattern="fab.pattern" :content="fab.content" :horizontal="fab.horizontal"
				:vertical="fab.vertical" :direction="fab.direction" @trigger="trigger" @fabClick="fabClick" />
		</view> -->

		<view v-show="popupShow" :style="{ height: popupHeight + 'px' }" class="popup">
			<scroll-view :scroll-top="0" scroll-y="true" :style="{ height: popupHeight + 'px' }" class="scroll-Y">
				<uni-list v-for="(item, index) in players" :key="index" :border="true">
					<!-- 右侧带角标 -->
					<!-- <uni-list-chat :title="item.name" avatar="https://web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png"
					note="您收到一条新的消息" time="2020-02-02 20:20" badge-text="12"></uni-list-chat> -->
					<uni-list-item
						:title="item.name + ' 打点数: ' + item.effectivenum + ' / ' + item.totalcontrolnum + ' 距离: ' + item.distance + '米 配速: ' + item.pace"
						:note="'平均心率: ' + item.avghr + ' 最大心率: ' + item.maxhr + ' CAL: ' + item.calorie + ' Ck: ' + item.ck + ' Ei: ' + item.ei">
					</uni-list-item>
				</uni-list>
			</scroll-view>
		</view>

	</view>
</template>

<script module="leaflet" lang="renderjs">
	import 'leaflet/dist/leaflet.css'
	import '@/utils/map/leafletHelper.css'

	// import mapHelper from '@/utils/mapHelper'
	import leafletHelper from '@/utils/map/leafletHelper'

	export default {
		components: {},
		// data() {
		// 	return {},
		// },
		// mounted() {
		// 	uni.$on('myEvent', this.myEventHandler);
		// },
		// destroyed() {
		// 	uni.$off('myEvent', this.myEventHandler);
		// },
		beforeDestroy() {
			// console.log("beforeDestroy")
			// clearInterval(this.interval)
			leafletHelper.free()
		},
		methods: {
			// myEventHandler(data) {
			// 	console.log('视图层接收到数据：', data);
			// },
			initMap() {
				// leafletHelper.init(this, 'map', [36.67175772119628, 117.12792580603369], 17)

				// const mapid = this.actionDetail.mapinfo.lid
				const mapurl = this.actionDetail.mapinfo.mapurl
				const centPoint = [this.actionDetail.mapinfo.centerlatitude, this.actionDetail.mapinfo.centerlongitude]
				const zoomNum = this.actionDetail.mapinfo.defscale
				leafletHelper.init(this, 'map', centPoint, zoomNum)
				leafletHelper.addMapLayer(mapurl)
			},
			handleMapDrawRoute() {
				// leafletHelper.global.setCheckPoints(this.checkPoints)
				leafletHelper.global.setRoutes(this.actionDetail.routesList)

				// leafletHelper.checkPoint.drawAllCheckPoints()
				// leafletHelper.checkPoint.drawPath()
				leafletHelper.route.drawAllRoutes()
				leafletHelper.route.drawAllPath()
			},
			handleMapDrawPlayer() {
				leafletHelper.global.setPlayers(this.players)
				leafletHelper.global.setPlayersPosition(this.players_position)
				leafletHelper.player.drawAllPlayers()
				// leafletHelper.player.drawOnePlayer(2)
				// leafletHelper.player.drawOnePlayer(3)

				leafletHelper.player.dealStaleData()
			},
			handleMapDrawTrail() {
				// leafletHelper.player.drawOneTrail(2, 10000)
				// leafletHelper.player.drawOneTrail(3, 10000)
				// leafletHelper.player.drawOneTrail(2, 0, false)
				leafletHelper.player.drawAllTrails(3000)
			},
			handleMapToggle() {
				// leafletHelper.checkPoint.toggle(true)
				leafletHelper.route.toggle(true)
				leafletHelper.player.togglePlayer(true)
				leafletHelper.player.toggleTooltip(true)
				leafletHelper.player.toggleTrail(true)
			},
		},
	}
</script>

<script>
	import {
		DefaultRequest,
		IdRequest
	} from "@/grpc/base_pb.js"


	export default {
		components: {},
		data() {
			return {
				interval: null,

				systemInfo: null,
				deviceOrientation: 'portrait', // 设备方向（竖屏 portrait | 横屏 landscape）
				flexDirection: 'column',
				pageHeight: 0,
				// mapHeight: 0,
				popupHeight: 0,
				popupHeightPortrait: 200,	// 竖屏状态下的底部弹框高度
				popupType: 'bottom',
				popupShow: false,

				actionId: 2,
				actionDetail: {},
				mapUrl: null,
				mapInfo: {},

				map: null,
				checkPoints: [],
				players: [],
				players_position: [],
			}
		},
		computed: {},
		mounted() {},
		onLoad() {
			// 逻辑层中触发自定义事件
			// uni.$emit('myEvent', {
			// 	name: 'Uniapp',
			// 	version: '2.0.0'
			// })
			this.loadData(this.actionId)
		},
		onReady() {
			this.layoutInit()
		},
		onShow() {
			// console.log('[onShow]')
			uni.onWindowResize(res => {
				// console.log('[onWindowResize]', res)
				this.layoutInit(res.size)
			});
		},
		beforeDestroy() {
			// console.log("beforeDestroy")
			clearInterval(this.interval)
			// leafletHelper.free()
		},
		methods: {
			// 布局初始化 设置地图高度
			layoutInit(windowSize = '') {
				var windowHeight, windowWidth

				if (windowSize == '') {
					this.systemInfo = uni.getSystemInfoSync()
					// console.log('[layoutInit] systemInfo', this.systemInfo)
					windowHeight = this.systemInfo.windowHeight
					windowWidth = this.systemInfo.windowWidth
				} else {
					windowHeight = windowSize.windowHeight
					windowWidth = windowSize.windowWidth
				}
				this.pageHeight = windowHeight

				if (windowHeight > windowWidth) {
					console.log('[layoutInit] 竖屏')
					this.deviceOrientation = 'portrait'
					this.flexDirection = 'column'
					this.popupHeight = this.popupHeightPortrait
					// if (this.popupShow) {
					// 	this.mapHeight = this.pageHeight - this.popupHeight
					// } else {
					// 	this.mapHeight = this.pageHeight
					// }
				} else { // 横屏
					console.log('[layoutInit] 横屏')
					this.deviceOrientation = 'landscape'
					this.flexDirection = 'row'
					this.popupHeight = this.pageHeight
					// this.mapHeight = this.pageHeight
				}

			},
			popupToggle() {
				// console.log('[popupToggle]')
				this.popupShow = !this.popupShow
			},
			async loadData() {
				this.actionDetail = await this.getToActionDetail(this.actionId)
				uni.setNavigationBarTitle({
					title: this.actionDetail.name
				});
				// console.log(this.actionDetail)

				this.initMap()
				this.handleMapDrawRoute()

				if (this.interval != null) {
					clearInterval(this.interval)
				}

				let that = this
				that.players = await that.getToUsersInGameDetail(that.actionId)
				// console.log('players', that.players)
				// leafletHelper.global.setPlayers(this.players)

				that.players_position = await that.getToUsersInGameGpsQuery(that.actionId)
				// leafletHelper.global.setPlayersPosition(this.players_position)

				that.handleMapDrawPlayer()
				that.handleMapDrawTrail()

				this.interval = setInterval(async function() {
					that.players = await that.getToUsersInGameDetail(that.actionId)
					that.players_position = await that.getToUsersInGameGpsQuery(that.actionId)
					//// leaflet.leafletHelper.global.setPlayers(that.players)
					// leafletHelper.global.setPlayersPosition(that.players_position)
					that.handleMapDrawPlayer()
				}, 1000);

				// await mapHelper.handleMapInfo(this, this.mapInfo)
				this.handleMapToggle()
			},
			//场控端_活动详情
			async getToActionDetail(actId) {
				try {
					return new Promise((resolve, reject) => {
						// 创建请求参数并赋值
						var request = new IdRequest()
						request.setId(actId)
						// 调用客户端相应的grpc方法，发送grpc请求，并接受后台发送回来的返回值
						this.$client.toActionDetail(request, {}, (err, response) => {
							if (err) {
								console.log(`[toActionDetail] err: code = ${err.code}` +
									`, message = "${err.message}"`)
								reject(err)
							} else {
								let res = response.toObject()
								console.log('[toActionDetail]', res)
								resolve(res)
							}
						})
					});
				} catch (e) {
					console.log('[getToActionDetail] err', e)
					reject(e)
				}
			},
			//场控端_正在进行中所有用户实时信息
			async getToUsersInGameDetail(actId) {
				try {
					return new Promise((resolve, reject) => {
						// 创建请求参数并赋值
						var request = new IdRequest()
						request.setId(actId)
						// 调用客户端相应的grpc方法，发送grpc请求，并接受后台发送回来的返回值
						this.$client.toUsersInGameDetail(request, {}, (err, response) => {
							if (err) {
								console.log(`[toUsersInGameDetail] err: code = ${err.code}` +
									`, message = "${err.message}"`)
								reject(err)
							} else {
								let res = response.toObject()
								// console.log('[toUsersInGameDetail]', res)
								resolve(res.usersList)
							}
						})
					});
				} catch (e) {
					console.log('[getToUsersInGameDetail] err', e)
					reject(e)
				}
			},
			//场控端_正在进行中所有用户实时gps查询
			async getToUsersInGameGpsQuery(actId) {
				try {
					return new Promise((resolve, reject) => {
						// 创建请求参数并赋值
						var request = new IdRequest()
						request.setId(actId)
						// 调用客户端相应的grpc方法，发送grpc请求，并接受后台发送回来的返回值
						this.$client.toUsersInGameGpsQuery(request, {}, (err, response) => {
							if (err) {
								console.log(`[toUsersInGameGpsQuery] err: code = ${err.code}` +
									`, message = "${err.message}"`)
								reject(err)
							} else {
								let res = response.toObject()
								// console.log('[toUsersInGameGpsQuery]', res)
								resolve(res.gpsinfoList)
							}
						})
					});
				} catch (e) {
					console.log('[getToUsersInGameGpsQuery] err', e)
					reject(e)
				}
			},
			// trigger(e) {
			// 	console.log(e)
			// 	this.content[e.index].active = !e.item.active
			// 	uni.showModal({
			// 		title: '提示',
			// 		content: `您${this.content[e.index].active ? '选中了' : '取消了'}${e.item.text}`,
			// 		success: function(res) {
			// 			if (res.confirm) {
			// 				console.log('用户点击确定')
			// 			} else if (res.cancel) {
			// 				console.log('用户点击取消')
			// 			}
			// 		}
			// 	})
			// },
			// fabClick() {
			// 	uni.showToast({
			// 		title: '点击了悬浮按钮',
			// 		icon: 'none'
			// 	})
			// },
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		// background-color: red;
		display: flex;
	}

	.map {
		flex: 1 1 auto;
		background-color: white;
		z-index: 0;
		// display: flex;
		// justify-content: center;
		// align-items: center;
	}

	.popup {
		// height: 200px;
		overflow: hidden;
	}

	.scroll-Y {
		// height: 100vh;
	}

	// .fab {
	// 	z-index: 1000;
	// 	width: 20px;
	// }
</style>