<!-- 
[模板] 样式1 - 排名总览
http://localhost:5173/card/#/pages/tpl/style1/rankOverview
https://oss-mbh5.colormaprun.com/card/#/pages/tpl/style1/rankOverview
 -->
<template>
	<view class="body">
		<view v-if="pageReady" class="content uni-column">
			<view class="uni-column page-top">
				<my-topbar :mcName="mcName" class="topbar-color" @btnBackClick="btnBack"
					@btnInfoClick="btnInfo"></my-topbar>
			</view>

			<view class="mid uni-column uni-jcc">
				<view class="mid-1 uni-row uni-jcsb">
					<text>排名：<text style="color: #ff0045;">{{totalSysPointRankNum}}</text></text>
					<text class="mid-1-name">{{nickName}}</text>
					<text>场次：<text style="color: #ff0045;">{{totalNum}}</text></text>
				</view>
				<view class="mid-2 uni-row uni-jcsa">
					<view class="uni-column">
						<text class="mid-2-value">{{totalSysPoint}}</text>
						<text class="mid-2-text">百味豆</text>
					</view>

					<view class="mid-line"></view>

					<view class="uni-column">
						<text class="mid-2-value">{{fmtDistanct(totalDistanct)}}</text>
						<text class="mid-2-text">里程 km</text>
					</view>

					<view class="mid-line"></view>
					<view class="uni-column">
						<text class="mid-2-value">{{totalCp}}</text>
						<text class="mid-2-text">打点数</text>
					</view>

					<view class="mid-line"></view>

					<view class="uni-column">
						<text class="mid-2-value">{{fmtPace(fastPace)}}</text>
						<text class="mid-2-text">最快配速</text>
					</view>
				</view>
			</view>

			<view class="main uni-column">
				<text class="main-title">选择比赛路线</text>
				<my-pathList ref="myPathList" :style="pathListStyle.style" :pathList="pathList" :mcState="mcState"
					:showLine="pathListStyle.showLine" :isNewUser="isNewUser"
					@onNewUserPathClick="onNewUserPathClick"></my-pathList>
				<!-- <button class="btnGuide" @click="btnGuide">新手引导</button> -->
			</view>

			<my-popup ref="mypopup" :config="cardConfigData.popupRuleConfig" :dataList="cardConfigData.popupRuleList"
				:acttime="acttime"></my-popup>
			<my-guide ref="myGuide" @popup-close="onGuideClose"></my-guide>
			<!-- <my-popup-map ref="mypopupmap" :point="navPoint"></my-popup-map> -->
		</view>
	</view>
</template>

<script>
	import tools from '/common/tools';
	import cardfunc from '../../../common/cardfunc';
	// import { localCardConfig } from "./cardconfig/test.js";
	import {
		localCardConfig
	} from "./cardconfig/pattern1.js";
	import {
		localUserConfig
	} from "./cardconfig/test_user.js";
	import {
		token,
		apiMatchRsDetailQuery,
		checkResCode
	} from '/common/api';

	export default {
		data() {
			return {
				cardConfigData: cardfunc.cardConfigData,
				pageReady: false,
				// 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-tpl-style1',
				rankKey: "rank-tpl-style1",
				queryObj: {},
				queryString: "",
				token: "",
				isNewUser: false,
				cardconfig: {}, // 卡片配置
				userconfig: {}, // 用户配置

				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: 已结束
				pathList: {},
				pathListStyle: {},
				selectedPath: null,
				navPoint: {},
			}
		},
		computed: {
			pathListLen() {
				return Object.keys(this.pathList).length;
			}
		},
		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);

			cardfunc.init(this, this.token, this.ecId);
			cardfunc.getCardConfig(this.cardConfigQueryCallback, localCardConfig);
			cardfunc.isNewUserQuery(this.isNewUserQueryCallback);
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {
			// this.dealFirstEnter();
		},
		onShow() {},
		onUnload() {
			this.clear();
		},
		methods: {
			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;
				}
			},
			cardConfigQueryCallback(cardconfig) {
				this.cardconfig = cardconfig;
				cardfunc.getUserConfig(this.userConfigQueryCallback, localUserConfig);
			},
			userConfigQueryCallback(userconfig) {
				this.userconfig = userconfig;
				this.loadConfig();
				this.matchRsDetailQuery();
				setTimeout(this.dealFirstEnter, 500);
			},
			loadConfig() {
				this.loadCardConfig(this.cardconfig);
				this.loadUserConfig(this.userconfig);
				this.pageReady = true;
			},
			loadCardConfig(cardconfig) {
				cardconfig = cardfunc.parseCardConfig(cardconfig);
				// console.log("[loadCardConfig] cardconfig:", cardconfig);

				// 加载卡片通用配置
				if (cardconfig.common != undefined) {
					cardfunc.loadCardCommonConfig(cardconfig.common);
				}

				// -------- 加载当前页面的配置 --------

				const config = cardfunc.parseCardConfig(cardconfig[this.pageName]);
				// console.log("[loadConfig] config_page:", config);
				if (config == undefined || config == null) {
					return;
				}

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

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

				// 加载比赛路线样式
				const pathListStyle = config.pathListStyle;
				// console.log("[loadConfig] pathList:", pathList);
				if (pathListStyle != undefined) {
					this.pathListStyle = pathListStyle;
				}
			},
			loadUserConfig(userconfig) {
				if (!userconfig) {
					console.log("[loadUserConfig] userconfig 为空");
					return;
				}
				
				const config = cardfunc.parseCardConfig(userconfig);
				console.log("[loadUserConfig] userconfig:", config);
				
				// 加载用户的弹窗数据
				cardfunc.loadUserPopupRule(config);

				// 加载比赛路线数据
				this.pathList = cardfunc.getUserPathList(config);
			},
			isNewUserQueryCallback(isNewUser) {
				this.isNewUser = isNewUser;
			},
			// 获取倒计时
			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) {
				return tools.fmtMcTime(timestamp);
			},
			// 获取活动时间
			getActtime() {
				this.acttime = tools.getActtime(this.beginSecond, this.endSecond);
			},
			// 卡片对应线上赛多个活动查询
			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() {
				const url = "/pages/tpl/style1/rankList?" + this.queryString;
				tools.appAction(url, "uni.navigateTo");
			},
			btnInfo() {
				// console.log(this.$refs.mypopup);
				this.$refs.mypopup.popupOpen();
			},
			// btnGuide() {
			// 	this.$refs.myGuide.popupOpen();
			// },
			onOverviewClick(ovtype) {
				this.queryObj.ovtype = ovtype;
				this.queryString = tools.objectToQueryString(this.queryObj);
				const url = "/pages/tpl/style1/rankList?" + this.queryString;
				tools.appAction(url, "uni.navigateTo");
			},
			onNewUserPathClick(data) {
				// console.log("onNewUserPathClick:", data);
				this.selectedPath = data;
				this.$refs.myGuide.popupOpen();
			},
			onGuideClose() {
				if (this.isNewUser && this.selectedPath != null) {
					this.$refs.myPathList.to_detail(this.selectedPath);
					this.selectedPath = null;
				}
			}
		}
	}
</script>

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

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

	.topbar-color {
		color: #333333;
	}

	.topbtm {
		width: 100%;
		margin-bottom: 40px;
		justify-content: space-evenly;
	}

	.topbtm-name {
		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 {
		width: 90%;
		height: 120px;
		position: relative;
		z-index: 20;
		margin-top: -100px;
		background: #ffffff;
		border-radius: 9px;
		box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.13);
		font-family: Source Han Sans CN;
	}

	.mid-1 {
		width: 90%;
		/* margin: 12px; */
		margin-bottom: 12px;
		font-weight: 500;
		color: #8e8e8e;
		font-size: 14px;
	}

	.mid-1-name {
		max-width: 310rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.mid-2 {
		width: 92%;
		/* margin: 0 10px; */
	}

	.mid-2-value {
		font-weight: 900;
		font-size: 22px;
	}

	.mid-2-text {
		color: #989898;
		font-size: 12px;
	}

	.mid-line {
		width: 0px;
		height: 45.04px;
		border: 1px solid;
		border-color: #e6e6e6;
	}

	.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: 20px;
		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;
	}
</style>