<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">
				<uni-icons type="arrow-left" size="20" color="#FFFFFF"></uni-icons>
				退出
			</view> -->
			<view class="outLogin" @click="outLogin" v-if="isUser">
				<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="buttonStyle1" @click="login('dynamicForm')">登录考试</button>
					<button type="primary" class="buttonStyle1" @click="register()"
						v-if="htmlData.examType =='1'">注册</button>
				</view>
			</uni-popup>
			<uni-popup ref="popup1" 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="registerForm" :rules="registerRules" :modelValue="registerFormData" class="formStyle">
						<template v-for="(item,index) in registerLists">
							<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="registerFormData[item.name]"
										@input="setValue(item.name,registerFormData[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="registerFormData[item.name]"
										:placeholder="'请输入'+item.label" />
								</view>
							</uni-forms-item>
						</template>
					</uni-forms> -->
					<uni-forms ref="registerForm" :modelValue="registerFormData" :rules="registerRules"
						class="formStyle">
						<uni-forms-item label="姓名" required name="studentName">
							<uni-easyinput type="text" v-model="registerFormData.studentName" placeholder="请输入姓名" />
						</uni-forms-item>
						<uni-forms-item label="账号" required name="loginName">
							<uni-easyinput type="text" v-model="registerFormData.loginName" placeholder="请输入账号" />
						</uni-forms-item>
						<uni-forms-item label="密码" required name="password">
							<uni-easyinput type="text" v-model="registerFormData.password" placeholder="请输入密码" />
						</uni-forms-item>

					</uni-forms>
					<button type="primary" class="buttonStyle1" @click="registerData('registerForm')">确定注册</button>
				</view>
			</uni-popup>
	</view>
</template>

<script>
	import {
		getExam,
		phoneLogin,
		checkOpenId,
		getStuOpenId,
		startExam,
		register,
		unbindMiniOpenid,
	} from "../../utils/url.js";
	import openId from "../../utils/getOpenId.js";
	export default {
		data() {
			return {
				// 数据源
				dynamicFormData: {
					loginName: '',
					password: '',
				},
				registerFormData: {
					studentName: '',
					loginName: '',
					password: '',
				},
				// 动态表单数据
				dynamicLists: [{
						label: '账号',
						id: 0,
						name: 'loginName',
						required: true
					},
					{
						label: '密码',
						id: 1,
						name: 'password',
						required: true
					}
				],
				registerLists: [{
						label: '姓名',
						id: 0,
						name: 'studentName',
						required: true
					},
					{
						label: '账号',
						id: 1,
						name: 'loginName',
						required: true
					},
					{
						label: '密码',
						id: 2,
						name: 'password',
						required: true
					}
				],
				// 规则
				dynamicRules: {
					email: {
						rules: []
					}
				},
				registerRules: {
					studentName: {
						rules: [{
							required: true,
							errorMessage: '请输入姓名',
						}]
					},
					loginName: {
						rules: [{
							required: true,
							errorMessage: '请输入账号',
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '请输入密码',
						}]
					},
				},
				//页面数据
				htmlData: {
					// 考试名  examName
					// 出题人 createBy
					// 题目总数 questionsNum
					// 题目总分 scoreNum
					// 考试时长 paperPeriod
					// 考试说明 remark
					// 考试类型 0选人 1自主填报
				},
				paper: null,
				examId: null,
				isPaper: false,
				isUser: false,
				isH5: false,

			}
		},
		methods: {
			async unbindMiniOpenid() {
				let res = {
					examId: uni.getStorageSync("examData").id,
					openId: uni.getStorageSync("openId")
				}
				let data = await unbindMiniOpenid(res);
				uni.setStorageSync("token", "");
				uni.setStorageSync("user", "");
				uni.showToast({
					title: '退出成功',
					icon: 'none',
					duration: 1500
				})
			},
			register() {
				this.registerFormData = {
					studentName: '',
					loginName: '',
					password: '',
				};
				this.$refs.popup1.open();
			},
			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.htmlData = data.data;
				uni.setStorageSync("examData", data.data);
				if(uni.getStorageSync("examData").id != uni.getStorageSync("oldExamId")||uni.getStorageSync("examData").examType != uni.getStorageSync("oldExamType")){
					uni.setStorageSync("token", "");
					uni.setStorageSync("user", "");
					// // #ifdef H5
					// location.reload();
					// //	#endif
				}
				if (uni.getStorageSync("user")) {
					this.isUser = true;
				} else {
					this.isUser = false;
				}
			},
			async phoneLogin(res,is) {
				//卷子是否存在
				
				//防止重复登录 
				if (!uni.getStorageSync("token") || !uni.getStorageSync("user")||is) {
					console.log(!uni.getStorageSync("token"),'!uni.getStorageSync("token")');
					console.log(!uni.getStorageSync("user"),'!uni.getStorageSync("user")');
					console.log(res.is,'res.is');
					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);
					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: '还有未答完的试卷！',
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/test/test?paper=true'
									});
								} else if (res.cancel) {
									// alert('用户点击取消');
								}

							}
						})
					} else {
						this.starExam();
					}
				} else {
					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.navigateTo({
							url: '/pages/test/test?paper=true'
						});
					} else {
						this.starExam();
					}
				}

			},
			//开始答题
			async starExam() {
				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() {
				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
						});
					// }
				} 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,
						
					},true);
					this.$refs.popup.close()
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			registerData(ref) {
				this.$refs[ref].validate().then(res => {
					this.registerText({
						...res,
						examId: this.htmlData.id,
					});

				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			async registerText(res) {
				let data = await register(res);
				uni.showToast({
					title: '注册成功',
					icon: 'none',
					duration: 1500
				})
				this.$refs.popup1.close();
				console.log(data, '111');
			},
			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);
					// 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);
					//存在卷，并且卷还在进行中
					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 {
						this.isPaper = false;
					}
				} else {
					uni.setStorageSync("token", "");
					uni.setStorageSync("user", "");
				}
			},
			getParam(path, name) {

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

				if (reg.test(path))

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

				return "";

			},
			outLogin() {
				let that = this;
				uni.showModal({
					title: '提示',
					content: '确定退出当前用户吗？',
					success: function(res) {
						if (res.confirm) {

							that.isUser = false;
							that.isH5 = false;
							//H5页面不是响应式的
							// #ifdef H5
							uni.setStorageSync("token", "");
							uni.setStorageSync("user", "");
							uni.showToast({
								title: '退出成功',
								icon: 'none',
								duration: 5000
							})
							location.reload();
							//	#endif
							// #ifdef MP-WEIXIN
							that.unbindMiniOpenid();
							// #endif
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			}
		},
		async onShow() {
			//// #ifdef H5
			//   openId.getOpenId(() => {
			//   let dt = window.localStorage.getItem("openId");
			//   console.log(dt,'dt');
			// });
			//// 	#endif
			
			
			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 = 70;
			// 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;
	}

	.buttonStyle1 {
		width: 85%;
		margin-left: 7%;
		margin-top: 30rpx;
		margin-bottom: 30rpx;
		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>
