<template>
	<view class="container">
		<image mode="" style="width: 100%; height: 336rpx;" src="../../static/images/zxks.jpeg">
			<view class='mainBox'>
				<view class="mainTop">
					考试概要
				</view>
				<view class="ksBox">
					<image mode="" class="imgStyle" style="width: 100%; height: 100%;"
						src="../../static/images/gkbj.png">
						<text class="fontTitle">{{htmlData.examName}}</text>
						<text class="fontStyle">出题人</text>
						<text class="fontSize">{{htmlData.createBy}}</text>
						<view class="ksMain">
							<view class="boxStyle">
								<view class="fontColor">
									{{htmlData.questionsNum||0}}题
								</view>
								<view class="fontStyle">

									<uni-icons type="calendar" size="20"></uni-icons>
									题目总数
								</view>
							</view>
							<view class="boxStyle">
								<view class="fontColor">
									{{htmlData.scoreNum||0}}分
								</view>
								<view class="fontStyle">
									<uni-icons type="star" size="20"></uni-icons>
									题目总分
								</view>
							</view>
							<view class="boxStyle">
								<view class="fontColor">
									{{htmlData.paperPeriod||0}}分钟
								</view>
								<view class="fontStyle">
									<uni-icons type="wallet" size="20"></uni-icons>
									考试时长
								</view>
							</view>
						</view>
						<button type="primary" class="buttonStyle" @click="open">开始答题</button>
				</view>
			</view>
			<view class='mainBox'>

				<view class="mainTop">
					考试说明
				</view>
				<view class="ksBox fontStyle">
					<text class="smPadding">
						{{htmlData.remark||'无'}}
					</text>
				</view>
			</view>
			<view class="phb" @click="toRanking">
				<uni-icons type="flag" size="20" color="#FFFFFF"></uni-icons>
				排行榜
			</view>
			<view class="ckcj" @click="lookGrade" v-if="isUser">
				<!-- v-if="uni.getStorageSync("user")" -->
				<uni-icons type="flag" size="20" color="#FFFFFF"></uni-icons>
				查看成绩
			</view>
			<view class="outLogin" @click="outLogin" v-if="isUser&&isH5">
				<!-- v-if="uni.getStorageSync("user")" -->
				<uni-icons type="arrow-left" size="20" color="#FFFFFF"></uni-icons>
				退出
			</view>
			<uni-popup ref="popup" type="center">
				<view class="popupBox">
					<view class="testTitle">
						<view class="hr"></view>
						<view class="testText">本场考试</view>
						<view class="hr"></view>
					</view>
					<view class="ksMain">
						<view class="boxStyle">
							<view class="fontColor">
								{{htmlData.questionsNum}}题
							</view>
							<view class="fontStyle">
								题目总数
							</view>
						</view>
						<view class="boxStyle">
							<view class="fontColor">
								{{htmlData.scoreNum}}分
							</view>
							<view class="fontStyle">
								题目总分
							</view>
						</view>
						<view class="boxStyle">
							<view class="fontColor">
								{{htmlData.paperPeriod}}分钟
							</view>
							<view class="fontStyle">
								考试时长
							</view>
						</view>
					</view>
					<view class="testTitle">
						<view class="hr"></view>
						<view class="testText">登录考试</view>
						<view class="hr"></view>
					</view>
					<uni-forms ref="dynamicForm" :rules="dynamicRules" :modelValue="dynamicFormData" class="formStyle">
						<template v-for="(item,index) in dynamicLists">
							<uni-forms-item :label="item.label" required :rules="changeRules(item)" :key="item.name"
								v-if="item.required==true" :name="item.name">
								<view class="form-item">
									<uni-easyinput v-model="dynamicFormData[item.name]"
										@input="setValue(item.name,dynamicFormData[item.name])"
										:placeholder="'请输入'+item.label" />
								</view>
							</uni-forms-item>
							<uni-forms-item :label="item.label" :rules="changeRules(item)" :key="item.name" v-else
								:name="item.name">
								<view class="form-item">
									<uni-easyinput v-model="dynamicFormData[item.name]"
										:placeholder="'请输入'+item.label" />
								</view>
							</uni-forms-item>
						</template>
					</uni-forms>
					<button type="primary" class="buttonStyle" @click="login('dynamicForm')">登录考试</button>
				</view>
			</uni-popup>
	</view>
</template>

<script>
	import {
		getExam,
		phoneLogin,
		checkOpenId,
		getStuOpenId,
		startExam,
	} from "../../utils/url.js";
	import openId from "../../utils/getOpenId.js";
	export default {
		data() {
			return {
				// 数据源
				dynamicFormData: {
					loginName: '',
					password: '',
				},
				// 动态表单数据
				dynamicLists: [{
						label: '账号',
						id: 0,
						name: 'loginName',
						required: true
					},
					{
						label: '密码',
						id: 1,
						name: 'password',
						required: true
					}
				],
				// 规则
				dynamicRules: {
					email: {
						rules: []
					}
				},
				//页面数据
				htmlData: {
					// 考试名  examName
					// 出题人 createBy
					// 题目总数 questionsNum
					// 题目总分 scoreNum
					// 考试时长 paperPeriod
					// 考试说明 remark
					// 考试类型 0选人 1自主填报
				},
				paper: null,
				examId: null,
				isPaper: false,
				isUser: false,
				isH5: false,
			}
		},
		methods: {
			handUser() {
				console.log(uni.getStorageSync("user"), 'uni.getStorageSync("user")')
				if (uni.getStorageSync("user")) {
					return true
				} else {
					return false
				}
			},
			setValue(name, value) {
				// 设置表单某项对应得值来触发表单校验
				// 接受两个参数，第一个参数为表单域的 name ，第二个参数为表单域的值
				this.$refs.dynamicForm.setValue(name, value)
			},
			async getPaper(id) {
				uni.showLoading({
					title: '加载中'
				});
				let data = await getExam(id);
				uni.hideLoading();
				this.changeForm(data.data);
				uni.setStorageSync("examData", data.data);
			},
			changeForm(data) {
				this.htmlData = data;
				if (this.htmlData.examType == "0") {
					this.dynamicLists = [{
							label: '账号',
							id: 0,
							name: 'loginName',
							required: true
						},
						{
							label: '密码',
							id: 1,
							name: 'password',
							required: true
						}
					]
				} else {
					this.dynamicLists = [{
							label: '姓名',
							id: 0,
							name: 'studentName',
							required: true
						},
						{
							label: '账号',
							id: 1,
							name: 'loginName',
							required: true
						},
						{
							label: '密码',
							id: 2,
							name: 'password',
							required: true
						}
					]
				}
			},
			async phoneLogin(res) {

				uni.showLoading({
					title: '加载中'
				});
				console.log(res, 'res');
				let data = await phoneLogin(res);
				console.log(data, 'data');
				uni.hideLoading();
				uni.setStorageSync("token", data.data.token.access_token);
				uni.setStorageSync("user", res);
				//卷子是否存在
				// console.log(uni.getStorageSync("examFlg"),'uni.getStorageSync("examFlg")');
				// console.log(uni.getStorageSync("examData").id,'uni.getStorageSync("examData").id');
				// console.log(uni.getStorageSync("oldExamId"),'uni.getStorageSync("oldExamId")');
				// console.log(uni.getStorageSync("user").loginName,'uni.getStorageSync("user").loginName');
				// console.log(uni.getStorageSync("oldLoginName"),'uni.getStorageSync("oldLoginName")');
				// console.log(uni.getStorageSync("paper"),'uni.getStorageSync("paper")');
				let resd = uni.getStorageSync("examFlg") == 1 && uni.getStorageSync("examData").id == uni
					.getStorageSync("oldExamId") && uni.getStorageSync("user").loginName == uni.getStorageSync(
						"oldLoginName") && uni.getStorageSync("paper")
				if (this.isPaper || resd) {
					uni.showModal({
						title: '提醒',
						content: '还有未答完的试卷！',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/test/test?paper=true'
								});
								// alert('用户点击确认');
							} else if (res.cancel) {
								// alert('用户点击取消');
							}

						}
					})
				} else {
					let res = uni.getStorageSync("user");
					console.log(res, 'res');
					let parmar = await this.getExam(uni.getStorageSync("examData").id, res.loginName, res.password);
					console.log(parmar, 'parmar');
					uni.navigateTo({
						url: '/pages/test/test'
					});
				}

			},
			async open() {
				// if (this.isPaper) {
				// 	uni.showModal({
				// 		title: '提醒',
				// 		content: '还有未答完的试卷！',
				// 		showCancel: false,
				// 		success: function(res) {
				// 			if (res.confirm) {
				// 				uni.navigateTo({
				// 					url: '/pages/test/test'
				// 				});
				// 				// alert('用户点击确认');
				// 			} else if (res.cancel) {
				// 				// alert('用户点击取消');
				// 			}

				// 		}
				// 	})
				// } else
				console.log(uni.getStorageSync("token"), 'uni.getStorageSync("token")')
				if (uni.getStorageSync("user")) {
					let res = uni.getStorageSync("user");
					let exam=uni.getStorageSync("examData")
					//考试类型不一样需要登录
					if(exam.examType!=uni.getStorageSync("oldExamType"))
					{
						this.$refs.popup.open();
					}else{
						this.phoneLogin({...res,examId:exam.id});
					}
					// let resd = uni.getStorageSync("examFlg") == 1 && uni.getStorageSync("examData").id == uni
					// 	.getStorageSync("oldExamId") && uni.getStorageSync("user").loginName == uni.getStorageSync(
					// 		"oldLoginName") && uni.getStorageSync("paper")
					// if (this.isPaper || resd) {
					// 	uni.showModal({
					// 		title: '提醒',
					// 		content: '还有未答完的试卷！',
					// 		showCancel: false,
					// 		success: function(res) {
					// 			if (res.confirm) {
					// 				uni.navigateTo({
					// 					url: '/pages/test/test?paper=true'
					// 				});
					// 				// alert('用户点击确认');
					// 			} else if (res.cancel) {
					// 				// alert('用户点击取消');
					// 			}

					// 		}
					// 	})
					// } else {
					// 	let res = uni.getStorageSync("user");
					// 	let parmar = await this.getExam(uni.getStorageSync("examData").id, res.loginName, res
					// 		.password);
					// 	uni.navigateTo({
					// 		url: '/pages/test/test'
					// 	});
					// }
				} else {
					this.$refs.popup.open();
				}
			},
			async getExam(examId, loginName, loginPassword) {
				uni.showLoading({
					title: '加载中'
				});
				let data = await startExam(examId, loginName, loginPassword);
				uni.hideLoading();
				uni.setStorageSync("paper", data.data);
			},
			login(ref) {
				this.$refs[ref].validate().then(res => {
					this.phoneLogin({
						...res,
						examId: this.htmlData.id,
						openId: uni.getStorageSync("openId") ? uni.getStorageSync("openId") : null
					});
					this.$refs.popup.close()
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			changeRules(item) {
				return [{
					'required': item.required,
					errorMessage: item.label + '必填'
				}, ]
			},
			toRanking() {
				uni.navigateTo({
					url: '/pages/ranking/ranking?examId=' + this.examId
				});
			},
			lookGrade() {
				uni.navigateTo({
					url: '/pages/performance/performance'
				});
			},
			async checkOpenId(examId, openId) {
				uni.showLoading({
					title: '加载中'
				});
				let result = await checkOpenId(examId, openId);
				uni.hideLoading();
				console.log(result, 'result');
				if (result.data.id) {
					this.paper = result.data;
					uni.setStorageSync("paper", this.paper);
					//存在卷，并且卷还在进行中
					if (parseInt(result.data.examNum) > 0 && result.data.examFlg == '1') {

						this.isPaper = true;
						this.phoneLogin({
							loginName: result.data.loginName,
							password: result.data.loginPassword,
							examId: this.examId,
							openId: uni.getStorageSync("openId") ? uni.getStorageSync("openId") : null
						});
					} else {
						let user = {
							loginName: result.data.loginName,
							password: result.data.loginPassword,
							examId: this.examId,
							openId: uni.getStorageSync("openId") ? uni.getStorageSync("openId") : null
						}
						uni.setStorageSync("user", user);
					}
				} else {
					uni.setStorageSync("token", "");
				}
			},
			getParam(path, name) {

				var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");

				if (reg.test(path))

					return unescape(RegExp.$2.replace(/\+/g, " "));

				return "";

			},
			outLogin() {
				uni.showModal({
					title: '提示',
					content: '确定退出当前用户吗？',
					success: function(res) {
						if (res.confirm) {
							uni.setStorageSync("token", "");
							uni.setStorageSync("user", "");
							this.isUser = false;
							this.isH5 = false;
							//H5页面不是响应式的
							location.reload();
							// uni.showToast({
							// 	title: '退出成功',
							// 	icon: 'none',
							// 	duration: 5000
							// })
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});

			}
		},
		async onShow() {
			//// #ifdef H5
			//   openId.getOpenId(() => {
			//   let dt = window.localStorage.getItem("openId");
			//   console.log(dt,'dt');
			// });
			//// 	#endif
			if (uni.getStorageSync("user")) {
				this.isUser = true;
			} else {
				this.isUser = false;
			}
			console.log(this.examId, 'this.examId');
			console.log(!this.examId, 'this.examId');
			console.log(uni.getStorageSync("user"), 'uni.getStorageSync("user")');
			if (!this.examId && uni.getStorageSync("examData")) {
				// console.log(uni.getStorageSync("examData"),'uni.getStorageSync("examData")');
				this.examId = uni.getStorageSync("examData").id;
			}
			await this.getPaper(this.examId);
			console.log(this.examId, 'this.examId');
			let openId = uni.getStorageSync("openId");
			if (openId) {
				this.checkOpenId(this.examId, openId)
				//有id代表就是有卷子
			}
		},
		async onLoad(options) {


			// #ifdef MP-WEIXIN
			if (options.q) {
				const q = decodeURIComponent(options.q); // 获取到二维码原始链接内容
				const scancode_time = parseInt(options.scancode_time); // 获取用户扫码时间 UNIX 时间戳
				console.log(q, 'q');
				console.log(scancode_time, 'scancode_time');
				let str = q
				let index = str.lastIndexOf("\/");
				str = str.substring(index + 1, str.length);
				console.log('我是获取到的考试id', str);
				this.examId = str;
			}
			uni.login({
				provider: 'weixin',
				success: async (res) => {
					uni.showLoading({
						title: '加载中'
					});
					let data = await getStuOpenId({
						jsCode: res.code
					});
					uni.hideLoading();
					uni.setStorageSync("openId", data.msg);
				}
			})
			// #endif
			// #ifdef H5
			// uni.setStorageSync("token", "");
			// console.log('我是清除token');
			// uni.setStorageSync("user", "");
			// uni.setStorageSync("examData", "");
			let local = location.href;
			let payment_id = this.getParam(local, "id");
			this.examId = parseInt(payment_id);
			this.isH5 = true;
			//	#endif
			//获取url中的参数
			// let id = 57;
			// this.examId = id;
		}
	}
</script>

<style scoped>
	.container {}

	.mainBox {
		width: 90%;
		/* height: 600rpx; */
		margin: 20rpx auto;
		position: relative;
		border-radius: 10rpx;
		display: flex;
		flex-direction: column;
		box-shadow: 0 0.05333rem 0.10667rem rgb(0 0 0 / 12%), 0 0 0.16rem rgb(0 0 0 / 4%);
	}

	.imgStyle {
		position: absolute;
		width: 100%;
		height: 75%;
		bottom: 0;
	}

	.mainTop {
		height: 80rpx;
		border-radius: 10rpx 10rpx 0 0;
		line-height: 80rpx;
		text-align: center;
		color: #fff;
		font-size: 32rpx;
		background-color: rgb(245, 166, 35);
	}

	.container {
		background: #fff;
		width: 100%;
		/* height: 100%; */
	}

	.ksBox {
		position: relative;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		text-align: center;
	}

	.ksMain {
		/* height: 140rpx; */
		display: flex;
		/* margin-top: 20rpx; */
	}

	.fontStyle {
		color: #909399;
		font-size: 28rpx;

	}

	.boxStyle {
		/* margin-left: 55rpx;
		margin-top: 10rpx; */
		text-align: center;
		margin-top: 10rpx;
		flex: 1;
	}

	.fontColor {
		color: rgb(245, 166, 35);
		font-size: 28rpx;
		margin-bottom: 10rpx;
	}

	.fontSize {
		font-size: 28rpx;
	}

	.fontTitle {
		font-size: 30rpx;
		margin-top: 35rpx;
		margin-bottom: 35rpx;
	}

	/* 小程序端需要添加!important,要不颜色是默认绿色 */
	.buttonStyle {
		width: 85%;
		margin-left: 7%;
		margin-top: 30rpx;
		margin-bottom: 70rpx;
		background-color: rgb(245, 166, 35) !important;
		border-radius: 44rpx;
	}

	.smPadding {
		margin: 20rpx;
		line-height: 40rpx;
		text-align: left;
	}

	.phb {
		position: fixed;
		right: 0;
		bottom: 20%;
		display: flex;
		background-color: rgb(245, 166, 35);
		padding: 10rpx 10rpx 10rpx 30rpx;
		border-radius: 30rpx 0 0 30rpx;
		font-size: 25rpx;
		color: #fff;
	}

	.ckcj {
		position: fixed;
		right: 0;
		bottom: 14%;
		display: flex;
		background-color: rgb(245, 166, 35);
		padding: 10rpx 10rpx 10rpx 30rpx;
		border-radius: 30rpx 0 0 30rpx;
		font-size: 25rpx;
		color: #fff;
	}

	.outLogin {
		position: fixed;
		right: 0;
		bottom: 8%;
		display: flex;
		background-color: rgb(245, 166, 35);
		padding: 10rpx 10rpx 10rpx 30rpx;
		border-radius: 30rpx 0 0 30rpx;
		font-size: 25rpx;
		color: #fff;
	}

	.popupBox {
		background-color: #f7f8fa;
		/* width: 680rpx;
		height: 800rpx; */
		border-radius: 12rpx;
		display: flex;
		flex-direction: column;
		padding: 50rpx 0;
	}

	.testTitle {
		display: flex;
		justify-content: center;
	}

	.hr {
		background-color: #dcdfe6;
		width: 200rpx;
		height: 2rpx;
		margin: 20rpx;
	}

	.testText {
		color: #303133;
		font-weight: 700;
	}

	.formStyle {
		padding: 0 40rpx;
		margin-top: 40rpx;
	}
</style>
