<!-- 
每月挑战 - 月排名列表
http://localhost:5173/card/#/pages/mytz/rankList?id=3
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="title" class="topbar-color" @btnBackClick="btnBack"
					@btnInfoClick="btnInfo"></my-topbar>

				<view class="topContent uni-row uni-jcse">
					<view class="tc-monthBox uni-column uni-jcc" @click="onMonthBoxClick">
						<view class="tc-monthName">{{selectMonthName}}</view>
						<view class="tc-monthRank">查询排行榜</view>
					</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>

			<uni-popup ref="popupMonthPick" :mask-click="false" maskBackgroundColor="rgba(0, 0, 0, 0.6)">
				<view class="uni-column uni-jcse popupMonthPick">
					<view class="uni-row uni-jcsb pmp-top">
						<view class="pmp-title">选择月排行榜</view>
						<view class="pmp-fullyear" @click="onMonthPick(0)">查看全年</view>
					</view>
					<view class="uni-row uni-jcsa pmp-main">
						<view v-for="index in 12" :key="index" :class="index <= currentMonth ? 'tc-monthBox-small' : 'tc-monthBox-small-gray'">
							<view class="tc-monthName-small" @click="onMonthPick(index)">{{index}}月</view>
						</view>
					</view>
				</view>
			</uni-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: '', // 卡片简介

				currentYear: 0,
				currentMonth: 0,
				selectYear: 0,
				selectMonth: 0,
				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: {
			selectMonthName() {
				if (this.selectMonth > 0) {
					return `${this.selectMonth}月`;
				}
				else {
					return this.selectYear;
				}
			},
			title() {
				if (this.selectMonth > 0) {
					return `${this.selectMonth}月挑战赛`;
				}
				else {
					return `${this.selectYear}年挑战赛`;
				}
			},
		},
		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.getCurYearMonth();

			cardfunc.init(this, this.token, this.ecId);
			cardfunc.getCardConfig(this.cardConfigQueryCallback, localCardConfig);
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {},
		onUnload() {},
		methods: {
			getCurYearMonth() {
				const currentDate = new Date();
				const currentYear = currentDate.getFullYear();
				const currentMonth = currentDate.getMonth() + 1; // 月份从0开始，所以要加1
				// console.log("[getCurYearMonth]", currentYear, currentMonth);
				this.currentYear = currentYear;
				this.currentMonth = currentMonth;
				this.selectYear = currentYear;
				this.selectMonth = currentMonth;
			},
			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.selectMonth >= 0)) {
					return '';
				}

				let group = 1;
				if (type == 'cup') {
					return `background-image: url("static/cup/${group}/${this.selectMonth}.png")`;
				} else if (type == 'cup-gray') {
					return `background-image: url("static/cup/${group}/${this.selectMonth}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: {
						year: this.selectYear,
						month: this.selectMonth,
					},
					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.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: {
						year: this.selectYear,
						month: this.selectMonth,
						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;
			},
			onMonthBoxClick() {
				this.$refs.popupMonthPick.open();
			},
			onMonthPick(month) {
				// console.log("[onMonthPick] month", month);
				if (month <= this.currentMonth) {
					this.selectMonth = month;
					this.$refs.popupMonthPick.close();
					
					this.getCurrentMonthlyChallengeQuery();
					this.monthRankDetailQuery();
				} else {
					uni.showToast({
						icon: "none",
						title: "暂无该月记录",
						duration: 1000
					})
				}
			}
		}
	}
</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-monthBox {
		width: 80px;
		height: 80px;
		background: url("/static/mytz/month_bg.png") no-repeat center;
		background-size: contain;
		color: #ff870d;
	}

	.tc-monthName {
		margin-top: 18px;
		font-size: 22px;
		font-weight: 700;
	}

	.tc-monthRank {
		font-size: 12px;
		font-weight: 500;
	}

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

	.popupMonthPick {
		width: 90vw;
		height: 200px;
		background-color: #FEFBF6;
		border-radius: 25px;
	}

	.pmp-top {
		width: 90%;
		font-size: 16px;
	}

	.pmp-main {
		width: 90%;
		height: 120px;
		flex-wrap: wrap;
	}

	.pmp-title {
		font-weight: 500;
	}

	.pmp-fullyear {
		padding: 5px 10px;
		border-radius: 8px;
		border: 1px solid rgba(255, 135, 13, 1);
		color: #FF870D;
		font-weight: 500;
	}

	.tc-monthBox-small {
		width: 50px;
		height: 50px;
		flex-shrink: 0;
		background: url("/static/mytz/month_bg.png") no-repeat center;
		background-size: contain;
		color: #ff870d;
	}

	.tc-monthBox-small-gray {
		width: 50px;
		height: 50px;
		flex-shrink: 0;
		background: url("/static/mytz/month_bg_gray.png") no-repeat center;
		background-size: contain;
		color: #C4C4C4;
	}

	.tc-monthName-small {
		margin-top: 20px;
		font-size: 16px;
		font-weight: 700;
		text-align: center;
	}
</style>