<!-- 
每月挑战 - 月排名列表
http://localhost:5173/card/#/pages/mytz/rankList
https://oss-mbh5.colormaprun.com/card/#/pages/mytz/rankList
 -->
<template>
	<view class="body">
		<view v-if="pageReady" class="content uni-column">
			<view class="page-top uni-column">
				<my-topbar :mcName="ecName" class="topbar-color" @btnBackClick="btnBack"
					@btnInfoClick="btnInfo"></my-topbar>

				<view class="topContent uni-row uni-jcse">
					<view class="tc-month">{{curMonth}}</view>
					<view class="tc-count uni-column">
						<text>挑战次数</text>
						<text>{{realNum}}/{{targetNum}}</text>
					</view>
					<view class="tc-cup" :style="getCupStyle('cup')">
						<view class="cup-gray" :style="getCupStyle('cup-gray')"></view>
					</view>
				</view>
			</view>
			<view class="main uni-column">
				<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>
			</view>

			<my-popup ref="mypopup" :config="cardConfigData.popupRuleConfig"
				:dataList="cardConfigData.popupRuleList"></my-popup>

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

<script>
	import tools from '/common/tools';
	import cardfunc from '/common/cardfunc';
	import {
		localCardConfig
	} from "./cardconfig/test.js";
	import {
		token,
		apiCardBaseQuery,
		apiCurrentMonthlyChallengeQuery,
		apiMonthRankDetailQuery,
		checkResCode,
		checkToken
	} from '/common/api';

	export default {
		data() {
			return {
				cardConfigData: cardfunc.cardConfigData,
				pageReady: false,
				pageName: "rankList",
				firstEnterKey: 'firstEnter-mytz',
				rankKey: "rank-mytz",
				queryObj: {},
				queryString: "",
				token: "",
				tokenValid: false,
				ecId: 0, // 卡片id
				ecName: '', // 卡片名称
				ecDesc: '', // 卡片简介

				month: '', // 月名称
				realNum: 0, // 实际完赛次数
				targetNum: 0, // 要求完赛次数

				cupProgress: 100, // 奖杯进度 （100 - 实际进度，初始值为100）

				dispArrStr: "grad,mapNum", // 要显示的集合范围
				tabItems: ["积分排名", "通关场地排名"],
				rankTypeList: ["grad", "mapNum"],
				tabCurrent: 0,
				tabItemsMark: [],
				rankRsList: ["gradRs", "mapNumRs"],
				rankList: [], // 排名列表
				configParam: {
					tabInitActIndex: 0
				}
			}
		},
		computed: {
			curMonth() {
				var currentDate = new Date();
				var currentMonth = currentDate.getMonth() + 1; // 月份从0开始，所以要加1
				return `${currentMonth}月`;
			}
		},
		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);

			cardfunc.init(this, this.token, this.ecId);
			cardfunc.getCardConfig(this.cardConfigQueryCallback, localCardConfig);
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {},
		onUnload() {},
		methods: {
			cardConfigQueryCallback(cardconfig) {
				this.loadConfig(cardconfig);
				this.getCardBaseQuery();
				this.getCurrentMonthlyChallengeQuery();
				this.monthRankDetailQuery();
				setTimeout(this.dealFirstEnter, 500);
			},
			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.tabInitActIndex != undefined && param.tabInitActIndex >= 0) {
						this.configParam.tabInitActIndex = param.tabInitActIndex;
						this.tabCurrent = param.tabInitActIndex;
					}
				}

				this.pageReady = true;
			},
			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);
					},
				})
			},
			getCupProgress() {
				if (this.targetNum > 0 && this.realNum > 0) {
					if (this.realNum < this.targetNum) {
						const progress = this.realNum / this.targetNum * 100;
						this.cupProgress = 100 - progress;
					} else {
						this.cupProgress = 0;
					}
				} else {
					this.cupProgress = 100;
				}
				// console.log("cupProgress:", this.cupProgress);
			},
			getCupStyle(type) {
				if (!(this.month > 0)) {
					return '';
				}

				let group = 1;
				if (type == 'cup') {
					return `background-image: url("static/cup/${group}/${this.month}.png")`;
				} else if (type == 'cup-gray') {
					return `background-image: url("static/cup/${group}/${this.month}h.png"); height:${this.cupProgress}% ;`;
				}
			},
			// 卡片基本信息查询
			getCardBaseQuery() {
				uni.request({
					url: apiCardBaseQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						ecId: this.ecId
					},
					success: (res) => {
						// console.log("getCardBaseQuery", res);
						const data = res.data.data;
						this.ecName = data.ecName;
						this.ecDesc = data.ecDesc;
					},
					fail: (err) => {
						console.log("getCardBaseQuery err", err);
					},
				});
			},
			// 玩家当前月挑战记录查询
			getCurrentMonthlyChallengeQuery() {
				uni.request({
					url: apiCurrentMonthlyChallengeQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {},
					success: (res) => {
						// console.log("getCurrentMonthlyChallengeQuery", res);
						if (checkResCode(res)) {
							if (res.statusCode == 401) { // 未登录
								this.tokenValid = false;
							} else {
								this.tokenValid = true;
							}

							const data = res.data.data;
							this.month = data.month;
							this.realNum = data.realNum;
							// this.realNum = 2;
							this.targetNum = data.targetNum;

							this.dealNotice(this.realNum);
							this.getCupProgress();
						}
					},
					fail: (err) => {
						console.log("getCurrentMonthlyChallengeQuery err", err);
					},
				});
			},
			// 月挑战排名查询
			monthRankDetailQuery() {
				uni.request({
					url: apiMonthRankDetailQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						dispArrStr: this.dispArrStr
					},
					success: (res) => {
						// console.log("monthRankDetailQuery", res);
						const rankdata = res.data.data;
						this.rankList = rankdata;
					},
					fail: (err) => {
						console.log("monthRankDetailQuery err", err);
					},
				});
			},
			btnBack() {
				// window.history.back();
				const url = `action://to_home/`;
				tools.appAction(url);
			},
			btnInfo() {
				this.$refs.mypopup.popupOpen();
			},
			onTabClick(val) {
				// console.log("onTabClick: ", val);
				this.tabCurrent = val;
			}
		}
	}
</script>

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

	.page-top {
		width: 100%;
		height: 150px;
		padding-top: 36px;
		justify-content: space-between;
		background-image: url("/static/backgroud/top_run.png"), linear-gradient(180deg, #178bff 0%, #004d9b 100%);
		background-repeat: no-repeat;
		background-position: 25px 36px, 0px 0px;
		background-size: auto 150px, contain;
	}

	.topbar-color {
		color: #ffffff;
	}

	.topContent {
		width: 90%;
		height: 130px;
	}

	.tc-month {
		width: 80px;
		height: 80px;
		background: url("/static/mytz/month_bg.png") no-repeat center;
		background-size: contain;
		color: #ff870d;
		font-size: 22px;
		font-weight: 700;
		text-align: center;
		line-height: 100px;
	}

	.tc-count {
		font-size: 14px;
		font-weight: 500;
		color: #FFFFFF;
	}

	.tc-cup {
		width: 70px;
		height: 70px;
		border-radius: 3px;
		border: solid #FFFFFF 1px;
		background-position-x: center;
		background-repeat: no-repeat;
		background-size: 70px auto;
	}

	.cup-gray {
		width: 70px;
		background-position-x: center;
		background-repeat: no-repeat;
		background-size: 70px auto;
		overflow: hidden;
	}

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

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

	.tab-view {
		width: 100%;
		flex-grow: 1;
	}
</style>