<template>
	<view class="body">
		<view class="content uni-column">
			<view class="uni-column top" :style="getBannerStyle(matchBanner)">
				<my-topbar :title="compName" @btnBackClick="btnBack"></my-topbar>
				<view class="top-content uni-row">
				</view>
			</view>

			<view class="main uni-column">
				<view class="selectBox uni-row uni-jcse">
					<view class="select">
						<e-select v-model="selectMap.selectValue" maxHeight="300px" :options="selectMap.data"
							:search="false" :inputClick="false" :clearable="false" @getText="getESelectText"
							@change="eSelectChange"></e-select>
					</view>
					<view class="select">
						<e-select v-model="selectPlan.selectValue" maxHeight="300px" :options="selectPlan.data"
							:search="false" :inputClick="false" :clearable="false" @getText="getESelectText"
							@change="eSelectChange"></e-select>
					</view>
				</view>

				<view id="map" class="map"></view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapGetters
	} from 'vuex';
	import tools from '/utils/tools.js';
	import 'leaflet/dist/leaflet.css';
	import '@/utils/map/leafletHelper.css'
	import leafletHelper from '@/utils/map/leafletHelper';

	export default {
		data() {
			return {
				queryObj: {},
				queryString: "",
				interval: null,
				
				compName: "小飞龙系列定向赛",
				matchBanner: "static/banner/banner1.png",
				selectMap: {
					selectValue: 1,
					data: [{
							text: "中心校区",
							value: 1
						},
						{
							text: "千佛山校区",
							value: 2
						},
						{
							text: "兴隆校区",
							value: 3
						}
					]
				},
				selectPlan: {
					selectValue: 1,
					data: [{
							text: "千佛山校区南门",
							value: 1
						},
						{
							text: "千佛山校区北门",
							value: 2
						},
						{
							text: "15点位路线",
							value: 3
						}
					]
				},
				
				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: 0,
			}
		},
		computed: {
			...mapState([
				'username', // 映射 this.username 为 store.state.username
				'token'
			]),
			...mapGetters([
				'metadata'
			]),
		},
		onLoad(query) {
			// console.log(query);
			this.queryObj = query;
			this.queryString = tools.objectToQueryString(this.queryObj);
			// console.log(queryString);
		},
		mounted() {
			this.initMap();
		},
		beforeDestroy() {
			// console.log("beforeDestroy")
			// clearInterval(this.interval)
			leafletHelper.free()
		},
		methods: {
			reLoad() {
				this.savePlayersData()
				
				var fullPath = this.$route.fullPath
				console.log("[windowResize] reLaunch: " + fullPath)
				uni.redirectTo({
					url: fullPath
				});
			},
			popupToggle() {
				this.popupShow = !this.popupShow
				this.$store.commit('setMapPopupShow', this.popupShow)
				// this.layoutInit()
			},
			initMap() {
				const mapUrl = 'http://192.168.0.22:5173/actMgt/static/test/华山西北-描边.jpg';
				// const center = [this.actionDetail.mapinfo.centerlatitude, this.actionDetail.mapinfo.centerlongitude]
				// const zoomNum = this.actionDetail.mapinfo.defscale
				const zoomNum = 15;
				const mapOptions = {
					// center: center,
					zoom: zoomNum
				};
				leafletHelper.init(this, 'map', mapUrl, mapOptions);
			},
			async loadData() {
				this.actionDetail = await this.getToActionDetail(this.actionId)
				uni.setNavigationBarTitle({
					title: this.actionDetail.name
				});
				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();
			},
			handleWindowResize() {
				leafletHelper.onWindowResize()
			},
			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() {
				this.trailTime = leafletHelper.config.trailTime
				// 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)
				
				leafletHelper.route.toggle(this.$store.state.mapControlRoute)
				leafletHelper.player.togglePlayer(this.$store.state.mapControlPlayer)
				leafletHelper.player.toggleTooltip(this.$store.state.mapControlTooltip)
				leafletHelper.player.toggleTrail(this.$store.state.mapControlTrail)
			},
			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
			},
			// 页面reLoad前调用本方法，将用户数据先保存，页面重载后再进行数据恢复
			savePlayersData() {
				leafletHelper.global.savePlayersData()
			},
			//场控端_活动详情
			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)
				}
			},
			onActionChange(e) {
				const value = e.detail.value
				console.log("onActionChange", value)
			},
			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'
					})
				}
			},
			fullScreenToggle() {
				this.$global.fullscreen();
				// this.layoutInit();
			},
			getBannerStyle(bannerUrl) {
				console.log("getBannerStyle bannerUrl", bannerUrl);
				let style = "";
				if (bannerUrl.length > 0) {
					style = `background-image: url("${bannerUrl}");`;
				}
				console.log("getBannerStyle", style);
				return style;
			},
			// 获取输入框中值
			getESelectText(data) {
				// console.log("getESelectText:", data);
			},
			// 获取选择选项值
			eSelectChange(data) {
				// console.log("eSelectChange:", data);
			},
			btnBack() {
				const url = "/pages/actManage/actDetail?" + this.queryString;
				tools.appAction(url, "uni.navigateTo");
			},
		}
	}
</script>

<style scoped>
	.content {
		height: 100vh;
	}
	
	.top {
		height: 36px;
		padding-top: 16px;
		flex-shrink: 0;
		background-repeat: no-repeat;
		background-size: cover;
	}

	.selectBox {
		width: 100%;
		margin-top: 5px;
		margin-bottom: 5px;
	}

	.select {
		width: 48%;
	}

	.map {
		width: 100%;
		flex: 1 1 auto;
		background-color: white;
		z-index: 0;
	}
</style>