<!-- 
[报名] 样式1 - 排名列表
http://localhost:5173/card/#/pages/bm/style1/rankList
https://oss-mbh5.colormaprun.com/card/#/pages/bm/style1/rankList
 -->
<template>
	<view class="body">
		<view class="content">
			<view class="uni-column" :class="cssTop">
				<view class="topbar uni-row">
					<image mode="aspectFit" class="topbar-back" @click="btnBack" src="/static/default/back.png"></image>
					<text class="mcName">{{mcName}}</text>
					<image mode="aspectFit" class="topbar-info" @click="btnInfo" src="/static/default/info.png"></image>
				</view>

				<view class="topcontent uni-column">
					<view>
						<text class="toptext">{{coiName}}</text>
						<text class="toptext" v-if="teamNum > 0">{{getTeamName(teamType, teamNum)}}</text>
					</view>
					<view class="top-countdown uni-row">
						<image mode="aspectFit" class="cal" src="/static/default/cal.png"></image>
						<text>{{countdown}}</text>
					</view>
				</view>

				<view class="topbtm uni-column">
					<view class="topbtm-content uni-row">
						<text class="topbtm-sspm"></text>
						<text class="topbtm-sspm">实时排名</text>
						<view class="btnReGroup" @click="btnReGroup">重新分组</view>
					</view>
				</view>
				<!-- <text class="mcName">{{ecId}} - {{mcId}} - {{token}}</text> -->
			</view>
			<view class="main uni-column">
				<uni-segmented-control class="main-tab" :current="tabCurrent" :values="tabItems"
					@clickItem="onClickTabItem" styleType="button" activeColor="#2e85ec"></uni-segmented-control>
				<view class="tab-view uni-column">
					<!-- 总排名 -->
					<my-ranklist v-show="tabCurrent === 0" :rankRs="rankList.totalRankRs"></my-ranklist>

					<!-- 队伍排名 -->
					<my-ranklist v-show="tabCurrent === 1" v-if="teamType==0" :rankRs="rankList.teamRankRs" :teamType="this.teamType"></my-ranklist>
					
					<!-- 队内排名 -->
					<my-ranklist v-show="tabCurrent === 2" v-if="teamType==0" :rankRs="rankList.inTeamRs"></my-ranklist>
					
					<!-- 学生排名 -->
					<my-ranklist v-show="tabCurrent === 1" v-if="teamType==1" :rankRs="teamNum==1 ? rankList.inTeamRs : rankList.otherRs[1]"></my-ranklist>
					
					<!-- 家长排名 -->
					<my-ranklist v-show="tabCurrent === 2" v-if="teamType==1" :rankRs="teamNum==2 ? rankList.inTeamRs : rankList.otherRs[2]"></my-ranklist>
				</view>

				<button class="btnStart" @click="btnStart">开始比赛</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,
		apiCardDetailQuery,
		apiCardRankDetailQuery,
		apiCardConfigQuery,
		checkResCode
	} from '/common/api';
	
	export default {
		data() {
			return {
				pageName: "rankList",
				// firstEnterKey: 'firstEnter-bm_sqsj_rankList',
				firstEnterKey: 'firstEnter-bm_sqsj',
				queryString: "",
				token: "",

				ecId: 0, // 卡片id
				mcId: 0, // 赛事id
				mcType: 0, // 赛事类型 1 普通活动 2 线下赛 3 线上赛
				mcName: "", // 赛事名称
				acttime: "", // 活动时间
				beginSecond: null, // 活动或赛事开始时间戳，单位秒
				endSecond: null, // 活动或赛事结束时间戳，单位秒
				coiName: "", // 已报名单位名称，可为空
				teamNum: 0, // 已报名队伍编号，可为0

				countdown: "", // 倒计时
				rankList: { // 排名列表
					totalRankRs: [],
					teamRankRs: [],
					inTeamRs: [],
					otherRs: []
				},
				interval: null,
				
				teamType: 0, // 队伍类型
				dispArrStr: "", // 要显示的集合范围 (total,team,in,other)
				tabItems: [],
				tabCurrent: 0,
				
				cssTop: "",
				popupDataList: [],
			}
		},
		computed: {},
		onLoad(event) { // 类型非必填，可自动推导
			// console.log(event);
			this.queryString = tools.objectToQueryString(event);
			// console.log(queryString);
			this.token = event["token"] ?? token;
			this.ecId = event["id"] ?? 0;

			tools.removeCssCode();
			
			this.getCardConfigQuery();
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {
			this.dealFirstEnter();
		},
		onUnload() {
			this.clear();
		},
		methods: {
			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 (this.cssTop == "") {
					this.cssTop = "top-default";
				}
				console.log("[loadConfig] cssTop:", this.cssTop);
				
				// 加载队伍类型  0: 红黄蓝紫 1: 学生/家长
				if (config.teamType != undefined && config.teamType >= 0) {
					this.teamType = config.teamType;
				}
				if (this.teamType == 0) {
					this.dispArrStr = "total,team,in", // 要显示的集合范围 (total,team,in,other)
					this.tabItems = ['总排名', '队伍排名', '队内排名'];
				} else if (this.teamType == 1) {
					this.dispArrStr = "total,in,other", // 要显示的集合范围 (total,team,in,other)
					this.tabItems = ['总排名', '学生排名', '家长排名'];
				}
				
				// 加载弹窗数据
				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: 26vh;
								padding-top: 30px;
								justify-content: space-between;
								background-image: url('static/backgroud/top_run.png'), url('static/backgroud/top_colorbar.png'), linear-gradient(180deg,#178bff 0%,#004d9b 100%);
								background-repeat: no-repeat;
								background-position: 45px 25px, center, 0px 0px;
								background-size: auto 27vh, auto 22vh , cover;
							}
						`,
						"popupDataList": [
							{
								"type": 1,
								"data": {
									"title": "山青活动",
									"img": "/static/logo/sqsj.png",
									"content": "山青世界为广大青少年提供了亲近自然、劳动实践、拓展培训、军事教育、科普体验、自然探索的平台和机会，也为企事业单位青年团队提供会议培训、拓展训练等服务",
								}
							}, 
							"default"
						],
						"teamType": 1
						}; */
						
						this.loadConfig(config);
						this.getCardDetailQuery();
					},
					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.getCountdown();
						this.getActtime();
						this.getCardRankDetailQuery();

						this.clear();
						this.interval = setInterval(this.getCountdown, 60000);
					},
					fail: (err) => {
						console.log("getCardDetailQuery 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.totalRankRs = rankdata.totalRankRs;
						this.rankList.teamRankRs = rankdata.teamRankRs;
						this.rankList.inTeamRs = rankdata.inTeamRs;
						this.rankList.otherRs = rankdata.otherRs;
					},
					fail: (err) => {
						console.log("getCardRankDetailQuery err", err)
					},
				});
			},
			btnBack() {
				// window.history.back();
				window.location.href = `action://to_home/`;
			},
			btnReGroup() {
				uni.navigateTo({
					url: '/pages/bm/style1/signup?from=rankList&' + this.queryString
				});
			},
			btnStart() {
				window.location.href = `action://to_detail/?id=${this.mcId}&matchType=${this.mcType}`;
			},
			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: 26vh;
		padding-top: 30px;
		justify-content: space-between;
		background-image: url("/static/backgroud/top_run.png"), url("/static/backgroud/top_colorbar.png"), linear-gradient(180deg,#f8a95a 0%,#d25f11 100%);
		/* background-image: url("/static/backgroud/top_run.png"), url("/static/backgroud/top_colorbar.png"), linear-gradient(180deg,#7aedff 0%,#047200 100%); */
		/* background-image: url("/static/backgroud/top_run.png"), url("/static/backgroud/top_colorbar.png"), linear-gradient(180deg,#178bff 0%,#004d9b 100%); */
		background-repeat: no-repeat;
		background-position: 45px 25px, center, 0px 0px;
		/* background-position-x: center; */
		/* background-position-y: center; */
		background-size: auto 27vh, auto 22vh , cover;
	}
	
	.topbar {
		width: 90%;
		justify-content: space-between;
	}

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

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

	.mcName {
		color: white;
		font-size: 39rpx;
		font-weight: bold;
	}

	.topcontent {
		/* height: 1300rpx; */
		/* background-color: #2e85ec; */
		margin-top: 50rpx;
		justify-content: center;
	}

	.top-countdown {
		height: 90rpx;
		color: #ffdc51;
		font-size: 28rpx;
	}
	
	.cal {
		width: 46rpx;
		height: 46rpx;
		margin-right: 20rpx;
	}
	
	.toptext {
		margin: 0 10rpx;
		color: #ffffff;
		font-size: 35rpx;
		font-weight: 500;
		line-height: 60rpx;
	}

	.btnReGroup {
		width: 130rpx;
		height: 36rpx;
		margin-top: 15rpx;
		margin-bottom: 15rpx;
		background: #ffcb00;
		border-radius: 15px;
		color: #000000;
		font-size: 24rpx;
		text-align: center;
		line-height: 36rpx;
	}

	.topbtm {
		width: 100%;
		height: 60rpx;
		margin-bottom: 10rpx;
		justify-content: space-evenly;
	}

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

	.topbtm-sspm {
		width: 120rpx;
		color: #ffee00;
		font-size: 24rpx;
		text-align: center;
	}

	.main {
		width: 100%;
		height: 70vh;
		justify-content: space-around;
		/* justify-content: space-between; */
	}

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

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

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

</style>