<!-- 
[报名] 样式1 - 报名
http://localhost:5173/card/#/pages/bm/style1/signup
https://oss-mbh5.colormaprun.com/card/#/pages/bm/style1/signup
 -->
<template>
	<view class="body">
		<view class="content uni-column">
			<view class="uni-column" :class="cssTop">
				<view class="topbar uni-row">
					<image mode="aspectFit" class="topbar-back" @click="btnBack" src="/static/default/back.png"></image>
					<text class="mcName">{{mcName}}</text>
					<image mode="aspectFit" class="topbar-info" @click="btnInfo" src="/static/default/info.png"></image>
				</view>
				<view :class="cssLogo"></view>
				<view class="toptime uni-row">
					<image mode="aspectFit" class="clock" src="/static/default/clock.png"></image>
					<text class="acttime">{{acttime}}</text>
				</view>
				<!-- <text class="mcName">{{ecId}} - {{mcId}} - {{token}}</text> -->
			</view>
			<view class="main uni-column">
				<uni-data-select class="select" placeholder="请选择组织名称" v-model="coiId" :localdata="orgList"
					@change="orgChange"></uni-data-select>
				<uni-data-select v-if="teamList.length > 0" class="select" placeholder="请选择分组" v-model="teamNum"
					:localdata="teamList"></uni-data-select>
				<view class="introduce uni-column">
					<text class="introduce-title">{{introduce.title}}</text>
					<text
						class="introduce-content">{{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">{{mcName}}</text>
						<text class="dialog-content-2">{{coiName}}</text>
						<text class="dialog-content-2">{{teamName}}</text>
					</view>
				</uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

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

	export default {
		data() {
			return {
				pageName: "signup",
				// firstEnterKey: 'firstEnter-bm_sqsj_signup',
				firstEnterKey: 'firstEnter-bm_sqsj',
				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
				coiRs: [], // 组织信息集合
				orgList: [], // 分组下拉列表数据源
				teamList: [], // 
				interval: null,
				
				mcState: 0 ,// 赛事/活动状态 0: 未开始  1: 进行中  2: 已结束
				teamType: 0, // 队伍类型  0: 红黄蓝紫 1: 学生/家长
				cssTop: "",
				cssLogo: "",
				introduce: {
					title: "",
					content: ""
				},
				popupDataList: [],
			}
		},
		computed: {
		},
		onLoad(event) { // 类型非必填，可自动推导
			// console.log(event);
			this.queryString = tools.objectToQueryString(event);
			// console.log(queryString);
			this.from = event["from"] ?? "";
			this.token = event["token"] ?? token;
			this.ecId = event["id"] ?? 0;
			
			tools.removeCssCode();
			
			this.getCardConfigQuery();
			this.getCardDetailQuery();
		},
		// 页面初次渲染完成，此时组件已挂载完成，DOM 树($el)已可用
		onReady() {
			this.dealFirstEnter();
		},
		onUnload() {
			this.clear();
		},
		methods: {
			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(".logo{") >= 0) {
						this.cssLogo = "logo";
					}
				}
				
				if (this.cssTop == "") {
					this.cssTop = "top-default";
				}
				if (this.cssLogo == "") {
					this.cssLogo = "logo-default";
				}
				console.log("[loadConfig] cssTop:", this.cssTop);
				console.log("[loadConfig] cssLogo:", this.cssLogo);
				
				// 加载队伍类型  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);
			},
			getTeamList(teamNum) {
				var teamList = [];
				if (teamNum > 0) {
					for (let i=0; i<=teamNum; i++) {
						teamList[i] = {};
						teamList[i].value = i;
						// teamList[i].text = `第 ${i+1} 队`;
						teamList[i].text = teamName[this.teamType][i];
					}
				}
				this.teamList = teamList;
			},
			fmtMcTime(timestamp) {
				var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
				// var Y = date.getFullYear() + '-';
				var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
				var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
				var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
				// var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());

				const timeStr = M + D + h + m;
				// console.log("timeStr", timeStr);
				return timeStr;
			},
			// 获取倒计时
			getActtime() {
				this.acttime = this.fmtMcTime(this.beginSecond) + " 至 " + this.fmtMcTime(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: 215px;
								padding-top: 30px;
								padding-bottom: 30px;
								justify-content: space-between;
								background-image: url("static/backgroud/top_colorbar.png"), linear-gradient(180deg,#178bff 0%,#004d9b 100%);
								background-repeat: no-repeat;
								background-position: center, 0px 0px;
								background-size: auto 176px , cover;
							}
							
							.logo{
								width: 150px;
								height: 150px;
								margin-top: 10px;
								background-image: url('static/logo/xfl.png');
								background-repeat: no-repeat;
								background-position-x: center;
								background-position-y: center;
								background-size: contain;
							}
						`,
						"popupDataList": [
							{
								"type": 1,
								"data": {
									"title": "山青活动",
									"img": "/static/logo/sqsj.png",
									"content": "山青世界为广大青少年提供了亲近自然、劳动实践、拓展培训、军事教育、科普体验、自然探索的平台和机会，也为企事业单位青年团队提供会议培训、拓展训练等服务",
								}
							}, 
							"default"
						],
						"introduce": {
							"title" : "介绍：",
							"content": "山青世界为广大青少年提供了亲近自然、劳动实践、拓展培训、军事教育、科普体验、自然探索的平台和机会，也为企事业单位青年团队提供会议培训、拓展训练等服务",
						},
						"teamType": 1
						}; */
						
						this.loadConfig(config);
					},
					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)
					},
				});
			},			
			// 线上赛报名页面信息详情
			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
					},
					success: (res) => {
						console.log("onlineMcSignUp", res)
						
						if (checkResCode(res)) {
							uni.showToast({
								title: '比赛报名成功！',
								icon: 'none',
								duration: 3000
							});

							uni.navigateTo({
								url: '/pages/bm/style1/rankList?' + this.queryString
							});
						}
					},
					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/style1/rankList?' + this.queryString
					});
				} else {
					window.location.href = `action://to_home/`;
				}
			},
			btnInfo() {
				this.$refs.mypopup.popupOpen();
			},
			orgChange(value, resetTeamNum=true) {
				console.log("[orgChange] value:", value);
				if (resetTeamNum) {
					this.teamNum = 0;
				}
				if (value > 0) {
					const selectedOption = this.orgList.find(option => option.value === value);
					const teamNum = selectedOption.teamNum;
					// console.log("[orgChange] teamNum:", teamNum);
					this.getTeamList(teamNum);
				} else {
					this.getTeamList(0);
				}
				
			},
			btnSignup() {
				if (!checkToken(this.token)) {
					return;
				}
				
				if (!(this.coiId > 0)) {
					uni.showToast({
						title: '请选择组织名称',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				// if ((this.teamList.length > 0) && !(this.teamNum > 0)) {
				// 	uni.showToast({
				// 		title: '请选择分组',
				// 		icon: 'none',
				// 		duration: 2000
				// 	});
				// 	return;
				// }
				this.coiName = tools.getSelectedText(this.orgList, this.coiId);
				this.teamName = tools.getSelectedText(this.teamList, this.teamNum);
				this.$refs.alertDialog.open();
			},
			dialogConfirm() {			
				this.onlineMcSignUp();
			},
			dialogClose() {}
		}
	}
</script>

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

	.top-default {
		width: 100%;
		/* height: 35vh; */
		height: 206px;
		padding-top: 36px;
		padding-bottom: 30px;
		justify-content: space-between;
		background-image: url("/static/backgroud/top_colorbar.png"), linear-gradient(180deg,#f8a95a 0%,#d25f11 100%);
		/* background-image: url("/static/backgroud/top_colorbar.png"), linear-gradient(180deg,#7aedff 0%,#047200 100%); */
		/* background-image: url("/static/backgroud/top_colorbar.png"), linear-gradient(180deg,#178bff 0%,#004d9b 100%); */
		background-repeat: no-repeat;
		background-position: center, 0px 0px;
		background-size: auto 176px , cover;
	}
	
	.logo-default {
		width: 150px;
		height: 150px;
		margin-top: 10px;
		background-image: url('/static/logo/jbs.png');
		background-repeat: no-repeat;
		background-position-x: center;
		background-position-y: center;
		background-size: contain;
	}
	
	.topbar {
		width: 90%;
		padding: 0rpx 30rpx;
		justify-content: space-between;
	}

	.topbar-back {
		width: 43rpx;
		height: 43rpx;
		/* opacity: 0; */
	}

	.topbar-info {
		width: 46rpx;
		height: 46rpx;
	}

	.mcName {
		color: white;
		font-size: 40rpx;
		font-weight: 550;
	}

	.toptime {
		height: 65rpx;
		margin-top: 20rpx;
		padding: 0 50rpx;
		justify-content: space-evenly;
		background-color: white;
		border-radius: 40rpx;
	}

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

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

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

	.select {
		margin-bottom: 36rpx;
	}

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

	.introduce-title {
		color: #333333;
		font-size: 30rpx;
		line-height: 60rpx;
	}

	.introduce-content {
		color: #333333;
		font-size: 25rpx;
		line-height: 36rpx;
	}

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

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

	.dialog-content-1 {
		font-size: 40rpx;
		margin-bottom: 30rpx;
	}

	.dialog-content-2 {
		font-size: 32rpx;
		margin-bottom: 10rpx;
	}
</style>