<!-- 
[报名] 样式2 - 排名列表
http://localhost:5173/card/#/pages/bm/style2/rankList
https://oss-mbh5.colormaprun.com/card/#/pages/bm/style2/rankList
 -->
<template>
	<view class="body">
		<view class="content uni-column">
			<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">{{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="main uni-column">
				<uni-segmented-control class="main-tab" :current="tabCurrent" :values="tabItems"
					@clickItem="onClickTabItem" styleType="button" activeColor="#81cd00"></uni-segmented-control>
				<view class="tab-view uni-column">
					<!-- 总距离 -->
					<my-ranklist v-show="tabCurrent === 0" :rankRs="rankList.totalDistanceRs" rank-type="totalDistance"></my-ranklist>

					<!-- 打点数 -->
					<my-ranklist v-show="tabCurrent === 1" :rankRs="rankList.totalCpRs" rank-type="totalCp"></my-ranklist>
					
					<!-- 百味豆 -->
					<my-ranklist v-show="tabCurrent === 2" :rankRs="rankList.totalSysPointRs" rank-type="totalSysPoint"></my-ranklist>
					
					<!-- 配速 -->
					<my-ranklist v-show="tabCurrent === 3" :rankRs="rankList.fastPaceRs" rank-type="fastPace"></my-ranklist>
				</view>

				<button class="btnBack" @click="btnBack">返回</button>
			</view>
			
			<my-popup ref="mypopup" :dataList="popupDataList" :acttime="acttime"></my-popup>
			
		</view>
	</view>
</template>

<script>
	import tools from '/common/tools';
	import { teamName, defaultPopUpDataList } from '/common/define';
	import {
		token,
		apiMatchRsDetailQuery,
		apiCardRankDetailQuery,
		apiCardConfigQuery,
		apiUserCurrentRankNumQuery,
		apiIsAllowMcSignUp,
		checkResCode
	} from '/common/api';
	
	export default {
		data() {
			return {
				pageName: "rankList",
				firstEnterKey: 'firstEnter-bm-style2',
				rankKey: "rank-bm-style2",
				queryObj: {},
				queryString: "",
				token: "",
				ovtype: "",

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

				mcState: 0 ,	// 赛事/活动状态 0: 未开始  1: 进行中  2: 已结束
				allowMcSignUp: false,	// 是否允许重新分组
				countdown: "", // 倒计时
				rankList: { // 排名列表
					totalDistanceRs: [],
					totalCpRs: [],
					totalSysPointRs: [],
					fastPaceRs: []
				},
				interval: null,
				
				teamType: 0, // 队伍类型
				dispArrStr: "totalDistance,totalCp,totalSysPoint,fastPace", // 要显示的集合范围
				tabItems: ["总距离", "打点数", "百味豆", "配速"],
				tabCurrent: 0,
				
				cssTop: "",
				cssTopbarColor: "",
				popupDataList: [],
			}
		},
		computed: {},
		onLoad(query) { // 类型非必填，可自动推导
			// console.log(query);
			this.queryObj = query;
			this.queryString = tools.objectToQueryString(this.queryObj);
			// console.log(queryString);
			this.token = query["token"] ?? token;
			this.ecId = query["id"] ?? 0;
			this.ovtype = query["ovtype"] ?? "";
			
			this.firstEnterKey += "-" + this.ecId;
			console.log("firstEnterKey:", this.firstEnterKey);

			this.rankKey += "-" + this.ecId;
			console.log("rankKey:", this.rankKey);
			
			tools.removeCssCode();
			
			this.getCardConfigQuery();
			this.dealOvtype();
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {
			// this.dealFirstEnter();
		},
		onUnload() {
			this.clear();
		},
		methods: {
			dealOvtype() {
				if (this.ovtype == "totalDistance") {
					this.tabCurrent = 0;
				} else if (this.ovtype == "totalCp") {
					this.tabCurrent = 1;
				} else if (this.ovtype == "totalSysPoint") {
					this.tabCurrent = 2;
				} else if (this.ovtype == "fastPace") {
					this.tabCurrent = 3;
				}
				console.log(`dealOvtype: ${this.ovtype} tabCurrent: ${this.tabCurrent}`);
			},
			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 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 = "距结束 --天--小时";
				}
			},
			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);
			},
			getTeamName(teamType, teamIndex) {
				return teamName[teamType][teamIndex];
			},
			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": `
							.top{
								width: 100%;
								height: 170px;
								padding-top: 36px;
								justify-content: space-between;
								background-image: url("static/backgroud/top_bg_aoti3.png");
								background-repeat: no-repeat;
								background-position: center;
								background-size: cover;
							}
						`,
						"popupDataList": [{
								"type": 1,
								"data": {
									"title": "小飞龙定向赛",
									"img": "/static/logo/xfl.png",
									"content": "济南奥体中心“一场三馆”包括体育场、体育馆、网球馆和游泳馆，呈现出“东荷西柳”的总体布局。 体育场以济南的“市树”柳树为母题，将垂柳柔美飘逸的形态固化为建筑语言。"
								}
							},
							"default"
						]
						}; */
						
						this.loadConfig(config);
						this.matchRsDetailQuery();
						
						setTimeout(this.dealFirstEnter, 500);
					},
					fail: (err) => {
						console.log("getCardConfigQuery err", err)
					},
				});
			},
			// 卡片对应活动或赛事详情查询
			// getCardDetailQuery() {
			// 	uni.request({
			// 		url: apiCardDetailQuery,
			// 		header: {
			// 			"Content-Type": "application/x-www-form-urlencoded",
			// 			"token": this.token,
			// 		},
			// 		method: "POST",
			// 		data: {
			// 			ecId: this.ecId
			// 		},
			// 		success: (res) => {
			// 			// console.log("getCardDetailQuery", 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.coiName = data.coiName;
			// 			this.teamNum = data.teamNum;
						
			// 			this.mcState = tools.checkMcState(this.beginSecond, this.endSecond);
						
			// 			this.getCountdown();
			// 			this.getActtime();
			// 			this.getCardRankDetailQuery();

			// 			this.clear();
			// 			this.interval = setInterval(this.getCountdown, 60000);
			// 		},
			// 		fail: (err) => {
			// 			console.log("getCardDetailQuery 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);
				
							this.getCountdown();
							this.getActtime();
							this.getCardRankDetailQuery();
				
							this.clear();
							this.interval = setInterval(this.getCountdown, 60000);
						}
					},
					fail: (err) => {
						console.log("matchRsDetailQuery err", err)
					},
				});
			},
			// 排名查询
			getCardRankDetailQuery() {
				uni.request({
					url: apiCardRankDetailQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						mcIdListStr: this.mcId,
						mcType: this.mcType,
						dispArrStr: this.dispArrStr
					},
					success: (res) => {
						// console.log("getCardRankDetailQuery", res);
						const rankdata = res.data.data;
						this.rankList.totalDistanceRs = rankdata.totalDistanceRs;
						this.rankList.totalCpRs = rankdata.totalCpRs;
						this.rankList.totalSysPointRs = rankdata.totalSysPointRs;
						this.rankList.fastPaceRs = rankdata.fastPaceRs;
					},
					fail: (err) => {
						console.log("getCardRankDetailQuery err", err)
					},
				});
			},
			// 卡片用户当前排名查询
			// getUserCurrentRankNumQuery() {
			// 	uni.request({
			// 		url: apiUserCurrentRankNumQuery,
			// 		header: {
			// 			"Content-Type": "application/x-www-form-urlencoded",
			// 			"token": this.token,
			// 		},
			// 		method: "POST",
			// 		data: {
			// 			ecId: this.ecId
			// 		},
			// 		success: (res) => {
			// 			// console.log("getUserCurrentRankNumQuery", res)
			// 			if (res.data.code == 0) {
			// 				const data = res.data.data;
			// 				const rankNum = data.rankNum;
			// 				this.dealNotice(rankNum);
			// 			}
			// 		},
			// 		fail: (err) => {
			// 			console.log("getUserCurrentRankNumQuery err", err)
			// 		},
			// 	});
			// },
			// 是否允许重新分组（报名）
			isAllowMcSignUp() {
				uni.request({
					url: apiIsAllowMcSignUp,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						ecId: this.ecId
					},
					success: (res) => {
						// console.log("isAllowMcSignUp", res)
						if (res.data.code == 0) {
							const data = res.data.data;
							this.allowMcSignUp = data.allowSignUp;
						}
					},
					fail: (err) => {
						console.log("isAllowMcSignUp err", err)
					},
				});
			},
			btnBack() {
				// window.history.back();
				uni.navigateTo({
					url: "/pages/bm/style2/rankOverview?" + this.queryString
				});
			},
			btnInfo() {
				// console.log(this.$refs.mypopup);
				this.$refs.mypopup.popupOpen();
			},
			onClickTabItem(e) {
				if (this.tabCurrent != e.currentIndex) {
					this.tabCurrent = e.currentIndex;
				}
			}
		}
	}
</script>

<style scoped>
	.content {
		width: 100vw;
		height: 100vh;
	}

	.top-default {
		width: 100%;
		height: 170px;
		padding-top: 36px;
		justify-content: space-between;
		background-image: url("/static/backgroud/top_bg_aoti3.png");
		background-repeat: no-repeat;
		background-position: center;
		background-size: cover;
	}
	
	.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%;
		margin-bottom: 5px;
		justify-content: space-evenly;
	}
	
	.topbtm-name {
		padding: 3px 12px;
		background-color: #9fda39;
		border-radius: 5px;
		text-align: center;
		font-weight: 500;
		color: #497400;
		font-size: 14px;
	}
	
	.cal {
		width: 46rpx;
		height: 46rpx;
		margin-right: 20rpx;
	}
	
	.main {
		width: 100%;
		/* height: 70vh; */
		flex-grow: 1;
		justify-content: space-around;
		/* justify-content: space-between; */
	}

	.main-tab {
		width: 90%;
		margin-top: 20rpx;
	}

	.tab-view {
		width: 100%;
		/* height: 69vh; */
		flex-grow: 1;
	}

	.btnBack {
		width: 70%;
		/* height: 6vh; */
		height: 80rpx;
		/* margin-bottom: 1vh; */
		margin-bottom: 20rpx;
		/* font-weight: bold; */
		color: white;
		font-size: 32rpx;
		line-height: 80rpx;
		border-radius: 27px;
		background-color: #81cd00;
	}
	
</style>