<!-- 
[报名] 样式3 - 报名
http://localhost:5173/card/#/pages/bm/style3/signup
https://oss-mbh5.colormaprun.com/card/#/pages/bm/style3/signup
 -->
<template>
	<view class="body">
		<view class="content uni-column">
			<view class="uni-column" :class="cssTop">
				<my-topbar :mcName="mcName" :class="cssTopbarColor"
					@btnBackClick="btnBack" @btnInfoClick="btnInfo"></my-topbar>
			</view>
			<view class="main uni-column">
				<view class="timebar uni-row">
					<image mode="aspectFit" class="clock" src="/static/default/clock.png"></image>
					<text class="acttime">{{acttime}}</text>
				</view>

				<input class="uni-input" maxlength="30" placeholder="请填写姓名" v-model="nickName" />

				<view class="introduce uni-column">
					<text class="introduce-title">{{introduce.title}}</text>
					<text class="introduce-content" v-html="introduce.content"></text>
				</view>
				<button class="btnSignup btnSignup-enable" v-if="mcState<=1" @click="btnSignup">报 名</button>
				<button class="btnSignup btnSignup-disable" v-if="mcState==2">活动已结束</button>
			</view>

			<my-popup ref="mypopup" :dataList="popupDataList" :acttime="acttime"></my-popup>

			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog type="info" cancelText="取消" confirmText="确认" title="您填写的姓名:" @confirm="dialogConfirm"
					@close="dialogClose">
					<view class="dialog-content uni-column">
						<text class="dialog-content-1">{{nickName}}</text>
					</view>
				</uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import tools from '../../../common/tools';
	import {
		defaultPopUpDataList
	} from '../../../common/define';
	import {
		token,
		apiCardDetailQuery,
		apiOnlineMcSignUpDetail,
		apiOnlineMcSignUp,
		apiCardConfigQuery,
		apiMatchRsDetailQuery,
		checkResCode,
		checkToken
	} from '../../../common/api';

	export default {
		data() {
			return {
				pageName: "signup",
				firstEnterKey: 'firstEnter-bm-style3',
				rankKey: "rank-bm-style3",
				queryObj: {},
				queryString: "",
				from: "", // 来源页面
				token: "",
				ecId: 0, // 卡片id
				mcId: 0, // 赛事id
				mcType: 0, // 赛事类型 1 普通活动 2 线下赛 3 线上赛
				mcName: "", // 赛事名称
				acttime: "", // 活动时间
				beginSecond: null, // 活动或赛事开始时间戳，单位秒
				endSecond: null, // 活动或赛事结束时间戳，单位秒
				coiId: 0, // 已报名单位id
				coiName: "", // 已报名单位名称，可为空
				teamNum: 0, // 已报名队伍编号，可为0
				nickName: "", // 昵称
				// coiRs: [], // 组织信息集合
				// orgList: [], // 分组下拉列表数据源
				// teamList: [], // 
				interval: null,

				mcState: 0, // 赛事/活动状态 0: 未开始  1: 进行中  2: 已结束
				// teamType: 0, // 队伍类型  0: 红黄蓝紫 1: 学生/家长
				cssTop: "",
				cssTopbarColor: "",
				cssLogo: "",
				introduce: {
					title: "",
					content: ""
				},
				popupDataList: [],
			}
		},
		computed: {},
		onLoad(query) { // 类型非必填，可自动推导
			// console.log(query);
			this.queryObj = query;
			this.queryString = tools.objectToQueryString(this.queryObj);
			// console.log(queryString);
			this.from = query["from"] ?? "";
			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);

			tools.removeCssCode();

			this.getCardConfigQuery();
			this.getCardDetailQuery();
			this.matchRsDetailQuery();
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {
			// this.dealFirstEnter();
		},
		onUnload() {
			this.clear();
		},
		methods: {
			dealNotice(rank) {
				// console.log('[dealNotice]');
				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);
					},
				})
			},
			clear() {
				if (this.interval != null) {
					clearInterval(this.interval);
					this.interval = null;
				}
			},
			loadConfig(config) {
				// console.log("config", config);

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

					if (css.indexOf(".top{") >= 0) {
						this.cssTop = "top";
					}
					if (css.indexOf(".topbar-color{") >= 0) {
						this.cssTopbarColor = "topbar-color";
					}
				}

				if (this.cssTop == "") {
					this.cssTop = "top-default";
				}
				if (this.cssTopbarColor == "") {
					this.cssTopbarColor = "topbar-color-default";
				}
				console.log("[loadConfig] cssTop:", this.cssTop);
				console.log("[loadConfig] cssTopbarColor:", this.cssTopbarColor);

				// 加载队伍类型  0: 红黄蓝紫 1: 学生/家长
				/* if (config.teamType != undefined && config.teamType >= 0) {
					this.teamType = config.teamType;
				} */

				// 加载介绍内容
				const introduce = config.introduce;
				if (introduce != undefined) {
					if (introduce.title != undefined) {
						this.introduce.title = introduce.title;
					}
					if (introduce.content != undefined) {
						this.introduce.content = introduce.content;
					}
				}

				// 加载弹窗数据
				const popupDataList = config.popupDataList;
				// console.log("[loadConfig] popupDataList:", popupDataList);
				if (popupDataList != undefined && popupDataList.length > 0) {
					for (var i = 0; i < popupDataList.length; i++) {
						// console.log("[loadConfig] popupDataList", i, popupDataList[i]);
						if (popupDataList[i] == 'default') {
							for (var j = 0; j < defaultPopUpDataList.length; j++) {
								this.popupDataList.push(defaultPopUpDataList[j]);
							}
						} else {
							this.popupDataList.push(popupDataList[i]);
						}
					}
				} else {
					this.popupDataList = defaultPopUpDataList;
					console.log("[loadConfig] popupDataList 加载默认列表");
				}
				// console.log("[loadConfig] popupDataList:", this.popupDataList);
			},
			fmtMcTime(timestamp) {
				return tools.fmtMcTime(timestamp);
			},
			// 获取倒计时
			getActtime() {
				this.acttime = tools.getActtime(this.beginSecond, this.endSecond);
			},
			getCardConfigQuery() {
				uni.request({
					url: apiCardConfigQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						ecId: this.ecId,
						pageName: this.pageName
					},
					success: (res) => {
						// console.log("getCardConfigQuery", res)
						const data = res.data.data;
						const config = data.configJson != "" ? JSON.parse(data.configJson) : "";
						// console.log("configJson", data.configJson);
						/* const config = {
							"css": `
								.top{
									width: 100%;
									height: 170px;
									padding-top: 36px;
									justify-content: space-between;
									background-image: url('static/backgroud/top_bg_guoqing.png');
									background-repeat: no-repeat;
									background-position-y: 20%;
									background-size: cover;
								}
								.topbar-color{
									color: #ffffff;
								}
								.btnSignup-enable {
									background-color: #ff0000 !important;
								}
								.swiper-item-button {
									background-color: #ff0000 !important;
								}
								.uni-swiper-dot-active {
									background: #ff0000 !important;
								}
							`,
							"popupDataList": [
								{
									"type": 2,
									"data": {
										"title": "基本图例",
										"img": "/static/common/jbtl.png"
									}
								}, {
									"type": 2,
									"data": {
										"title": "基本标识",
										"img": "/static/common/jbbs2.png"
									}
								},
								{
									"type": 7,
									"data": {
										"title": "活动规则",
										"content": "<li>赛期内随时参赛、不限完赛次数、起点任选、实时排名 <li>起点-各途经点-结束点完整打卡为1次有效完赛 <li>赛事如有疑问，请咨询微信客服",
										"imageList": [
											{
												"src": "/static/common/qrcode_wxkf.png",
												"width": "100px",
												"height": "100px"
											}
										]
									}
								},
								{
									"type": 7,
									"data": {
										"title": "活动奖励",
										"content": "<li>途经点打卡1次，获1个百味豆<br><li>每次正确答题，再获1个百味豆<br><li>20个百味豆兑换1个鸡蛋<br><li>上不封顶！随时兑换！<br><text style='font-size:12px;color:#999999;'>(限本次活动百味豆，兑换以“蛋叔券”为准)</text><br><li>健身又能“薅羊毛”~",
										"imageList": [
											{
												"src": "/static/common/jidanquan.png",
												"width": "80px",
												"height": "80px"
											}
										]
									}
								}
							],
							"introduce": {
								"title": "介绍：",
								"content": "<li>领秀城社区欢乐定向赛来袭 \r\n <li>领秀城 A、B、C、D、E、F 区及商业街、贵和购物广场等8个起点任选。\r\n <li>跑的多，得蛋多，神秘蛋叔赞助！\r\n <li>还等什么？火速报名吧！\r\n <li>定向赛场上，每一个人都是主角~"
							}
						}; */

						this.loadConfig(config);

						setTimeout(this.dealFirstEnter, 500);
					},
					fail: (err) => {
						console.log("getCardConfigQuery err", err)
					},
				});
			},
			// 卡片信息查询
			getCardDetailQuery() {
				uni.request({
					url: apiCardDetailQuery,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token
					},
					method: "POST",
					data: {
						ecId: this.ecId
					},
					success: (res) => {
						// console.log("getCardDetailQuery", 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.coiId = data.coiId;
						this.coiName = data.coiName;
						this.teamNum = data.teamNum;

						this.mcState = tools.checkMcState(this.beginSecond, this.endSecond);

						this.getActtime();
						// this.getOnlineMcSignUpDetail();

						this.clear();
						this.interval = setInterval(this.getActtime, 60000);
					},
					fail: (err) => {
						console.log("getCardDetailQuery err", err)
					},
				});
			},
			// 卡片对应线上赛多个活动查询
			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 (res.data.code == 0) {
							const data = res.data.data;
							const rank = JSON.stringify(data);
							this.dealNotice(rank);
						}
					},
					fail: (err) => {
						console.log("matchRsDetailQuery err", err)
					},
				});
			},
			// 卡片用户当前排名查询
			// getUserCurrentRankNumQuery() {
			// 	uni.request({
			// 		url: apiUserCurrentRankNumQuery,
			// 		header: {
			// 			"Content-Type": "application/x-www-form-urlencoded",
			// 			"token": this.token,
			// 		},
			// 		method: "POST",
			// 		data: {
			// 			ecId: this.ecId
			// 		},
			// 		success: (res) => {
			// 			// console.log("getUserCurrentRankNumQuery", res)
			// 			if (res.data.code == 0) {
			// 				const data = res.data.data;
			// 				const rankNum = data.rankNum;
			// 				this.dealNotice(rankNum);
			// 			}
			// 		},
			// 		fail: (err) => {
			// 			console.log("getUserCurrentRankNumQuery err", err)
			// 		},
			// 	});
			// },
			// 线上赛报名页面信息详情
			/* getOnlineMcSignUpDetail() {
				uni.request({
					url: apiOnlineMcSignUpDetail,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						mcId: this.mcId,
					},
					success: (res) => {
						// console.log("getOnlineMcSignUpDetail", res)
						this.coiRs = res.data.data.coiRs;
						const rsNum = this.coiRs.length;
						this.orgList = [];
						for (let i = 0; i < rsNum; i++) {
							this.orgList[i] = {};
							this.orgList[i].value = this.coiRs[i].coiId;
							this.orgList[i].text = this.coiRs[i].coiName;
							this.orgList[i].teamNum = this.coiRs[i].teamNum;
						}
						// console.log("orgList", this.orgList);
						if (this.coiId > 0) {
							this.orgChange(this.coiId, false);
						}
					},
					fail: (err) => {
						console.log("getOnlineMcSignUpDetail err", err)
					},
				});
			}, */
			// 线上赛报名
			onlineMcSignUp() {
				uni.request({
					url: apiOnlineMcSignUp,
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
						"token": this.token,
					},
					method: "POST",
					data: {
						mcId: this.mcId,
						coiId: this.coiId,
						selectTeam: this.teamNum,
						nickName: this.nickName
					},
					success: (res) => {
						// console.log("onlineMcSignUp", res);

						if (checkResCode(res)) {
							uni.showToast({
								title: '比赛报名成功！',
								icon: 'none',
								duration: 3000
							});

							// uni.navigateTo({
							// 	// url: '/pages/bm/style3/rankOverview?' + this.queryString
							// 	url: '/pages/bm/style3/rankList?' + this.queryString
							// });
							const url = '/pages/bm/style3/rankList?' + this.queryString;
							tools.appAction(url, "uni.navigateTo");
						}
					},
					fail: (err) => {
						console.log("onlineMcSignUp err", err);
						uni.showToast({
							title: '出错了，报名失败',
							icon: 'none',
							duration: 3000
						});
					},
				});
			},
			btnBack() {
				// console.log("from:", this.from)
				if (this.from != '') {
					// window.history.back();
					// uni.navigateTo({
					// 	url: '/pages/bm/style3/rankList?' + this.queryString
					// });
					const url = '/pages/bm/style3/rankList?' + this.queryString;
					tools.appAction(url, "uni.navigateTo");
				} else {
					const url = `action://to_home/`;
					tools.appAction(url);
				}
			},
			btnInfo() {
				this.$refs.mypopup.popupOpen();
			},
			btnSignup() {
				if (!checkToken(this.token)) {
					return;
				}

				if (!(this.nickName.trim().length > 0)) {
					uni.showToast({
						title: '请填写姓名',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				this.nickName = this.nickName.trim();
				this.$refs.alertDialog.open();
			},
			dialogConfirm() {
				this.onlineMcSignUp();
			},
			dialogClose() {}
		}
	}
</script>

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

	.top-default {
		width: 100%;
		height: 170px;
		padding-top: 36px;
		justify-content: space-between;
		background-image: url("/static/backgroud/top_bg_egg3.png");
		background-repeat: no-repeat;
		background-position: center;
		background-size: cover;
	}

	.topbar-color-default {
		color: #333333;
	}

	.main {
		width: 76%;
		min-height: 800rpx;
		/* margin-top: 20rpx; */
		justify-content: space-around;
	}

	.timebar {
		width: 90%;
		height: 65rpx;
		margin-top: 20rpx;
		padding: 0 30rpx;
		justify-content: space-evenly;
		background: #ffffff;
		border: 0.5px solid;
		border-color: #e7e7e7;
		border-radius: 20px;
		box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.13);
	}

	.acttime {
		font-weight: 550;
		color: #333333;
		font-size: 30rpx;
	}

	.clock {
		width: 30rpx;
		height: 30rpx;
		margin-right: 20rpx;
	}

	.uni-input {
		width: 90%;
		height: 85rpx;
		/* margin-top: 30rpx; */
		padding: 0 30rpx;
		background: #f1f1f1;
		border-radius: 9px;
	}

	.input-placeholder {
		color: #333333;
		font-size: 16px;
	}

	.introduce {
		width: 100%;
		margin-top: 10rpx;
		margin-bottom: 30rpx;
		align-items: flex-start;
		justify-content: space-around;
	}

	.introduce-title {
		color: #333333;
		font-size: 30rpx;
		line-height: 60rpx;
		font-family: Source Han Sans CN;
	}

	.introduce-content {
		color: #333333;
		font-size: 25rpx;
		line-height: 46rpx;
		font-family: Source Han Sans CN;
	}

	.btnSignup {
		width: 100%;
		height: 100rpx;
		margin-bottom: 30rpx;
		color: white;
		font-weight: bold;
		line-height: 100rpx;
		border-radius: 55rpx;
	}

	.btnSignup-enable {
		background-color: #81cd00;
	}

	.btnSignup-disable {
		background-color: #c3c3c3;
	}

	.dialog-content {
		width: 279px;
		height: 110px;
		background: #f1f1f1;
		border-radius: 9px;
		justify-content: center;
		text-align: center;
		font-weight: 550;
		color: #333333;
	}

	.dialog-content-1 {
		font-size: 40rpx;
	}
</style>