<!-- 
锦标赛排名列表
http://localhost:5173/card/#/pages/jbs/rankList
https://oss-mbh5.colormaprun.com/card/#/pages/jbs/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>
					<text class="topbar-rule" @click="btnInfo" >规则</text>
					<!-- <image mode="aspectFit" class="topbar-info" @click="btnInfo" src="/static/default/info.png"></image> -->
				</view>
				<view :class="cssLogo"></view>
				<view class="topcontent uni-row">
					<text class="countdown">结束倒计时：</text>
					<image mode="aspectFit" class="cal" src="/static/default/cal.png"></image>
					<text class="countdown">{{countdown}}</text>
				</view>
				<!-- <text class="mcName">{{ecId}} - {{mcId}} - {{token}}</text> -->
			</view>
			<view class="main uni-column">
				<my-ranklist :rankRs="rankList.totalRankRs"></my-ranklist>
				<button class="btnStart btnStart-disable" v-if="mcState==0">活动尚未开始</button>
				<button class="btnStart btnStart-enable" v-if="mcState==1" @click="btnStart">开始比赛</button>
				<button class="btnStart btnStart-disable" v-if="mcState==2">活动已结束</button>

			</view>

			<my-popup ref="mypopup" :config="popupRuleConfig" :dataList="popupDataList"></my-popup>

		</view>
	</view>
</template>

<script>
	import tools from '../../common/tools';
	import {
		defaultPopUpDataList
	} from '/common/define';
	import {
		token,
		apiCardDetailQuery,
		apiCardRankDetailQuery,
		apiUserCurrentRankNumQuery,
		apiCardConfigQuery,
		apiOnlineMcSignUp,
		checkResCode
	} from '../../common/api';

	export default {
		data() {
			return {
				pageName: "rankList",
				firstEnterKey: 'firstEnter-jbs_rankList',
				rankKey: "rank-jbs",
				queryObj: {},
				queryString: "",
				token: "",

				ecId: 0, // 卡片id
				coiId: 0, // 单位id
				mcId: 0, // 赛事id
				mcType: 0, // 赛事类型 1 普通活动 2 线下赛 3 线上赛
				mcName: "", // 赛事名称
				beginSecond: null, // 活动或赛事开始时间戳，单位秒
				endSecond: null, // 活动或赛事结束时间戳，单位秒
				ocaId: 0,	// 关联id，带入到App活动详情页面

				mcState: 0, // 赛事/活动状态 0: 未开始  1: 进行中  2: 已结束
				countdown: "", // 倒计时
				rankList: { // 排名列表
					totalRankRs: [],
					teamRankRs: [],
					inTeamRs: [],
				},
				interval: null,

				dispArrStr: "total", // 要显示的集合范围 (total,team,in,other)
				cssTop: "",
				cssLogo: "",
				popupRuleConfig: {}, // 规则弹窗配置
				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.firstEnterKey += "-" + this.ecId;
			console.log("firstEnterKey:", this.firstEnterKey);

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

			tools.removeCssCode();

			this.getCardConfigQuery();
			this.getUserCurrentRankNumQuery();
			// this.getCardDetailQuery();
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {
			// this.dealFirstEnter();
		},
		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() {
				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(".logo{") >= 0) {
						this.cssLogo = "logo";
					}
				}

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

				// 加载规则弹窗配置
				const popupRuleConfig = config.popupRuleConfig;
				if (popupRuleConfig != undefined) {
					this.popupRuleConfig = popupRuleConfig;
				}
				// console.log("[loadConfig] popupRuleConfig:", this.popupRuleConfig);
				
				// 加载弹窗数据
				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() {
				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 = "--天--小时";
				}
			},
			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;
						const config = data.configJson != "" ? JSON.parse(data.configJson) : "";
						// console.log("configJson", data.configJson);
						/* const config = {
						"css": `
							.top{
								width: 100%;
								height: 26vh;
								padding-top: 36px;
								justify-content: space-between;
								background-image: url('static/backgroud/top_colorbar.png'), linear-gradient(180deg,#178bff 0%,#004d9b 100%);
								background-repeat: no-repeat;
								background-position: center, 0px 0px;
								background-size: auto 22vh , cover;
							}
							.logo{
								width: 150px;
								height: 150px;
								margin-top: 10px;
								background-image: url('static/logo/xfl.png');
								background-repeat: no-repeat;
								background-position-x: center;
								background-position-y: center;
								background-size: contain;
							}
						`,
						"popupDataList": [
							{
								"type": 1,
								"data": {
									"title": "山青活动",
									"img": "/static/logo/sqsj.png",
									"content": "山青世界为广大青少年提供了亲近自然、劳动实践、拓展培训、军事教育、科普体验、自然探索的平台和机会，也为企事业单位青年团队提供会议培训、拓展训练等服务",
								}
							}, 
							"default"
						]
						}; */

						this.loadConfig(config);
						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.coiId = data.coiId;
						this.mcId = data.mcId;
						this.mcType = data.mcType;
						this.mcName = data.mcName;
						this.beginSecond = data.beginSecond;
						this.endSecond = data.endSecond;
						this.ocaId = data.ocaId;
						
						this.mcState = tools.checkMcState(this.beginSecond, this.endSecond);

						this.getCountdown();
						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;
					},
					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)
					},
				});
			},
			// 线上赛报名(重新分组)
			onlineMcSignUp() {
				uni.request({
					url: apiOnlineMcSignUp,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						mcId: this.mcId,
						coiId: this.coiId,
						selectTeam: 0
					},
					success: (res) => {
						// console.log("onlineMcSignUp", res)

						if (checkResCode(res)) {
							// uni.showToast({
							// 	title: '比赛报名成功！',
							// 	icon: 'none',
							// 	duration: 3000
							// });

							const url = `action://to_detail/?id=${this.ocaId}&matchType=${this.mcType}`;
							tools.appAction(url);
						}
					},
					fail: (err) => {
						console.log("onlineMcSignUp err", err)
						uni.showToast({
							title: '出错了，比赛报名失败',
							icon: 'none',
							duration: 3000
						});
					},
				});
			},
			btnBack() {
				// window.history.back();
				const url = `action://to_home/`;
				tools.appAction(url);
			},
			btnStart() {
				this.onlineMcSignUp();
			},
			btnInfo() {
				this.$refs.mypopup.popupOpen();
			},
		}
	}
</script>

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

	.top-default {
		width: 100%;
		height: 28vh;
		/* height: 500rpx; */
		padding-top: 36px;
		justify-content: flex-start;
		background-image: url("/static/backgroud/top_medal.png"), url("/static/backgroud/top_bg1.png");
		background-repeat: no-repeat;
		background-position-x: center, center;
		background-position-y: 15vh, center;
		background-size: 55vw auto, cover;
	}

	.logo-default {
		/* width: 150px;
		height: 150px;
		margin-top: 10px;
		background-image: url('/static/logo/jbs.png');
		background-repeat: no-repeat;
		background-position-x: center;
		background-position-y: center;
		background-size: contain; */
	}

	.topbar {
		width: 90%;
		/* padding: 0rpx 30rpx; */
		justify-content: space-between;
	}

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

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

	.topbar-rule {
		color: white;
		font-size: 32rpx;
	}
	
	.mcName {
		color: white;
		/* font-size: 32rpx; */
		font-size: 39rpx;
		font-weight: bold;
	}

	.topcontent {
		min-width: 300rpx;
		height: 100rpx;
		justify-content: space-evenly;
	}

	.countdown {
		color: white;
		font-size: 32rpx;
	}

	.cal {
		width: 30rpx;
		margin-right: 20rpx;
	}

	.main {
		width: 100%;
		height: 66vh;
		justify-content: space-between;
	}

	.btnStart {
		width: 70%;
		height: 5vh;
		/* height: 80rpx; */
		margin-bottom: 1vh;
		font-weight: bold;
		line-height: 5vh;
		background-color: #ffb40b;
	}

	.btnStart-enable {
		background-color: #ffb40b;
	}

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

<style lang="scss" scoped>
	::v-deep .list {
		height: 58vh;
		margin-top: 5px;
	}
</style>