<!-- 
[游戏] 网格赛事 - 排名列表
http://localhost:5173/card/#/pages/game/grid/rankList
https://oss-mbh5.colormaprun.com/card/#/pages/game/grid/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" :showRule="true" @btnBackClick="btnBack"
					@btnInfoClick="btnInfo"></my-topbar>
			</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> -->
				<my-tab v-if="tabPageItems.length > 0" ref="tabPage" class="tabPage" :tabItems="tabPageItems" :type="0"
					:initActIndex="tabPageInitActIndex" @onTabClick="onTabPageClick" :fontSize="14"></my-tab>

				<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]" :styleType="ranklistStyleType"></my-ranklist>
					</template>
				</view>

				<view v-if="ranklistStyleType == 1 && selfRank" class="btmSelfInfo uni-row uni-jcsa">
					<image class="btmSelfInfo-corner" mode="aspectFit" src="/static/custom/yuedong/yd.png"></image>
					<view class="bsi-box uni-row uni-jcsb">
						<view class="uni-row">
							<view class="bsi-headimg"></view>
							<view class="uni-column uni-ais">
								<view class="bsi-name">{{selfRank.userName}}</view>
								<view class="bsi-score">
									<text class="bsi-score-type">{{tabItems[tabCurrent]}}</text>
									<text>{{rankfunc.fmtRankNumByType(selfRank.inRankNum, rankTypeList[tabCurrent])}}</text>
								</view>
							</view>
						</view>
						<view class="bsi-ranknum">第 {{selfRank.rankNum}} 名</view>
					</view>
				</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 rankfunc from '/common/rankfunc';
	import {
		localCardConfig
	} from "./cardconfig/test2.js";
	import {
		teamName
	} from '/common/define';
	import {
		token,
		apiMatchRsDetailQuery,
		apiCardRankDetailQuery,
		apiCompStatisticQuery,
		apiIsAllowMcSignUp,
		apiUserJoinCardQuery,
		checkResCode
	} from '/common/api';

	export default {
		data() {
			return {
				rankfunc: rankfunc,
				cardConfigData: cardfunc.cardConfigData,
				pageReady: false,
				pageName: "rankList",
				messageKey: "message-game-grid",
				queryObj: {},
				queryString: "",
				token: "",
				ovtype: "",
				cardconfig: {}, // 卡片配置
				userconfig: {}, // 用户配置

				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,

				tabPageItems: [],
				// tabPageItems: ["赛事", "排行榜"],
				tabPageCurrent: 0,
				tabPageInitActIndex: 1,

				teamType: 0, // 队伍类型
				dispArrStr: "totalDistance,totalCp,totalSysPoint,fastPace", // 要显示的集合范围
				tabItems: ["总里程", "打点数", "百味豆", "配速"],
				rankTypeList: ["totalDistance", "totalCp", "totalSysPoint", "fastPace"],
				tabCurrent: 0,
				tabItemsMark: [],
				/* tabItemsMark: [{
					textColor: "#ff6203",
					icon: "static/common/award.png"
				}], */
				rankRsList: ["totalDistanceRs", "totalCpRs", "totalSysPointRs", "fastPaceRs"],

				configParam: {
					labelTicketName: "我的奖券",
					labelAwardAddress: "兑奖地址",
					// labelGoodsList: "兑换商品",
					tabInitActIndex: 0
				},
				ranklistStyleType: 0, // 排名列表样式
				selfRank: null // 个人成绩
			}
		},
		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"] ?? "";

			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}`);
			},
			clear() {
				if (this.interval != null) {
					clearInterval(this.interval);
					this.interval = null;
				}
			},
			cardConfigQueryCallback(cardconfig) {
				this.cardconfig = cardconfig;
				// cardfunc.getUserConfig(this.userConfigQueryCallback, localUserConfig);
				this.loadConfig();
				this.matchRsDetailQuery();
			},
			/* userConfigQueryCallback(userconfig) {
				this.userconfig = userconfig;
				this.loadConfig();
				this.matchRsDetailQuery();
			}, */
			loadConfig() {
				this.loadCardConfig(this.cardconfig);
				this.loadUserConfig(this.userconfig);
				this.pageReady = true;
			},
			loadCardConfig(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) {
					return;
				}

				// 加载CSS样式
				const css = config.css;
				if (css != undefined && css.length > 0) {
					tools.loadCssCode(css);
				}

				// 加载TAB
				const tabPageItems = config.tabPageItems;
				if (tabPageItems != undefined) {
					this.tabPageItems = tabPageItems;
				}

				// 加载成绩参数
				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;
					}
					if (rankParam.ranklistStyleType != undefined && rankParam.ranklistStyleType > 0) {
						this.ranklistStyleType = rankParam.ranklistStyleType;
					}
				}
				// 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;
					}
					if (param.tabInitActIndex != undefined && param.tabInitActIndex >= 0) {
						this.configParam.tabInitActIndex = param.tabInitActIndex;
						this.tabCurrent = param.tabInitActIndex;
					}
				}
			},
			loadUserConfig(userconfig) {
				if (!userconfig) {
					console.log("[loadUserConfig] userconfig 为空");
					return;
				}

				const config = cardfunc.parseCardConfig(userconfig);
				console.log("[loadUserConfig] userconfig:", config);

				// 加载用户的弹窗数据
				cardfunc.loadUserPopupRule(config);
			},
			// 获取倒计时
			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;

						this.getSelfRank();
					},
					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");
			},
			onTabPageClick(val) {
				console.log("onTabClick: ", val);
				// this.tabPageCurrent = val;
				if (val == 0) {
					const url = '/pages/game/grid/grid?' + this.queryString;
					tools.appAction(url, "uni.navigateTo");
				}
			},
			onTabClick(val) {
				// console.log("onTabClick: ", val);
				this.tabCurrent = val;
				this.getSelfRank();
			},
			getSelfRank() {
				const ranktype = this.rankRsList[this.tabCurrent];
				const rs = this.rankList[ranktype];
				// console.log("[getSelfRank] rs", rs);
				if (rs) {
					this.selfRank = tools.objArrGetObjByValue(rs, "isSelf", 1);
					console.log("[getSelfRank] self", this.selfRank);
				}
			}
		}
	}
</script>

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

	.page-top {
		width: 100%;
		height: 60px;
		padding-top: 36px;
		justify-content: space-between;
		background: linear-gradient(135deg, #FFEF9E 0%, #FFFCF2 45.14%, #FFF4D4 100%);
	}

	.topbar-color {
		color: #000000;
	}

	.main {
		width: 100%;
		flex-grow: 1;
		justify-content: space-around;
	}

	.tabPage {
		/* width: 100%; */
	}

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

	.btmSelfInfo {
		position: absolute;
		bottom: 0;
		width: 100%;
		height: 80px;
		background-color: #c7e848;
		border-radius: 10px 10px 0 0;
	}

	.btmSelfInfo-corner {
		position: absolute;
		right: 0px;
		top: -38px;
		width: 180px;
		height: 50px;
	}

	.bsi-box {
		width: 80%;
	}

	.bsi-infoBox {
		/* width: 40%; */
	}

	.bsi-headimg {
		width: 40px;
		height: 40px;
		margin-right: 10px;
		border-radius: 50%;
		background-color: #9980bf;
	}

	.bsi-name {
		font-size: 16px;
		font-weight: 500;
		color: #000000;
	}

	.bsi-score {
		font-size: 12px;
		font-weight: 500;
		color: #000000;
	}

	.bsi-score-type {
		margin-right: 5px;
	}

	.bsi-ranknum {
		font-size: 18px;
		font-weight: 500;
		color: #000000;
	}

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