<!-- 
[模板] 样式1 - 排名列表
http://localhost:5173/card/#/pages/tpl/style1/rankList
https://oss-mbh5.colormaprun.com/card/#/pages/tpl/style1/rankList
 -->
<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" :showMessage="cardConfigData.popupMessageList.length > 0" 
					@btnBackClick="btnBack" @btnInfoClick="btnInfo" @btnMessageClick="btnMessage"></my-topbar>
				
				<view class="topbtm uni-row">
					<!-- <view class="topbtm-egg bgcolor-main" @click="btnMyEgg"></view> -->
					<view class="topbtm-egg" @click="btnMyEgg">{{configParam.labelTicketName}}</view>
					<text class="topbtm-name bgcolor-main">{{nickName}}</text>
					<!-- <view class="topbtm-egg bgcolor-main" @click="btnExchg">兑换地址</view> -->
					<view class="topbtm-egg" v-if="configParam.labelGoodsList && configParam.labelGoodsList.length > 0" @click="btnGoodsList">{{configParam.labelGoodsList}}</view>
					<view class="topbtm-egg" v-else @click="btnExchg">{{configParam.labelAwardAddress}}</view>
				</view>
			</view>
			<view class="main uni-column">
				<view class="main-bar uni-row uni-jcse">
					<text>题目输出：{{all_totalAnswerNum}}</text>
					<text>总里程：{{fmtDistanct(all_totalDistance)}}km</text>
					<text>总打点：{{all_totalCp}}</text>
					<text>总百味豆：{{all_totalSysPoint}}</text>
				</view>
				<!-- <view>>> {{rankList}}</view> -->
				<my-tab ref="tab" :tabItems="tabItems" :tabItemsMark="tabItemsMark" :type="0"
					:initActIndex=configParam.tabInitActIndex @onTabClick="onTabClick" :fontSize="12"></my-tab>
				
				<view class="tab-view uni-column">
					<template v-for="(item, index) in rankRsList" :key="index">
						<my-ranklist v-show="tabCurrent === index" :rankRs="rankList[item]"
							:rank-type="rankTypeList[index]"></my-ranklist>
					</template>
				</view>

				<button class="btnBack bgcolor-main" @click="btnStartGame">{{btnStartGameText}}</button>
			</view>
			
			<my-popup ref="mypopup" :config="cardConfigData.popupRuleConfig" :dataList="cardConfigData.popupRuleList" :acttime="acttime"></my-popup>
			<my-popup ref="mypopupExchg" :config="cardConfigData.popupExchgConfig" :dataList="cardConfigData.popupExchgList"></my-popup>
			<my-popup ref="mypopupMessage" :config="cardConfigData.popupMessageConfig" :dataList="cardConfigData.popupMessageList" @noMoreRemindersClick="onNoMoreRemindersClick"></my-popup>
			
		</view>
	</view>
</template>

<script>
	import tools from '/common/tools';
	import cardfunc from '../../../common/cardfunc';
	import { localCardConfig } from "./cardconfig/test.js";
	import { teamName } from '/common/define';
	import {
		token,
		apiMatchRsDetailQuery,
		apiCardRankDetailQuery,
		apiCompStatisticQuery,
		apiIsAllowMcSignUp,
		apiUserJoinCardQuery,
		checkResCode
	} from '/common/api';
	
	export default {
		data() {
			return {
				cardConfigData: cardfunc.cardConfigData,
				pageReady: false,
				pageName: "rankList",
				firstEnterKey: 'firstEnter-tpl-style1',
				rankKey: "rank-tpl-style1",
				messageKey: "message-tpl-style1",
				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: [], // 卡片对应活动集合
				
				isJoin: null, // 是否报名
				btnStartGameText: "",
				
				all_totalDistance: 0, // 赛事所有人累计里程，单位米
				all_totalRightAnswerNum: 0, // 赛事所有人正确答题数（校园文化输出）
				all_totalAnswerNum: 0, // 赛事所有人答题数（校园文化输出）
				all_totalCp: 0, // 赛事中所有人打点数
				all_totalSysPoint: 0, // 赛事中所有人百味豆
				
				mcState: 0 ,	// 赛事/活动状态 0: 未开始  1: 进行中  2: 已结束
				allowMcSignUp: false,	// 是否允许重新分组
				countdown: "", // 倒计时
				rankList: {}, // 排名列表
				interval: null,
				
				teamType: 0, // 队伍类型
				dispArrStr: "totalDistance,totalCp,totalSysPoint,fastPace", // 要显示的集合范围
				tabItems: ["总里程", "打点数", "百味豆", "配速"],
				rankTypeList: ["totalDistance", "totalCp", "totalSysPoint", "fastPace"],
				tabCurrent: 0,
				tabItemsMark: [{
					textColor: "#ff6203",
					icon: "static/common/award.png"
				}],
				rankRsList: ["totalDistanceRs", "totalCpRs", "totalSysPointRs", "fastPaceRs"],
				
				
				configParam: {
					labelTicketName: "我的奖券",
					labelAwardAddress: "兑奖地址",
					// labelGoodsList: "兑换商品",
					tabInitActIndex: 0
				}
			}
		},
		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);
			
			this.messageKey += "-" + this.ecId;
			console.log("messageKey:", this.messageKey);
			
			cardfunc.init(this, this.token, this.ecId);
			cardfunc.getCardConfig(this.cardConfigQueryCallback, localCardConfig);
			
			this.dealOvtype();
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {
			// this.dealFirstEnter();
			// this.$refs.mypopupMessage.popupOpen();
		},
		onShow() {
			this.getUserJoinCardQuery();
		},
		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;
				}
			},
			cardConfigQueryCallback(cardconfig) {
				this.loadConfig(cardconfig);
				cardfunc.unReadMessageQuery(this.unReadMessageQueryCallback);
				this.matchRsDetailQuery();
				setTimeout(this.dealFirstEnter, 500);
			},
			unReadMessageQueryCallback(unReadMessage, mqIdListStr) {
				// console.log("[unReadMessageQueryCallback] unReadMessage", unReadMessage);
				if (unReadMessage.length > 0) {
					this.messageKey += mqIdListStr;
					// console.log("[unReadMessageQueryCallback] messageKey:", this.messageKey);
					const messageValue = uni.getStorageSync(this.messageKey);
					// console.log("[unReadMessageQueryCallback] messageValue:", messageValue);
					if (!messageValue) {
						this.$refs.mypopupMessage.popupOpen();
						// uni.setStorageSync(this.messageKey, true);
					}
				}
			},
			loadConfig(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) {
					this.pageReady = true;
					return;
				}
				
				// 加载CSS样式
				const css = config.css;
				if (css != undefined && css.length > 0) {
					tools.loadCssCode(css);
				}
				
				// 加载成绩参数
				const rankParam = config.rankParam;
				if (rankParam != undefined) {
					if (rankParam.tabItemsMark != undefined) {
						this.tabItemsMark = rankParam.tabItemsMark;
					}
					if (rankParam.dispArrStr != undefined && rankParam.dispArrStr.length > 0) {
						this.dispArrStr = rankParam.dispArrStr;
						// console.log("[loadConfig] dispArrStr:", rankParam.dispArrStr);
					}
					if (rankParam.tabItems != undefined && rankParam.tabItems.length > 0) {
						this.tabItems = rankParam.tabItems;
						// console.log("[loadConfig] tabItems:", rankParam.tabItems);
					}
					if (rankParam.rankTypeList != undefined && rankParam.rankTypeList.length > 0) {
						this.rankTypeList = rankParam.rankTypeList;
					}
					if (rankParam.rankRsList != undefined && rankParam.rankRsList.length > 0) {
						this.rankRsList = rankParam.rankRsList;
					}
				}
				// console.log("[loadConfig] rankParam:", rankParam);
				
				// 加载页面参数
				const param = config.param;
				if (param != undefined) {
					if (param.labelTicketName != undefined && param.labelTicketName.length > 0) {
						this.configParam.labelTicketName = param.labelTicketName;
					}
					if (param.labelAwardAddress != undefined && param.labelAwardAddress.length > 0) {
						this.configParam.labelAwardAddress = param.labelAwardAddress;
					}
					if (param.labelGoodsList != undefined && param.labelGoodsList.length > 0) {
						this.configParam.labelGoodsList = param.labelGoodsList;
					}
				}
				
				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 = "距结束 --天--小时";
				}
			},
			// 格式化 距离
			fmtDistanct(val) {
				return Math.round(val * 100 / 1000) / 100;
				/* if (val < 10000)
					return Math.round(val * 10 / 1000) / 10;
				else
					return Math.round(val / 1000); */
			},
			fmtMcTime(timestamp) {
				return tools.fmtMcTime(timestamp);
			},
			// 获取活动时间
			getActtime() {
				this.acttime = tools.getActtime(this.beginSecond, this.endSecond);
				// console.log("acttime", this.acttime);
			},
			getTeamName(teamType, teamIndex) {
				return teamName[teamType][teamIndex];
			},
			// 卡片对应线上赛多个活动查询
			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.compStatisticQuery();
							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 = rankdata;
					},
					fail: (err) => {
						console.log("getCardRankDetailQuery err", err);
					},
				});
			},
			// 赛事总成绩统计查询
			compStatisticQuery() {
				uni.request({
					url: apiCompStatisticQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						mcId: this.mcId
					},
					success: (res) => {
						// console.log("compStatisticQuery", res);
						if (res.data.code == 0) {
							const data = res.data.data;
							this.all_totalDistance = data.totalDistance;
							this.all_totalRightAnswerNum = data.totalRightAnswerNum;
							this.all_totalAnswerNum = data.totalAnswerNum;
							this.all_totalCp = data.totalCp;
							this.all_totalSysPoint = data.totalSysPoint;
						}
					},
					fail: (err) => {
						console.log("compStatisticQuery 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 = "我要比赛";
								this.btnStartGameText = "选择场地";
							} else {	// 未报名
								this.btnStartGameText = "我要报名";
							}
						}
					},
					fail: (err) => {
						console.log("getUserJoinCardQuery err", err)
					},
				});
			},
			onNoMoreRemindersClick() {
				this.$refs.mypopupMessage.popupClose();
				uni.setStorageSync(this.messageKey, true);
			},
			btnBack() {
				const url = `action://to_home/`;
				tools.appAction(url);
			},
			btnStartGame() {
				if (this.isJoin) {	// 已报名
					const url = "/pages/tpl/style1/rankOverview?" + this.queryString;
					tools.appAction(url, "uni.navigateTo");
				} else {	// 未报名
					const url = "/pages/tpl/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();
			},
			btnMyEgg() {
				const url = "/pages/achievement/index2?tabCurrent=2&" + this.queryString;
				tools.appAction(url, "uni.navigateTo");
			},
			btnExchg() {
				this.$refs.mypopupExchg.popupOpen();
			},
			btnGoodsList() {
				this.queryObj.from = "/pages/tpl/style1/rankList";
				this.queryString = tools.objectToQueryString(this.queryObj);
				const url = "/pages/exchange/style1/goodsList?" + this.queryString;
				tools.appAction(url, "uni.navigateTo");
			},
			onTabClick(val) {
				// console.log("onTabClick: ", val);
				this.tabCurrent = val;
			}
		}
	}
</script>

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

	.page-top {
		width: 100%;
		height: 170px;
		padding-top: 36px;
		justify-content: space-between;
		background-image: url("/static/backgroud/top_bg2.png");
		background-repeat: no-repeat;
		background-position: center;
		background-size: cover;
	}

	.topbar-color {
		color: #5b9100;
	}
	
	.topbtm {
		width: 100%;
		margin-bottom: 5px;
		justify-content: space-around;
	}
	
	.topbtm-name {
		max-width: 300rpx;
		padding: 3px 12px;
		background-color: #9fda39;
		border-radius: 5px;
		text-align: center;
		font-weight: 500;
		color: #497400;
		font-size: 14px;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	.topbtm-egg {
		width: 60px;
		padding: 3px 12px;
		background-color: #9fda39;
		border-radius: 50px;
		text-align: center;
		color: #497400;
		font-size: 14px;
	}
	
	.topbtm-null {
		width: 60px;
		padding: 3px 12px;
	}
	
	.cal {
		width: 46rpx;
		height: 46rpx;
		margin-right: 20rpx;
	}
	
	.main {
		width: 100%;
		flex-grow: 1;
		justify-content: space-around;
	}
	
	.main-bar {
		width: 100%;
		height: 21px;
		background-color: #d8e8c6;
		
		font-size: 10px;
		font-weight: 500;
		color: #3d6706;
	}

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

	.tab-view {
		width: 100%;
		flex-grow: 1;
	}

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