<!-- 
成就 v2
http://localhost:5173/card/#/pages/achievement/index2
https://oss-mbh5.colormaprun.com/card/#/pages/achievement/index2
 -->
<template>
	<view class="body">
		<view class="content uni-column">
			<view class="topbar uni-row">
				<uni-icons v-if="showBack" type="left" class="topbar-back" @click="btnBack"></uni-icons>
				<text v-else></text>
				<text>成就</text>
				<text style="color: rgba(46, 133, 236, 1);"></text>
			</view>
			
			<my-tab ref="tab1" :initActIndex="tabCurrent" :tabItems="tabItems" :type="1" @onTabClick="onTabClick"></my-tab>
			
			<view class="main">
				<!-- 挑战 -->
				<view v-if="tabCurrent == 0">
					<view class="norecord" v-if="challengeRs == null || challengeRs.length == 0">暂无记录</view>
					<view class="uni-column" v-for="(item, index) in challengeRs" :key="index">
						<text class="year">{{item.year}}</text>
						<view class="list uni-row">
							<view class="item uni-column" v-for="(item2, index2) in item.monthRs" :key="index2">
								<view class="item-cup" :style="getCupStyle('cup', item2.month)">
									<view class="item-cup-gray"
										:style="getCupStyle('cup-gray', item2.month, getCupProgress(item2.targetNum, item2.realNum))">
									</view>
								</view>
								<view class="item-title uni-row">
									<text class="item-title-month">{{item2.month}}月</text>
									<view class="item-title-divide"></view>
									<text class="item-title-progress">{{item2.realNum}}/{{item2.targetNum}}</text>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 奖牌 -->
				<view v-if="tabCurrent == 1">
					<view class="norecord" v-if="activityRs == null || activityRs.length == 0">暂无记录</view>
					<view class="uni-column" v-for="(item, index) in activityRs" :key="index">
						<text class="year">{{item.year}}</text>
						<view class="list uni-row">
							<view class="item item-bg uni-column" v-for="(item2, index2) in item.aiRs" :key="index2"
								@click="showAchDetail(item2)">
								<view class="item-medal" :style="getMedalStyle(item2.iconUrl)"></view>
								<view class="item-title uni-column">
									<view class="item-title-ainame">{{item2.aiName}}</view>
									<view class="item-title-aitime">{{fmtTime(item2.aiTime)}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 兑换 -->
				<view v-if="tabCurrent == 2">
					<view class="norecord" v-if="exchangeRs == null || exchangeRs.length == 0">暂无记录</view>
					<view class="uni-column" v-for="(item, index) in exchangeRs" :key="index">
						<text class="year">{{item.year}}</text>
						<view class="list uni-row">
							<view class="item uni-column"
								:class="item2.exState==1 ? 'item-convertible' : 'item-converted'"
								v-for="(item2, index2) in item.aiRs" :key="index2" @click="showAchDetail(item2)">
								<view class="item-medal" :style="getMedalStyle(item2.iconUrl)"></view>
								<view class="item-title uni-column">
									<view class="item-title-ainame">{{item2.aiName}}</view>
									<view class="item-title-aitime">{{fmtTime(item2.aiTime)}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>

			</view>
		</view>

		<!-- 页面载入后，弹窗显示新获取的成就  -->
		<my-popup ref="popupNewach" :dataList="popupDataList" @popup-close="onPopupNewachClose"></my-popup>

		<!-- 点击成就列表项后，弹窗显示对应的成就内容  -->
		<my-popup ref="popupAchdet" :dataList="popupAchdet" @popup-close="onPopupAchdetClose"></my-popup>

		<!-- <my-popup-map ref="mypopupmap" :point="point"></my-popup-map> -->

	</view>
</template>

<script>
	import tools from '../../common/tools';

	import {
		token,
		apiMonthlyChallengeQuery,
		apiAchievementQuery,
		apiExchangeListQuery,
		apiExchangeDetailQuery,
		apiUnReadMessageQuery,
		apiReadMessage,
		checkResCode
	} from '../../common/api';

	export default {
		data() {
			return {
				queryObj: {},
				queryString: "",
				token: "",
				tokenValid: false,

				challengeRs: [], // 挑战成就集合
				activityRs: [], // 活动成就集合
				exchangeRs: [], // 兑换记录集合
				unReadMessageRs: [], // 未读消息列表
				mqIdListStr: "", // 已读消息id列表 逗号分隔

				tabItems: ["挑战", "奖牌", "兑换"],
				tabCurrent: 0,
				popupDataList: [], // 弹窗数据：新获取的成就
				popupAchdet: [], // 弹窗数据：用户点击的成就列表项
				point: {
					longitude: 117.022194,
					latitude: 36.661612,
					name: "泉城广场定向赛起始点",
				},
				interval: null,
				showBack: false, // 是否在导航栏显示返回按钮
			}
		},
		computed: {},
		onLoad(query) { // 类型非必填，可自动推导
			// console.log(query);
			this.queryObj = query;
			this.queryString = tools.objectToQueryString(this.queryObj);
			// console.log(queryString);
			this.token = query["token"] ?? token;
			this.tabCurrent = parseInt(query["tabCurrent"] ?? 0);
			this.showBack = query["tabCurrent"] >= 0 ? true : false;

			this.getMonthlyChallengeQuery();
			this.getAchievementQuery();
			this.getExchangeListQuery();
			this.getUnReadMessageQuery();
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {},
		onUnload() {
			if (this.interval != null) {
				clearInterval(this.interval);
				this.interval = null;
			}
		},
		methods: {
			getCupProgress(targetNum, realNum) {
				let cupProgress = 100;
				if (targetNum > 0 && realNum > 0) {
					if (realNum < targetNum) {
						const progress = realNum / targetNum * 100;
						cupProgress = 100 - progress;
					} else {
						cupProgress = 0;
					}
				}
				// console.log("cupProgress:", cupProgress);
				return cupProgress;
			},
			getCupStyle(type, month, cupProgress = 0) {
				if (!(month > 0)) {
					return '';
				}

				let group = 1;
				if (type == 'cup') {
					return `background-image: url("static/cup/${group}/${month}.png")`;
				} else if (type == 'cup-gray') {
					return `background-image: url("static/cup/${group}/${month}h.png"); height:${cupProgress}% ;`;
				}
			},
			getMedalStyle(bgurl) {
				return `background-image: url("${bgurl}")`;
			},
			fmtTime(timestamp, type = 2) {
				return tools.timestampToTime(timestamp * 1000, type);
			},
			// 玩家所有月挑战记录查询
			getMonthlyChallengeQuery() {
				uni.request({
					url: apiMonthlyChallengeQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {},
					success: (res) => {
						// console.log("getMonthlyChallengeQuery", res);

						if (checkResCode(res)) {
							if (res.statusCode == 401) { // 未登录
								this.tokenValid = false;
							} else {
								this.tokenValid = true;
							}

							this.challengeRs = res.data.data;
						}
					},
					fail: (err) => {
						console.log("getMonthlyChallengeQuery err", err)
					},
				});
			},
			// 玩家活动成就查询
			getAchievementQuery() {
				uni.request({
					url: apiAchievementQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {},
					success: (res) => {
						// console.log("getAchievementQuery", res);

						if (checkResCode(res)) {
							if (res.statusCode == 401) { // 未登录
								this.tokenValid = false;
							} else {
								this.tokenValid = true;
							}

							this.activityRs = res.data.data;
						}
					},
					fail: (err) => {
						console.log("getAchievementQuery err", err);
					},
				});
			},
			// 玩家兑换记录查询
			getExchangeListQuery() {
				uni.request({
					url: apiExchangeListQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {},
					success: (res) => {
						// console.log("getExchangeListQuery", res);

						if (checkResCode(res)) {
							if (res.statusCode == 401) { // 未登录
								this.tokenValid = false;
							} else {
								this.tokenValid = true;
							}

							this.exchangeRs = res.data.data;
						}
					},
					fail: (err) => {
						console.log("getExchangeListQuery err", err);
					},
				});
			},
			// 玩家兑换详情查询
			exchangeDetailQuery(oarId) {
				uni.request({
					url: apiExchangeDetailQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						oarId: oarId
					},
					success: (res) => {
						// console.log("exchangeDetailQuery", res);
						if (checkResCode(res)) {
							const data = res.data.data;

							// 弹窗已获取数据且可兑换状态时，不再更新弹窗数据
							if (this.popupAchdet.length > 0 && this.popupAchdet[0].qrCode != "" && data
								.qrCode != "") {
								return;
							}

							this.popupAchdet = [{
								"type": 4,
								"data": {
									"title": "兑换",
									"img": data.iconUrl,
									"content": data.aiName,
									"qrCode": data.qrCode,
									"exTime": this.fmtTime(data.exTime, 0)
								},
							}];

							if (data.qrCode == "") { // 已兑换
								clearInterval(this.interval);
								this.interval = null;
							}

							if (!this.$refs.popupAchdet.isOpen) {
								setTimeout(() => {
									this.$refs.popupAchdet.popupOpen();
								}, 100);
							}
						}
					},
					fail: (err) => {
						console.log("exchangeDetailQuery err", err);
					},
				});
			},
			// 未读消息列表查询
			getUnReadMessageQuery() {
				uni.request({
					url: apiUnReadMessageQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {},
					success: (res) => {
						// console.log("getUnReadMessageQuery", res);

						if (checkResCode(res)) {
							if (res.statusCode == 401) { // 未登录
								this.tokenValid = false;
							} else {
								this.tokenValid = true;
							}

							this.unReadMessageRs = res.data.data;
							this.mqIdListStr = "";
							for (var i = 0; i < this.unReadMessageRs.length; i++) {
								let popupData = {
									type: 3,
									data: {}
								};
								if (this.unReadMessageRs[i].mqType == 1) { // 消息类型  1: 成就
									popupData.data.title = "恭喜";
								}
								popupData.data.img = this.unReadMessageRs[i].iconUrl;
								popupData.data.content = "恭喜获得成就 \r\n" + this.unReadMessageRs[i].aiName;
								this.popupDataList.push(popupData);

								this.mqIdListStr += this.unReadMessageRs[i].mqId;
								if (i < this.unReadMessageRs.length - 1) {
									this.mqIdListStr += ",";
								}
							}

							if (this.popupDataList.length > 0) {
								this.$refs.popupNewach.popupOpen();
							}
						}
					},
					fail: (err) => {
						console.log("getUnReadMessageQuery err", err);
					},
				});
			},
			// 标记消息已读
			readMessage() {
				uni.request({
					url: apiReadMessage,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						"mqIdListStr": this.mqIdListStr
					},
					success: (res) => {
						// console.log("readMessage", res);
					},
					fail: (err) => {
						console.log("readMessage err", err);
					},
				});
			},
			showAchDetail(data) {
				// console.log("showAchDetail", data);
				this.popupAchdet.length = 0;

				if (this.tabCurrent == 1) { // 奖牌
					let popupData = {
						type: 3,
						data: {}
					};
					popupData.data.title = "恭喜";
					popupData.data.img = data.iconUrl;
					popupData.data.content = "恭喜获得成就 \r\n" + data.aiName;
					this.popupAchdet.push(popupData);
					this.$refs.popupAchdet.popupOpen();
				}

				if (this.tabCurrent == 2) { // 兑换
					this.exchangeDetailQuery(data.oarId);
					this.interval = setInterval(this.exchangeDetailQuery, 2000, data.oarId);
				}
			},
			onPopupNewachClose() {
				// console.log("onPopupNewachClose");
				this.readMessage();
			},
			onPopupAchdetClose() {
				// console.log("onPopupAchdetClose");

				if (this.interval != null) {
					clearInterval(this.interval);
					this.interval = null;
				}

				if (this.tabCurrent == 2) { // 兑换
					this.getExchangeListQuery();
				}
			},
			btnBack() {
				window.history.back();
			},
			onTabClick(val) {
				// console.log("onTabClick: ", val);
				this.tabCurrent = val;
			},
			test() {
				// this.$refs.mypopupmap.popupOpen();
				const url =
					`action://to_map_app?title=${this.point.name}&latitude=${this.point.latitude}&longitude=${this.point.longitude}`;
				// window.location.href = url;
				tools.appAction(url);
			}
		}
	}
</script>


<style scoped>
	.content {
		width: 100vw;
		height: 100vh;
		justify-content: flex-start;
	}

	.topbar {
		width: 90%;
		margin-top: 72rpx;
		justify-content: space-between;
		font-weight: 550;
		color: #333333;
		font-size: 18px;
	}
	
	.topbar-back {
		width: 43rpx;
		height: 43rpx;
		color: inherit !important;
		font-size: 48rpx !important;
		/* opacity: 0; */
	}

	.main {
		width: 90%;
		padding-top: 30rpx;
		padding-bottom: 30rpx;
	}

	.norecord {
		font-weight: 500;
		color: #818181;
		font-size: 14px;
		text-align: center;
		line-height: 80vh;
	}

	.year {
		width: 100%;
		margin-left: 20rpx;
		text-align: left;
		font-weight: 550;
		color: #818181;
		font-size: 16px;
	}

	.list {
		width: 100%;
		padding-bottom: 10rpx;
		flex-wrap: wrap;
		justify-content: flex-start;
	}

	.item {
		width: 31.85%;
		margin: 20rpx 5rpx;
	}

	.item-bg {
		background: #e7ecef;
		border-radius: 5px;
	}

	.item-cup {
		width: 28vw;
		height: 28vw;
		/* background: #e7ecef; */
		border-radius: 5px;
		background-image: url("/static/cup/1/004.png");
		background-position-x: center;
		/* background-position-y: center; */
		background-repeat: no-repeat;
		background-size: 100% auto;
		/* background-clip: padding-box; */

		mask-image: url('/static/backgroud/mask.png');
		mask-size: 100%;
		mask-repeat: no-repeat;
		mask-clip: padding-box;
	}

	.item-cup-gray {
		width: 100%;
		/* height: 60%; */
		background-image: url("/static/cup/1/004h.png");
		background-position-x: center;
		background-repeat: no-repeat;
		background-size: 100% auto;
		overflow: hidden;
		/* filter: grayscale(1); */
	}

	.item-medal {
		width: 20vw;
		height: 20vw;
		margin-top: 25rpx;
		background-position-x: center;
		/* background-position-y: center; */
		background-repeat: no-repeat;
		background-size: auto 100%;
	}

	.item-title {
		width: 100%;
		margin-top: 10rpx;
		justify-content: center;
	}

	.item-title-month {
		color: #333333;
		font-size: 14px;
		font-weight: 550;
	}

	.item-title-divide {
		width: 4px;
		height: 14px;
		margin: 0 12rpx;
		background: #c6c6c6;
		border-radius: 2px;
	}

	.item-title-progress {
		color: #818181;
		font-size: 13px;
		font-weight: 500;
	}

	.item-title-ainame {
		margin-top: 12rpx;
		font-weight: 500;
		color: #333333;
		font-size: 12px;
	}

	.item-title-aitime {
		margin-top: 12rpx;
		margin-bottom: 20rpx;
		color: #818181;
		font-size: 11px;
	}

	.item-convertible {
		background: url("/static/medal/convertible.png") #e7ecef no-repeat;
		background-size: 30%;
		border-radius: 5px;
	}

	.item-converted {
		background: url("/static/medal/converted.png") #e7ecef no-repeat;
		background-size: 30%;
		border-radius: 5px;
	}
</style>