<!-- 
[报名] 样式2 - 排名总览
http://localhost:5173/card/#/pages/bm/style2/rankOverview
https://oss-mbh5.colormaprun.com/card/#/pages/bm/style2/rankOverview
 -->
<template>
	<view class="body">
		<view class="content">
			<view class="uni-column" :class="cssTop">
				<view class="topbar uni-row" :class="cssTopbarColor">
					<!-- <image mode="aspectFit" class="topbar-back" @click="btnBack" src="/static/default/back.png"></image> -->
					<text class="topbar-back" @click="btnBack">&lt;</text>
					<text class="mcName" @click="playMusic">{{mcName}}</text>
					<text class="topbar-rule" @click="btnInfo">规则</text>
					<!-- <image mode="aspectFit" class="topbar-info" @click="btnInfo" src="/static/default/info.png"></image> -->
				</view>

				<view class="topbtm uni-column">
					<text class="topbtm-name">姓名：{{nickName}}</text>
				</view>
			</view>
			<view class="top-oval">
				<text class="top-oval-text" @click="onOverviewClick('totalNum')">点击查看排行榜</text>
			</view>

			<view class="mid uni-column">
				<view class="mid-1 uni-row uni-jcsb">
					<view class="overview-1 uni-column" @click="onOverviewClick('totalDistanct')">
						<text class="ovline1">总距离 {{fmtDistanct(totalDistanct)}} km</text>
						<text class="ovline2">第 {{totalDistanctRankNum > 0 ? totalDistanctRankNum : '- -'}} 名</text>
					</view>
					<view class="overview-2 uni-column" @click="onOverviewClick('totalNum')">
						<text class="">总场次 {{totalNum}}</text>
					</view>
					<view class="overview-3 uni-column" @click="onOverviewClick('totalCp')">
						<text class="ovline1">总打点数 {{totalCp}} 个</text>
						<text class="ovline2">第 {{totalCpRankNum > 0 ? totalCpRankNum : '- -'}} 名</text>
					</view>
				</view>
				<view class="mid-2 uni-row uni-jcse">
					<view class="overview-4 uni-column" @click="onOverviewClick('totalSysPoint')">
						<text class="ovline1">总百味豆 {{totalSysPoint}} 个</text>
						<text class="ovline2">第 {{totalSysPointRankNum > 0 ? totalSysPointRankNum : '- -'}} 名</text>
					</view>
					<view class="overview-5 uni-column" @click="onOverviewClick('fastPace')">
						<text class="ovline1">最快配速 {{fmtPace(fastPace)}}</text>
						<text class="ovline2">第 {{fastPaceRankNum > 0 ? fastPaceRankNum : '- -'}} 名</text>
					</view>
				</view>
			</view>

			<view class="main uni-column">
				<text class="main-title">选择比赛路线</text>
				<view class="main-path uni-row">
					<view v-for="(item, index) in pathList.row1" :key="'row1-' + index">
						<image mode="aspectFit" class="pathimg" :src="item.img" @click="onPathImgClick(item)"></image>
					</view>
				</view>
				<view class="main-path uni-row">
					<view v-for="(item, index) in pathList.row2" :key="'row2-' + index">
						<image mode="aspectFit" class="pathimg" :src="item.img" @click="onPathImgClick(item)"></image>
					</view>
				</view>
			</view>

			<my-popup ref="mypopup" :dataList="popupDataList" :acttime="acttime"></my-popup>
			<!-- <my-popup-map ref="mypopupmap" :point="navPoint"></my-popup-map> -->
		</view>
	</view>
</template>

<script>
	import tools from '/common/tools';
	import {
		defaultPopUpDataList
	} from '/common/define';
	import {
		token,
		apiMatchRsDetailQuery,
		apiCardConfigQuery,
		checkResCode
	} from '/common/api';

	export default {
		data() {
			return {
				// audioSrc: "/static/audio/2.mp3",
				// audioSrc: "https://oss-mbh5.colormaprun.com/card/static/audio/2.mp3",
				audioSrc: "http://t-oss-mbh5.colormaprun.com/card/static/audio/2.mp3",
				pageName: "rankOverview",
				firstEnterKey: 'firstEnter-bm-style2',
				rankKey: "rank-bm-style2",
				queryObj: {},
				queryString: "",
				token: "",

				ecId: 0, // 卡片id
				mcId: 0, // 赛事id
				mcType: 0, // 赛事类型 1 普通活动 2 线下赛 3 线上赛
				mcName: "", // 赛事名称
				acttime: "", // 活动时间
				beginSecond: null, // 活动或赛事开始时间戳，单位秒
				endSecond: null, // 活动或赛事结束时间戳，单位秒
				nickName: "", // 昵称
				totalNum: null, // 总场次
				totalDistanct: null, // 总距离,单位米
				totalDistanctRankNum: null, // 总距离排名
				totalCp: null, // 总打点数
				totalCpRankNum: null, // 总打点数排名
				totalSysPoint: null, // 总百味豆
				totalSysPointRankNum: null, // 总百味豆排名
				fastPace: null, // 个人最快配速
				fastPaceRankNum: null, // 个人最快配速排名
				ocaRs: [], // 卡片对应活动集合

				interval: null,
				mcState: 0, // 赛事/活动状态 0: 未开始  1: 进行中  2: 已结束
				cssTop: "",
				cssTopbarColor: "",
				pathList: {},
				popupDataList: [],
				navPoint: {},
			}
		},
		computed: {},
		onLoad(query) { // 类型非必填，可自动推导
			// console.log("query:", query);
			this.queryObj = query;
			// this.queryString = tools.objectToQueryString(this.queryObj);
			// console.log(queryString);
			this.token = query["token"] ?? token;
			this.ecId = query["id"] ?? 0;

			this.firstEnterKey += "-" + this.ecId;
			console.log("firstEnterKey:", this.firstEnterKey);

			this.rankKey += "-" + this.ecId;
			console.log("rankKey:", this.rankKey);

			tools.removeCssCode();

			this.getCardConfigQuery();
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {
			// this.dealFirstEnter();
			// this.playMusic();
		},
		onShow() {
			// uni.showToast({
			// 	icon: "none",
			// 	title: "[rankOverview] onShow"
			// })
			// if (this.$audio.audioStatus == 2 && this.$audio.audioSrc == this.audioSrc) {
			// 	this.$audio.play();
			// }
		},
		onUnload() {
			this.clear();
		},
		methods: {
			playMusic() {
				return;
				// uni.showToast({
				// 	title: 'playMusic',
				// 	icon: 'none',
				// 	duration: 2000
				// });
				if (this.$audio.audioStatus == 0 || this.$audio.audioSrc != this.audioSrc) {
					this.$audio.playAudio(this.audioSrc);
				}
			},
			dealNotice(rank) {
				// console.log('[dealFirstEnter]');
				let that = this;
				uni.getStorage({
					key: that.rankKey,
					success: (res) => {
						console.log('[getStorage]', that.rankKey, res.data);
						const oldRank = res.data;
						if (oldRank != rank) {
							// that.notice = true;
							that.setRankValue(rank);
						}
					},
					fail: (e) => {
						console.log('[getStorage] fail', that.rankKey, e);
						// that.notice = false;
						that.setRankValue(rank);
					},
				})
			},
			setRankValue(data) {
				let that = this;
				uni.setStorage({
					key: that.rankKey,
					data: data,
					success: () => {
						console.log('[setStorage] success', that.rankKey, data);
					},
					fail: (e) => {
						console.log('[setStorage] fail', that.rankKey, e);
					},
				})
			},
			dealFirstEnter() {
				// console.log('[dealFirstEnter]');
				let that = this;
				uni.getStorage({
					key: that.firstEnterKey,
					success: (res) => {
						console.log('[getStorage]', that.firstEnterKey, res.data);
					},
					fail: (e) => {
						console.log('[getStorage] fail', that.firstEnterKey, e);
						that.btnInfo();
						that.setFirstEnterValue(true);
					},
				})
			},
			setFirstEnterValue(data) {
				let that = this;
				uni.setStorage({
					key: that.firstEnterKey,
					data: data,
					success: () => {
						console.log('[setStorage] success', that.firstEnterKey, data);
					},
					fail: (e) => {
						console.log('[setStorage] fail', that.firstEnterKey, e);
					},
				})
			},
			clear() {
				if (this.interval != null) {
					clearInterval(this.interval);
					this.interval = null;
				}
			},
			loadConfig(config) {
				// console.log("config", config);

				// 加载CSS样式
				const css = config.css;
				if (css != undefined && css.length > 0) {
					tools.loadCssCode(css);

					if (css.indexOf(".top{") >= 0) {
						this.cssTop = "top";
					}
					if (css.indexOf(".topbar-color{") >= 0) {
						this.cssTopbarColor = "topbar-color";
					}
				}

				if (this.cssTop == "") {
					this.cssTop = "top-default";
				}
				if (this.cssTopbarColor == "") {
					this.cssTopbarColor = "topbar-color-default";
				}
				console.log("[loadConfig] cssTop:", this.cssTop);
				console.log("[loadConfig] cssTopbarColor:", this.cssTopbarColor);

				// 加载比赛路线数据
				const pathList = config.pathList;
				// console.log("[loadConfig] pathList:", pathList);
				if (pathList != undefined) {
					this.pathList = pathList;
				}

				// 加载弹窗数据
				const popupDataList = config.popupDataList;
				// console.log("[loadConfig] popupDataList:", popupDataList);
				if (popupDataList != undefined && popupDataList.length > 0) {
					for (var i = 0; i < popupDataList.length; i++) {
						// console.log("[loadConfig] popupDataList", i, popupDataList[i]);
						if (popupDataList[i] == 'default') {
							for (var j = 0; j < defaultPopUpDataList.length; j++) {
								this.popupDataList.push(defaultPopUpDataList[j]);
							}
						} else {
							this.popupDataList.push(popupDataList[i]);
						}
					}
				} else {
					this.popupDataList = defaultPopUpDataList;
					console.log("[loadConfig] popupDataList 加载默认列表");
				}
				// console.log("[loadConfig] popupDataList:", this.popupDataList);
			},
			// 获取倒计时
			getCountdown() {
				// console.log(this.endSecond)
				if (this.endSecond > 0) {
					const now = Date.now() / 1000;
					const dif = this.endSecond - now;
					// const dif = 3600*24 - 60;
					if (dif > 0) {
						this.countdown = '距结束 ' + tools.convertSecondsToDHM(dif);
					} else {
						this.countdown = "活动已结束";
					}
					// this.countdown = tools.convertSecondsToHMS(dif);
				} else {
					this.countdown = "距结束 --天--小时";
				}
			},
			// 格式化 距离
			fmtDistanct(val) {
				if (val < 1000)
					return Math.round(val * 10 / 1000) / 10;
				else
					return Math.round(val / 1000);
			},
			// 格式化 配速
			fmtPace(val) {
				return tools.convertSecondsToHMS(val, 2);
			},
			fmtMcTime(timestamp) {
				var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
				// var Y = date.getFullYear() + '-';
				var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
				var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
				var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
				// var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());

				const timeStr = M + D + h + m;
				// console.log("timeStr", timeStr);
				return timeStr;
			},
			// 获取活动时间
			getActtime() {
				this.acttime = this.fmtMcTime(this.beginSecond) + " 至 " + this.fmtMcTime(this.endSecond);
			},
			getCardConfigQuery() {
				uni.request({
					url: apiCardConfigQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						ecId: this.ecId,
						pageName: this.pageName
					},
					success: (res) => {
						// console.log("getCardConfigQuery", res)
						const data = res.data.data;
						// console.log("configJson", data.configJson);
						const config = data.configJson != "" ? JSON.parse(data.configJson) : "";
						// console.log("configJson", data.configJson);
						/* const config = {
							"css": `
							`,
							"pathList": {
								"row1": [{
										"type": 2, // 1: 比赛路线  2: 导航到指定地点
										"img": "/static/common/dhdqdwz.png",
										"point": {
											"longitude": 117.022194,
											"latitude": 36.661612,
											"name": "小飞龙定向赛起始点"
										}
									},
									{
										"type": 1, // 1: 比赛路线  2: 导航到指定地点
										"img": "/static/common/cjlx12dw.png",
										"path": {
											"ocaId": 1,
											"mcType": 3 // 赛事类型 1 普通活动 2 线下赛 3 线上赛
										}
									}
								],
								"row2": [{
										"type": 1, // 1: 比赛路线  2: 导航到指定地点
										"img": "/static/common/zjlx16dw.png",
										"path": {
											"ocaId": 2,
											"mcType": 3 // 赛事类型 1 普通活动 2 线下赛 3 线上赛
										}
									},
									{
										"type": 1, // 1: 比赛路线  2: 导航到指定地点
										"img": "/static/common/gjlx20dw.png",
										"path": {
											"ocaId": 3,
											"mcType": 3 // 赛事类型 1 普通活动 2 线下赛 3 线上赛
										}
									}
								]
							},
							"popupDataList": [{
									"type": 1,
									"data": {
										"title": "小飞龙定向赛",
										"img": "/static/logo/xfl.png",
										"content": "济南奥体中心“一场三馆”包括体育场、体育馆、网球馆和游泳馆，呈现出“东荷西柳”的总体布局。 体育场以济南的“市树”柳树为母题，将垂柳柔美飘逸的形态固化为建筑语言。"
									}
								},
								{
									type: 2,
									data: {
										title: "规则",
										img: "/static/common/guize.png",
									}
								}, {
									type: 2,
									data: {
										title: "奖励",
										img: "/static/common/jiangli.png",
									}
								},
								"default"
							]
						}; */

						this.loadConfig(config);
						this.matchRsDetailQuery();

						setTimeout(this.dealFirstEnter, 500);
					},
					fail: (err) => {
						console.log("getCardConfigQuery err", err)
					},
				});
			},
			// 卡片对应线上赛多个活动查询
			matchRsDetailQuery() {
				uni.request({
					url: apiMatchRsDetailQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						ecId: this.ecId
					},
					success: (res) => {
						console.log("matchRsDetailQuery", res);
						if (checkResCode(res)) {
							const data = res.data.data;
							this.mcType = data.mcType;
							this.mcId = data.mcId;
							this.mcName = data.mcName;
							this.beginSecond = data.beginSecond;
							this.endSecond = data.endSecond;
							this.nickName = data.nickName;
							this.totalNum = data.totalNum;
							this.totalDistanct = data.totalDistanct;
							this.totalDistanctRankNum = data.totalDistanctRankNum;
							this.totalCp = data.totalCp;
							this.totalCpRankNum = data.totalCpRankNum;
							this.totalSysPoint = data.totalSysPoint;
							this.totalSysPointRankNum = data.totalSysPointRankNum;
							this.fastPace = data.fastPace;
							this.fastPaceRankNum = data.fastPaceRankNum;
							this.ocaRs = data.ocaRs;

							this.mcState = tools.checkMcState(this.beginSecond, this.endSecond);

							const rank = JSON.stringify(data);
							this.dealNotice(rank);

							this.getCountdown();
							this.getActtime();

							this.clear();
							this.interval = setInterval(this.getCountdown, 60000);
						}
					},
					fail: (err) => {
						console.log("matchRsDetailQuery err", err)
					},
				});
			},
			btnBack() {
				// window.history.back();
				const url = `action://to_home/`;
				// window.location.href = url;
				tools.appAction(url);
			},
			btnInfo() {
				// console.log(this.$refs.mypopup);
				this.$refs.mypopup.popupOpen();
			},
			onOverviewClick(ovtype) {
				this.queryObj.ovtype = ovtype;
				this.queryString = tools.objectToQueryString(this.queryObj);
				uni.navigateTo({
					url: "/pages/bm/style2/rankList?" + this.queryString
				});
			},
			onPathImgClick(item) {
				//item.type 1: 比赛路线  2: 导航到指定地点
				if (item.type == 1) {
					// 赛事/活动状态 0: 未开始  1: 进行中  2: 已结束
					if (this.mcState == 1) {
						const url = `action://to_detail/?id=${item.path.ocaId}&matchType=${item.path.mcType}`;
						// window.location.href = url;
						tools.appAction(url);
					} else if (this.mcState == 0) {
						uni.showToast({
							title: '比赛尚未开始',
							icon: 'none',
							duration: 3000
						});
					} else if (this.mcState == 2) {
						uni.showToast({
							title: '比赛已结束',
							icon: 'none',
							duration: 3000
						});
					}
				} else if (item.type == 2) {
					this.navPoint = item.point;
					// this.$refs.mypopupmap.popupOpen();
					
					const url = `action://to_map_app?title=${this.navPoint.name}&latitude=${this.navPoint.latitude}&longitude=${this.navPoint.longitude}`;
					// window.location.href = url;
					tools.appAction(url);
				}
			},
		}
	}
</script>

<style scoped>
	.content {
		width: 100vw;
		height: 100vh;
		overflow-x: hidden;
	}

	.top-default {
		position: relative;
		z-index: 10;
		width: 100%;
		height: 300px;
		padding-top: 36px;
		justify-content: space-between;
		background-image: url("/static/backgroud/top_bg_aoti2.png");
		background-repeat: no-repeat;
		background-position-x: center;
		background-position-y: bottom;
		/* background-size: 100% 100%; */
		background-size: cover;
	}

	.top-oval {
		position: relative;
		z-index: 0;
		margin-top: -180px;
		margin-left: -10%;
		width: 120%;
		height: 280px;
		background: linear-gradient(180deg, #ffffff 12.18%, #eeeeee 100%);
		border-radius: 50%;
		text-align: center;
	}
	
	.top-oval-text {
		color: #333333;
		font-size: 13px;
		line-height: 386px;
		pointer-events: auto;
	}

	.topbar {
		width: 90%;
		justify-content: space-between;
	}

	.topbar-color-default {
		color: #5b9100;
	}

	.topbar-back {
		/* width: 43rpx; */
		/* height: 43rpx; */
		/* opacity: 0; */
		font-size: 50rpx;
	}

	.topbar-info {
		width: 46rpx;
		height: 46rpx;
	}

	.topbar-rule {
		font-size: 32rpx;
	}

	.mcName {
		font-size: 40rpx;
		font-weight: 550;
	}

	.topbtm {
		width: 100%;
		/* height: 60rpx; */
		margin-bottom: 40px;
		justify-content: space-evenly;
	}

	.topbtm-name {
		/* width: 320rpx; */
		/* height: 28px; */
		padding: 5px 12px;
		background-color: #9fda39;
		border-radius: 5px;
		/* backdrop-filter: blur(30px); */
		text-align: center;
		font-weight: 500;
		color: #497400;
		font-size: 14px;
	}

	.mid {
		position: relative;
		z-index: 20;
		margin-top: -130px;
		pointer-events: none;
	}

	.mid-1 {
		width: 92%;
	}

	.mid-2 {
		width: 66%;
	}

	.overview-1 {
		width: 111px;
		height: 54px;
		background: #ffb40b;
		border-radius: 50%;
		box-shadow: 3px 3px 0px rgba(140, 140, 140, 1);
		pointer-events: auto;
	}

	.overview-2 {
		margin-top: -43px;
		color: #ffffff;
		font-size: 18px;
		pointer-events: auto;
	}

	.overview-3 {
		width: 111px;
		height: 54px;
		background: #f39509;
		border-radius: 50%;
		box-shadow: 3px 3px 0px rgba(140, 140, 140, 1);
		pointer-events: auto;
	}

	.overview-4 {
		width: 111px;
		height: 54px;
		background: #81cd00;
		border-radius: 50%;
		box-shadow: 3px 3px 0px rgba(140, 140, 140, 1);
		pointer-events: auto;
	}

	.overview-5 {
		width: 111px;
		height: 54px;
		background: #64cbb0;
		border-radius: 50%;
		box-shadow: 3px 3px 0px rgba(140, 140, 140, 1);
		pointer-events: auto;
	}

	.ovline1 {
		margin-top: 9px;
		color: #ffffff;
		font-size: 12px;
	}

	.ovline2 {
		color: #ffffff;
		font-size: 16px;
	}

	.main {
		width: 100%;
		margin-top: 36px;
		margin-bottom: 10px;
		/* height: 70vh; */
		justify-content: space-around;
		/* justify-content: space-between; */
	}

	.main-title {
		margin-bottom: 10px;
		font-weight: 550;
		color: #333333;
		font-size: 16px;
	}

	.pathimg {
		width: 127px;
		height: 115px;
	}

	.main-path {
		width: 90%;
		margin-top: 10px;
		margin-bottom: 10px;
		justify-content: space-evenly;
	}
</style>