<!-- 
[报名] 样式1 - 排名列表
http://localhost:5173/card/#/pages/bm/style1/rankList
https://oss-mbh5.colormaprun.com/card/#/pages/bm/style1/rankList
 -->
<template>
	<view class="body">
		<view v-if="pageReady" class="content uni-column">
			<view class="uni-column" :class="cssTop">
				<my-topbar :mcName="mcName" class="topbar-color" :showMessage="popupMessageList.length > 0"
					@btnBackClick="btnBack" @btnInfoClick="btnInfo" @btnMessageClick="btnMessage"></my-topbar>

				<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" v-if="mcState==1 && allowMcSignUp"></text>
						<text class="topbtm-sspm">实时排名</text>
						<view class="btnReGroup" v-if="mcState==1 && allowMcSignUp" @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="tabActiveColor"></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 btnStart-disable" v-if="mcState==0">活动尚未开始</button>
				<button class="btnStart btnStart-enable" v-if="mcState==1" @click="btnStartGame">{{btnStartGameText}}</button>
				<button class="btnStart btnStart-disable" v-if="mcState==2">活动已结束</button>
			</view>
			
			<my-popup ref="mypopup" :config="popupRuleConfig" :dataList="popupDataList" :acttime="acttime"></my-popup>
			<my-popup ref="mypopupMessage" :config="popupMessageConfig" :dataList="popupMessageList" @noMoreRemindersClick="onNoMoreRemindersClick"></my-popup>
			
		</view>
	</view>
</template>

<script>
	import tools from '/common/tools';
	import { teamName, defaultPopUpDataList, defaultPopUpDataList2 } from '/common/define';
	import {
		token,
		apiCardDetailQuery,
		apiCardRankDetailQuery,
		apiCardConfigQuery,
		apiUserCurrentRankNumQuery,
		apiIsAllowMcSignUp,
		apiUserJoinCardQuery,
		apiUnReadMessageQuery,
		apiReadMessage,
		checkResCode
	} from '/common/api';
	
	export default {
		data() {
			return {
				pageReady: false,
				pageName: "rankList",
				firstEnterKey: 'firstEnter-bm',
				rankKey: "rank-bm-style1",
				messageKey: "message-bm-style1",
				queryObj: {},
				queryString: "",
				token: "",

				ecId: 0, // 卡片id
				mcId: 0, // 赛事id
				mcType: 0, // 赛事类型 1 普通活动 2 线下赛 3 线上赛
				mcName: "", // 赛事名称
				acttime: "", // 活动时间
				beginSecond: null, // 活动或赛事开始时间戳，单位秒
				endSecond: null, // 活动或赛事结束时间戳，单位秒
				coiName: "", // 已报名单位名称，可为空
				ocaId: 0,	// 关联id，带入到App活动详情页面
				teamNum: 0, // 已报名队伍编号，可为0
				
				isJoin: null, // 是否报名
				btnStartGameText: "",

				mcState: 0 ,	// 赛事/活动状态 0: 未开始  1: 进行中  2: 已结束
				allowMcSignUp: false,	// 是否允许重新分组
				countdown: "", // 倒计时
				rankList: { // 排名列表
					totalRankRs: [],
					teamRankRs: [],
					inTeamRs: [],
					otherRs: []
				},
				interval: null,
				
				teamType: 0, // 队伍类型
				dispArrStr: "", // 要显示的集合范围 (total,team,in,other)
				tabItems: [],
				tabCurrent: 0,
				tabActiveColor: "#2e85ec",
				
				cssTop: "",
				popupRuleConfig: {}, // 规则弹窗配置
				popupMessageConfig: {}, // 通知弹窗配置
				popupDataList: [],
				popupMessageList: [],
				// mqIdListStr: "", // 已读消息id列表 逗号分隔
			}
		},
		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.firstEnterKey += "-" + this.ecId;
			console.log("firstEnterKey:", this.firstEnterKey);

			this.rankKey += "-" + this.ecId;
			console.log("rankKey:", this.rankKey);
			
			this.messageKey += "-" + this.ecId;
			console.log("messageKey:", this.messageKey);
			
			tools.removeCssCode();
			
			this.getCardConfigQuery();
			this.getUserCurrentRankNumQuery();
			this.isAllowMcSignUp();
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {
			// this.dealFirstEnter();
		},
		onShow() {
			this.getUserJoinCardQuery();
		},
		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;
				}
			},
			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);
				
				const tabActiveColor = config.tabActiveColor;
				if (tabActiveColor != undefined && tabActiveColor.length > 0) {
					this.tabActiveColor = tabActiveColor;
				}
				
				// 加载队伍类型  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 popupRuleConfig = config.popupRuleConfig;
				if (popupRuleConfig != undefined) {
					this.popupRuleConfig = popupRuleConfig;
				}
				// console.log("[loadConfig] popupRuleConfig:", this.popupRuleConfig);
				
				// 加载通知弹窗配置
				const popupMessageConfig = config.popupMessageConfig;
				if (popupMessageConfig != undefined) {
					this.popupMessageConfig = popupMessageConfig;
				}
				// console.log("[loadConfig] popupMessageConfig:", this.popupMessageConfig);
				
				// 加载弹窗数据
				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 if (popupDataList[i] == 'default2') {
							for (var j = 0; j < defaultPopUpDataList2.length; j++) {
								this.popupDataList.push(defaultPopUpDataList2[j]);
							}
						} else {
							this.popupDataList.push(popupDataList[i]);
						}
					}
				} else {
					this.popupDataList = defaultPopUpDataList;
					console.log("[loadConfig] popupDataList 加载默认列表");
				}
				// console.log("[loadConfig] popupDataList:", this.popupDataList);
				
				this.pageReady = true;
			},
			// 获取倒计时
			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) {
				return tools.fmtMcTime(timestamp);
			},
			// 获取活动时间
			getActtime() {
				this.acttime = tools.getActtime(this.beginSecond, 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;
							}
						`,
						"tabActiveColor": "#ff870d",
						"popupDataList": [
							{
								"type": 1,
								"data": {
									"title": "山青活动",
									"img": "/static/logo/sqsj.png",
									"content": "山青世界为广大青少年提供了亲近自然、劳动实践、拓展培训、军事教育、科普体验、自然探索的平台和机会，也为企事业单位青年团队提供会议培训、拓展训练等服务",
								}
							}, 
							"default"
						],
						"teamType": 1
						}; */
						
						this.loadConfig(config);
						this.getUnReadMessageQuery();
						this.getCardDetailQuery();
						
						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.ocaId = data.ocaId;
						
						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)
					},
				});
			},
			// 排名查询
			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)
					},
				});
			},
			// 卡片用户当前排名查询
			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)
					},
				});
			},
			// 用户是否已经报名卡片对应赛事查询
			getUserJoinCardQuery() {
				uni.request({
					url: apiUserJoinCardQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token
					},
					method: "POST",
					data: {
						ecId: this.ecId
					},
					success: (res) => {
						// console.log("getUserJoinCardQuery", res)
						const code = res.data.code;
						const data = res.data.data;
						if (code == 0) {
							this.isJoin = data.isJoin;
							if (this.isJoin) { // 已报名
								this.btnStartGameText = "我要比赛";
							} else {	// 未报名
								this.btnStartGameText = "我要报名";
							}
						}
					},
					fail: (err) => {
						console.log("getUserJoinCardQuery err", err)
					},
				});
			},
			// 未读消息列表查询
			getUnReadMessageQuery() {
				uni.request({
					url: apiUnReadMessageQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						relationType: 2,	// 类型 1 成就 2 卡片
						relationId: this.ecId
					},
					success: (res) => {
						// console.log("getUnReadMessageQuery", res);
						if (checkResCode(res)) {
							const unReadMessageRs = res.data.data;
							this.popupMessageList.length = 0;
							this.mqIdListStr = "";
							for (var i = 0; i < unReadMessageRs.length; i++) {
								let popupData = {
									type: 6,	// 6: 通知
									data: {}
								};
								this.messageKey += "-" + unReadMessageRs[i].mqId;
								popupData.data.mqType = unReadMessageRs[i].mqType;
								popupData.data.title = unReadMessageRs[i].mqTitle;
								popupData.data.message = unReadMessageRs[i].mqMessage;
								this.popupMessageList.push(popupData);
			
								// this.mqIdListStr += this.unReadMessageRs[i].mqId;
								// if (i < this.unReadMessageRs.length - 1) {
								// 	this.mqIdListStr += ",";
								// }
							}
			
							if (this.popupMessageList.length > 0) {
								const messageValue = uni.getStorageSync(this.messageKey);
								console.log("messageValue:", messageValue);
								if (!messageValue) {
									this.$refs.mypopupMessage.popupOpen();
									// uni.setStorageSync(this.messageKey, true);
								}
							}
						}
					},
					fail: (err) => {
						console.log("getUnReadMessageQuery err", err);
					},
				});
			},
			onNoMoreRemindersClick() {
				this.$refs.mypopupMessage.popupClose();
				uni.setStorageSync(this.messageKey, true);
			},
			// 标记消息已读
			readMessage() {
				uni.request({
					url: apiReadMessage,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						"mqIdListStr": this.mqIdListStr
					},
					success: (res) => {
						// console.log("readMessage", res);
					},
					fail: (err) => {
						console.log("readMessage err", err);
					},
				});
			},
			btnBack() {
				// window.history.back();
				const url = `action://to_home/`;
				tools.appAction(url);
			},
			btnReGroup() {
				this.queryObj.from = "rankList";
				this.queryString = tools.objectToQueryString(this.queryObj);
				// uni.navigateTo({
				// 	url: '/pages/bm/style1/signup?' + this.queryString
				// });
				const url = '/pages/bm/style1/signup?' + this.queryString;
				tools.appAction(url, "uni.navigateTo");
			},
			btnStartGame() {
				if (this.isJoin) {	// 已报名
					const url = `action://to_detail/?id=${this.ocaId}&matchType=${this.mcType}`;
					tools.appAction(url);
				} else {	// 未报名
					const url = "/pages/bm/style1/signup?" + this.queryString;
					tools.appAction(url, "uni.navigateTo");
				}
			},
			btnInfo() {
				// console.log(this.$refs.mypopup);
				this.$refs.mypopup.popupOpen();
			},
			btnMessage() {
				// console.log(this.$refs.mypopup);
				this.$refs.mypopupMessage.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: 24.6vh;
		padding-top: 36px;
		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-color {
		color: white;
	}
	
	.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: 100%;
		justify-content: space-around;
		/* justify-content: space-between; */
	}

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

	.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;
	}

	.btnStart {
		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;
	}
	
	.btnStart-enable {
		background-color: #ffb40b;
	}

	.btnStart-disable {
		background-color: #c3c3c3;
	}
	
</style>