<!-- 
成就 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 class="topbar-back" v-else></text>
				<text>成就</text>
				<text class="topbar-back"></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="norecord2" v-if="item.monthRs == null || item.monthRs.length == 0">暂无记录</view>
						<view class="list uni-row" v-else>
							<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="norecord2" v-if="item.aiRs == null || item.aiRs.length == 0">暂无记录</view>
						<view class="list uni-row" v-else>
							<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="norecord2" v-if="item.aiRs == null || item.aiRs.length == 0">暂无记录</view>
						<view class="list uni-row" v-else>
							<view class="item uni-column"
								:class="getConvertClass(item2.exState)"
								v-for="(item2, index2) in item.aiRs" :key="index2" @click="showAchDetail(item2)">
								<view class="item-exchange" :style="getMedalStyle(item2.iconUrl)"></view>
								<view class="item-title uni-column">
									<view class="item-title-ainame" style="margin-top: 3rpx;">{{item2.aiName}}</view>
									<view class="item-title-ainame2">{{item2.sourceName}}</view>
									<view class="item-title-aitime2">{{fmtTime(item2.aiTime)}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>

			</view>
		</view>

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

		<!-- 点击成就列表项后，弹窗显示对应的成就内容  -->
		<my-popup ref="popupAchdet" :config="popupConfig" :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,
				popupConfig: {	// 弹窗配置
					height: "460px"
				},
				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;

			// tools.removeCssCode();
			
			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}")`;
			},
			// exState: 1 可兑 2 已兑 3 临期 4 过期
			getConvertClass(exState) {
				let cls = '';
				if (exState == 1) {
					cls = 'item-convertible';
				} else if (exState == 2) {
					cls = 'item-converted';
				} else if (exState == 3) {
					cls = 'item-nearExpiration';
				} else if (exState == 4) {
					cls = 'item-expired';
				}
				return cls;
			},
			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].data.exState == 1 && data
								.exState == 1) {
								return;
							}
							// 弹窗已获取数据且临期状态时，不再更新弹窗数据
							if (this.popupAchdet.length > 0 && this.popupAchdet[0].data.exState == 3 && data
								.exState == 3) {
								return;
							}
							
							this.popupAchdet = [{
								"type": 4,
								"data": {
									"title": "兑换",
									"img": data.iconUrl,	// 对应图标url
									"content": data.aiName,	// 兑换品Name
									"aiTime": data.aiTime,	// 获得成就时间戳
									"qrCode": data.qrCode,	// 本系统生成二维码对应字符串，已核销为空
									"qrCodeExTime": data.qrCodeExTime,	// 二维码过期时间戳,已核销为0
									"exState": data.exState,// 1 可兑 2 已兑 3 临期 4 过期
									"exTime": data.exTime,	// 核销时间戳，未核销时间为0 
									"expireTime": data.expireTime,	// 兑换过期时间,时间戳
									"sourceName": data.sourceName,	// 兑换对应来源名称
									"verfType": data.verfType,	// 兑换券展示类型  1 本系统核销  2 赞助商提供码核销 3 赞助商不提供码核销
									"cName": data.cName,	// 对应赞助商名称
									"cDesc": data.cDesc,	// 对应赞助商提供本兑换券简介
									"otherSerCode": data.otherSerCode,	// verfType=2有效，赞助商提供数字码
									"sponsorsLogo": data.cUrl,	// 对应赞助商图标
								},
							}];

							if (data.exState == 2 || data.exState == 4) { // 已兑换 or 已过期
								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: {
						relationType: 1,	// 类型 1 成就 2 卡片
					},
					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.popupDataList.length = 0;
							this.mqIdListStr = "";
							for (var i = 0; i < this.unReadMessageRs.length; i++) {
								let popupData = {
									type: 3,
									data: {}
								};
								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) { // 奖牌
					if (data.isCertificate == 1) {
						let queryObj = this.queryObj;
						queryObj.certStyleType = data.certStyleType;
						queryObj.oarId = data.oarId;
						// console.log("queryObj", queryObj);
						const queryString = tools.objectToQueryString(queryObj);
						// console.log("queryString", queryString);
						const url = "/pages/achievement/ecert/ecert?" + queryString;
						tools.appAction(url, "uni.navigateTo");
					} else {
						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}`;
				tools.appAction(url);
			} */
		}
	}
</script>


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

	.topbar {
		width: 90%;
		margin-top: 40px;
		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;
	}

	.norecord2 {
		font-weight: 500;
		color: #818181;
		font-size: 14px;
		text-align: center;
		line-height: 36px;
	}
	
	.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-exchange {
		width: 20vw;
		height: 20vw;
		margin-top: 25rpx;
		background-position-x: center;
		background-position-y: center;
		background-repeat: no-repeat;
		background-size: 100% auto;
	}
	
	.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 {
		max-width: 90%;
		margin-top: 12rpx;
		font-weight: 500;
		color: #333333;
		font-size: 12px;
		white-space: nowrap;
		overflow: hidden;
		/* text-overflow: ellipsis; */
	}

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

	.item-title-ainame2 {
		width: 196rpx;
		margin-top: 3rpx;
		font-weight: 500;
		color: #818181;
		font-size: 11px;
		text-align: center;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.item-title-aitime2 {
		margin-top: 0rpx;
		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;
	}
	
	.item-nearExpiration {
		background: url("/static/medal/nearExpiration.png") #e7ecef no-repeat;
		background-size: 30%;
		border-radius: 5px;
	}
	
	.item-expired {
		background: url("/static/medal/expired.png") #e7ecef no-repeat;
		background-size: 30%;
		border-radius: 5px;
	}
	
	::v-deep #u-a-p > div {
		top: 30px !important;
	}
	
</style>