<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="extraIcon" class="popup">
			<scroll-view :scroll-top="0" scroll-y="true"
				:style="{ height: popupHeight + 'px', width: popupWidth + 'px' }" class="scroll-Y">
				<uni-list v-for="(item, index) in players" :key="index" :border="true" class="list">

					<!-- <uni-list-item :show-extra-icon="true" :extra-icon="{color: '#4cd964', size: '22', type: 'spinner'}"
						:title="'(' + (index+1) + ') ' + item.name + ' 打点: ' + item.effectivenum + ' / ' + item.totalcontrolnum + ' 距离: ' + item.distance + '米 配速: ' + item.pace"
						:note="'平均心率: ' + item.avghr + ' 最大心率: ' + item.maxhr + ' CAL: ' + item.calorie + ' Ck: ' + item.ck + ' Ei: ' + item.ei"
						:clickable="true" @click="onPlayerListItemClick(item)" :class="{ 
							'list-item': focusPlayerId != item.id,
							'list-item-focus': focusPlayerId == item.id 
							}">
					</uni-list-item> -->

					<uni-list-item :clickable="true" @click="onPlayerListItemClick(item)" class="list-item" :class="{ 
							'list-item-focus': focusPlayerId == item.id 
							}">
						<template v-slot:header>
							<!-- <image class="slot-image" src="/static/logo.png" mode="widthFix"></image> -->
							<div class="slot-image" :style="'background-color:' + getPlayerColor(item.id)"></div>
						</template>
						<template v-slot:body>
							<view class="slot-box">
								<view class="slot-title">
									[{{index+1}}] <span class="slot-phone" @click="onPhoneClick(item.phone)">
										{{item.name}} </span>
									打点 {{item.effectivenum}}/{{item.totalcontrolnum}} 距离
									{{item.distance}}米 配速 {{item.pace}}
								</view>
								<view class="slot-note">
									心率 {{item.lasthr}} 平均 {{item.avghr}} 最大 {{item.maxhr}} | CAL
									{{Math.round(item.calorie/1000)}} Ck {{Math.round(item.ck/1000)}} Ei {{Math.round(item.ei*100)/100}}
								</view>
							</view>
						</template>
						<!-- <template v-slot:footer>
							<image class="slot-image" src="/static/logo.png" mode="widthFix"></image>
						</template> -->
					</uni-list-item>
				</uni-list>
			</scroll-view>
		</view>

	</view>
</template>

<script>
	import { mapState, mapGetters } from 'vuex'
	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,
				pageWidth: 0,
				// mapHeight: 0,
				popupHeight: 0,
				popupWidth: 0,
				popupHeightPortrait: 300, // 竖屏状态下的底部弹框高度
				popupWidthlandscape: 390, // 横屏状态下的右侧弹框宽度
				popupType: 'bottom',
				popupShow: false,
				extraIcon: {
					color: '#4cd964',
					size: '22',
					type: 'gear-filled'
				},

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

				map: null,
				checkPoints: [],
				players: [],
				players_position: [],
				focusPlayerId: 0,
				trailTime: 90000,
			}
		},
		computed: {
			...mapState([
				'username',	// 映射 this.username 为 store.state.username
			]),
			...mapGetters([
				'metadata'
			]),
		},
		mounted() {},
		onLoad(option) {
			// console.log('[mapShow] onLoad')
			// console.log(option.actionId)
			if (option.actionId > 0) {
				this.actionId = option.actionId
				this.loadData(this.actionId)
			}
			// 逻辑层中触发自定义事件
			// uni.$emit('myEvent', {
			// 	name: 'Uniapp',
			// 	version: '2.0.0'
			// })
		},
		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: {
			// 全屏展示
			fullscreen() {
				if (document.fullscreenElement || document.webkitFullScreenElement || document.mozFullScreenElement ||
					document.msFullScreenElement) {
					// alert('当前是全屏')
					if (document.webkitCancelFullScreen) {
						document.webkitCancelFullScreen();
					} else if (document.mozCancelFullScreen) {
						document.mozCancelFullScreen();
					} else if (document.exitFullscreen) {
						document.exitFullscreen();
					} else {
						uni.showToast({
							title: '浏览器不支持全屏API或已被禁用',
							icon: 'none'
						})
					}
				} else {
					let elem = document.body;
					if (elem.webkitRequestFullScreen) {
						elem.webkitRequestFullScreen();
					} else if (elem.mozRequestFullScreen) {
						elem.mozRequestFullScreen();
					} else if (elem.requestFullScreen) {
						elem.requestFullscreen();
					} else {
						uni.showToast({
							title: '浏览器不支持全屏API或已被禁用',
							icon: 'none'
						})
					}
				}
			},
			// 布局初始化 设置地图高度
			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
				this.pageWidth = windowWidth

				if (windowHeight > windowWidth) {
					console.log('[layoutInit] 竖屏')
					this.deviceOrientation = 'portrait'
					this.flexDirection = 'column'
					this.popupHeight = this.popupHeightPortrait
					this.popupWidth = this.pageWidth
					// 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.popupWidth = this.popupWidthlandscape
					// this.mapHeight = this.pageHeight
				}

			},
			popupToggle() {
				this.popupShow = !this.popupShow
			},
			fullScreenToggle() {
				this.fullscreen()
				this.layoutInit()
			},
			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()
					that.handleMapDrawTrail()
				}, 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, this.metadata, (err, response) => {
							if (err) {
								console.warn(`[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, this.metadata, (err,
							response) => {
								if (err) {
									console.warn(`[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, this.metadata, (err,
							response) => {
								if (err) {
									console.warn(`[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)
				}
			},
			onPlayerListItemClick(item) {
				// console.log("onListItemClick", item)
				this.handlePlayerListItemClick(item)
			},
			onPhoneClick(phoneNumber) {
				if (phoneNumber.length == 11) {
					uni.makePhoneCall({
						phoneNumber: phoneNumber
					})
				} else {
					uni.showToast({
						title: '手机号码不正确',
						icon: 'none'
					})
				}
			}
			// 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>

<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.global.dealStaleData()
			},
			handleMapDrawTrail() {
				// leafletHelper.player.drawOneTrail(2, 10000)
				// leafletHelper.player.drawOneTrail(3, 10000)
				// leafletHelper.player.drawOneTrail(2, 0, false)
				leafletHelper.player.drawAllTrails(this.trailTime)
			},
			handleMapToggle() {
				// leafletHelper.checkPoint.toggle(true)
				leafletHelper.route.toggle(true)
				leafletHelper.player.togglePlayer(true)
				leafletHelper.player.toggleTooltip(true)
				leafletHelper.player.toggleTrail(true)
			},
			handlePlayerListItemClick(item) {
				this.focusPlayerId = item.id
				leafletHelper.player.handleFocusPlayer(this.focusPlayerId)
			},
			getPlayerColor(playerId) {
				if (playerId != this.focusPlayerId)
					return leafletHelper.player.getPlayerColor(playerId)
				else
					return leafletHelper.config.gStyle.marker.focus.fillColor
			}
		},
	}
</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;
	}

	.list {}

	.list-item {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		height: 60px;
	}

	.list-item-focus {
		background-color: #fffaef;
	}

	.slot-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		align-items: flex-start;
	}

	.slot-image {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		margin-right: 10px;
		width: 6px;
		height: 39px;
		align-self: center;
	}

	.slot-title {
		flex: 1;
		font-size: 14px;
		color: #424242;
		// margin-right: 10px;
	}

	.slot-note {
		flex: 1;
		font-size: 12px;
		color: #7d8da7;
		// margin-right: 10px;
	}

	.slot-phone {
		padding: 0 5px;
		color: #000;
		font-weight: bold;
	}

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