<template>
	<view class="container">
		<view class="topBox">
			<view class="topMain" v-if="testList.length>0">
				<view class="testTitle">
					<view>{{serialIndex+1}}、</view>
					<view class="titleStyle">{{typeDice[testList[serialIndex].type]}}</view>
					<view class="questionTypes">{{testList[serialIndex].title}}</view>
				</view>
				<view class="topic">
					{{testList[serialIndex].questionStem}}
				</view>
				<view class="answer">
					<!--填空  -->
					<view v-if="testList[serialIndex].type=='gap'">
						<view v-for="(item,index) in testList[serialIndex].option" :key="index" class="gapStyle">
							<uni-easyinput v-model="testList[serialIndex].option[index].answer" placeholder="请输入您的答案"
								@input='changeInput' />
						</view>

					</view>
					<!--论述  -->
					<view v-else-if="testList[serialIndex].type=='discuss'">
						<uni-easyinput type="textarea" maxlength='-1' autoHeight v-model="testList[serialIndex].answer"
							placeholder="请输入您的答案" @input='changeInput' />
					</view>
					<!--单选判断  -->
					<view v-else-if="testList[serialIndex].type=='single'||testList[serialIndex].type=='judge'">
						<view class="singleClass" v-for="(item,index) in testList[serialIndex].option" :key="index" @click="changeSingleIndex(item.id)">
							<view class="mark" 
								:class="{active: testList[serialIndex].answer==item.id}">
								<!-- :class="{active: testList[serialIndex].answer!=''||testList[serialIndex].answer=='0'?index == testList[serialIndex].answer:false}"> -->
								{{option[index]}}
							</view>
							<view style="width: 90%;margin-top: 10rpx;">
								{{item.content}}
							</view>
						</view>
					</view>
					<!--多选  -->
					<view v-else-if="testList[serialIndex].type=='multiple'">
						<view class="singleClass" v-for="(item,index) in testList[serialIndex].option" :key="index" @click="changeMultipleIndex(item.id)">
							<view class="mark" :class="{active: testList[serialIndex].answer.indexOf(item.id) != -1}"
								>
								{{option[index]}}
							</view>
							<view style="width: 90%;margin-top: 10rpx;">
								{{item.content}}
							</view>
						</view>
					</view>

				</view>
				<view class="contenBox">
					<view style="display: flex; align-items: center;">
						<button type="primary" class="buttonStyle" @click="upQuestion" v-if="serialIndex>0">上一题</button>
						<button type="primary" class="buttonStyle" @click="nextQuestion">下一题</button>
					</view>
				</view>
			</view>
		</view>
		<view class="footer">
			<view class="footer_left footer_flex">
				<view @click="paper" class="cursorStyle">
					<uni-icons type="upload" size="20" color="#606266" class="iconMargin"></uni-icons> 交卷
				</view>
			</view>
			<view class="footer_center footer_flex">
				<uni-countdown ref="countDown" :show-day="false" :hour="0" :minute="second" :second="mini"
					class="iconMargin" @timeup="handPaper">
				</uni-countdown>
			</view>
			<view class="footer_right footer_flex">
				<view @click="popupNumber">
					<uni-icons type="wallet" size="20" color="#606266" class="iconMargin"></uni-icons>
					{{serialIndex+1}}/{{testList.length}}
				</view>
			</view>
		</view>
		<uni-popup ref="popupNumber" type="left">
			<view class="popupMain">
				<uni-icons type="closeempty" size="20" class="iPosition" @click="popupClose"></uni-icons>
				<view class="fontTitile">
					答题目录
				</view>
				<view class="hr"></view>
				<view class="serial">
					<view class="mark" v-for="(item,index) in testList" :key="index" @click="changeIndex(index)"
						:class="{active: index == serialIndex}">
						{{index+1}}
					</view>
				</view>
			</view>
		</uni-popup>
		<view class="phb" @click="goHome">
			<uni-icons type="home" 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>
	</view>
</template>

<script>
	import {
		startExam,
		answerSheet,
		unbindMiniOpenid,
	} from "../../utils/url.js";
	export default {
		data() {
			return {
				isUser: false,
				second: 10,
				mini: 0,
				// 题型字典
				typeDice: {
					single: '单选题',
					multiple: '多选题',
					judge: '判断题',
					gap: '填空题',
					discuss: '论述题',
				},
				// 选项前标签
				option: {
					0: 'A',
					1: 'B',
					2: 'C',
					3: 'D',
					4: 'E',
					5: 'F',
					6: 'G',
					7: 'H',
					8: 'I',
					9: 'J',
					10: 'K',
					11: 'L',
					12: 'M',
					13: 'N',
					14: 'O',
					15: 'P',
					16: 'Q',
					17: 'R',
					18: 'S',
					19: 'T',
					20: 'U',
					21: 'V',
					22: 'W',
					23: 'X',
					24: 'Y',
					25: 'Z'
				},
				//当前题的索引
				serialIndex: 0,
				//单选single 多选multiple 判断judge 填空gap 论述discuss 
				testList: [
					// {
					// 	type: 'gap',
					// 	title: '驾校题',
					// 	questionStem: '驾驶人连续驾驶机动车超过__小时，停车休息时间不得少于__分钟',
					// 	answer: '',
					// 	option: [{
					// 			tiankong: '',
					// 		},
					// 		{
					// 			tiankong: '',
					// 		}
					// 	]
					// },
					// {
					// 	type: 'single',
					// 	title: '初一数学',
					// 	questionStem: '一个多边形的每个内角都是144度，这个多边形是（）',
					// 	answer: '',
					// 	option: [{
					// 			content: '八边形'
					// 		},
					// 		{
					// 			content: '十边形'
					// 		},
					// 		{
					// 			content: '十二边形'
					// 		},
					// 		{
					// 			content: '十四边形'
					// 		},
					// 	]
					// },
					// {
					// 	type: 'multiple',
					// 	title: '初一政治',
					// 	questionStem: '学生学习的三个基本资料本领域包括（）',
					// 	answer: [],
					// 	option: [{
					// 			content: '认知'
					// 		},
					// 		{
					// 			content: '情感'
					// 		},
					// 		{
					// 			content: '意识'
					// 		},
					// 		{
					// 			content: '动作技能'
					// 		},
					// 	]
					// },
					// {
					// 	type: 'judge',
					// 	title: '驾校题',
					// 	questionStem: '驾驶人连续驾驶机动车超过4小时，停车休息时间不得少于20分钟',
					// 	answer: '',
					// 	option: [{
					// 			content: '正确'
					// 		},
					// 		{
					// 			content: '错误'
					// 		},
					// 	]
					// },
					// {
					// 	type: 'discuss',
					// 	title: '论述题',
					// 	questionStem: '谈一谈对学校的看法',
					// 	answer: '',
					// 	option: [{
					// 		tiankong: ''
					// 	}, ]
					// },
				],
			}
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			let data = uni.getStorageSync("examData");
			let res = uni.getStorageSync("user");

			this.second = parseInt(data.paperPeriod);
			this.examId = data.id;
			let paperData = uni.getStorageSync("paper");
			this.studentTestPaperId = paperData.id;
			this.changePaperData(paperData.paper.testQuestionsList);
			//存在未答试卷
			if (option.paper) {
				let parmar = uni.getStorageSync("testData");
				this.compareTest(parmar);
				let seIndex = uni.getStorageSync("serialIndex");
				if (seIndex) {
					this.serialIndex = seIndex;
				}

			}
			uni.setStorageSync("oldExamId", data.id);
			uni.setStorageSync("oldExamType", data.examType);
			uni.setStorageSync("oldLoginName", res.loginName);
			uni.setStorageSync("examFlg", 1);
			// console.log(data.id,'data');
			// console.log(res.loginName,'res');
			// examFlg
			// uni.setStorageSync("examId",);
			// if (option.paper) {
			// 	let paperData = uni.getStorageSync("paper");
			// 	this.studentTestPaperId = paperData.id;
			// 	console.log(paperData, 'paperData');
			// 	this.changePaperData(paperData.paper.testQuestionsList);
			// } else {
			// 	// console.log(option.paperPeriod, 'option.paperPeriod');
			// 	// this.second = 1;
			// this.$refs.countDown.update();
			// 	this.getExam(res.examId, res.loginName, res.loginPassword)
			// }

		},
		onShow() {
			uni.setStorageSync("isStop", true);
			this.time = this.getTime();
			if (uni.getStorageSync("user")) {
				this.isUser = true;
			} else {
				this.isUser = false;
			}
		},
		methods: {
			goHome() {
				uni.navigateTo({
					url: '/pages/index/index'
				});
			},
			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
				})
				uni.navigateTo({
					url: '/pages/index/index'
				});
			},
			outLogin() {
				let that=this;
				uni.showModal({
					title: '提示',
					content: '确定退出当前用户吗？',
					success: function(res) {
						if (res.confirm) {
							// #ifdef H5
							uni.setStorageSync("token", "");
							uni.setStorageSync("user", "");
							uni.showToast({
								title: '退出成功',
								icon: 'none',
								duration: 5000
							})
							uni.navigateTo({
								url: '/pages/index/index'
							});
							//	#endif
							// #ifdef MP-WEIXIN
							that.unbindMiniOpenid();
							// #endif
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			compareTest(parmar) {
				if (!parmar) {
					return false
				}
				let is = true;
				if (parmar.length === this.testList.length) {
					this.testList.map((item, index) => {
						if (item.id != parmar[index].id) {
							is = false;
						}
					})
					if (is) {
						this.testList = parmar;
					}
				}
			},
			getTime() {
				let date = new Date(),
					year = date.getFullYear(),
					month = date.getMonth() + 1,
					day = date.getDate(),
					hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
					minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
					second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				month >= 1 && month <= 9 ? (month = "0" + month) : "";
				day >= 0 && day <= 9 ? (day = "0" + day) : "";
				let timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
				return timer;
			},
			async getExam(examId, loginName, loginPassword) {
				uni.showLoading({
					title: '加载中'
				});
				let data = await startExam(examId, loginName, loginPassword);
				uni.hideLoading();
				this.studentTestPaperId = data.data.id;
				this.changePaperData(data.data.paper.testQuestionsList);
			},
			// qaq 问答题
			// singleChoice 单选题
			// judgment 判断题
			// cloze  填空题
			// multipleChoice 多选题
			changePaperData(data) {
				this.testList = [];
				for (var key in data) {
					if (data[key]) {
						switch (key) {
							case 'qaq':
								data[key].map(item => {
									this.testList.push({
										type: 'discuss',
										id: item.id,
										title: item.courseName,
										questionStem: item.stem,
										answer: '',
									})
								});

								break;
							case 'singleChoice':
								data[key].map(item => {
									this.testList.push({
										type: 'single',
										id: item.id,
										title: item.courseName,
										questionStem: item.stem,
										answer: '',
										option: item.testAnswerList.map(it => {
											return {
												id: it.id,
												content: it.answer
											}
										})
									})
								});
								break;
							case 'judgment':
								data[key].map(item => {
									this.testList.push({
										type: 'judge',
										id: item.id,
										title: item.courseName,
										questionStem: item.stem,
										answer: '',
										option: item.testAnswerList.map(it => {
											return {
												id: it.id,
												content: it.answer
											}
										})
									})
								});
								break;
							case 'cloze':
								data[key].map(item => {
									this.testList.push({
										type: 'gap',
										id: item.id,
										title: item.courseName,
										questionStem: item.stem,
										answer: '',
										option: item.testAnswerList.map(it => {
											return {
												answer: ''
											}
										})
									})
								});
								break;
							case 'multipleChoice':
								data[key].map(item => {
									this.testList.push({
										type: 'multiple',
										id: item.id,
										title: item.courseName,
										questionStem: item.stem,
										answer: [],
										option: item.testAnswerList.map(it => {
											return {
												id: it.id,
												content: it.answer
											}
										})
									})
								});
								break;
							default:
								break;
						}
					}
				}
			},
			paper() {
				let that = this;
				uni.showModal({
					title: '提醒',
					content: '确实交卷吗？',
					success: function(res) {
						if (res.confirm) {
							that.goPerformance();
							// alert('用户点击确认');
						} else if (res.cancel) {
							// alert('用户点击取消');
						}

					}
				})
			},
			popupNumber() {
				this.$refs.popupNumber.open()
			},
			popupClose() {
				this.$refs.popupNumber.close()
			},
			async goPerformance(isGo) {
				let answers = [];
				// let indexList=[];
				let accomplish = false;
				this.testList.map((item, index) => {
					// single: '单选题', answer里存索引
					// multiple: '多选题',answer里存数组
					// judge: '判断题',answer里存索引
					// gap: '填空题',答案存在option里面
					// discuss: '论述题',answer里存答案
					switch (item.type) {
						case 'single':
							if (item.answer) {} else {
								accomplish = true;
							}
							if (item.answer == "" || item.answer == null || item
								.answer == undefined) {
								accomplish = true;
							} else {
								answers.push({
									id: item.id,
									answer: item.answer
								})
							}
							break;
						case 'multiple':
							if (item.answer && item.answer.length > 0) {
								answers.push({
									id: item.id,
									answer: item.answer.join(',')
								})
							} else {
								accomplish = true;
							}
							break;
						case 'judge':
							if (item.answer) {} else {
								accomplish = true;
							}
							if (item.answer == "" || item.answer == null || item
								.answer == undefined) {
								accomplish = true;
							} else {
								answers.push({
									id: item.id,
									answer: item.answer
								})
							}
							break;
						case 'gap':
							answers.push({
								id: item.id,
								answer: item.option.map(item => {
									if (item.answer == "" || item.answer == null || item
										.answer == undefined) {
										accomplish = true;
									} else {
										return item.answer
									}
								}).join(',')
							})
							break;
						case 'discuss':
							if (item.answer) {
								answers.push({
									id: item.id,
									answer: item.answer
								})
							} else {
								accomplish = true;
							}
							break;
						default:
							break;
					}
				})
				uni.showLoading({
					title: '加载中'
				});
				await answerSheet({
					answers: JSON.stringify(answers),
					studentTestPaperId: this.studentTestPaperId,
					answerBegin: this.time
				});
				uni.hideLoading();
				uni.setStorageSync("isStop", false);
				uni.setStorageSync("paper", null);
				uni.setStorageSync("examFlg", 0);
				uni.setStorageSync("testData", null);
				uni.setStorageSync("serialIndex", 0);
				if(isGo)
				{
					let that=this;
					uni.showModal({
						title: '提醒',
						content: '答题时间到，请交卷！',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.redirectTo({
									url: '/pages/performance/performance?id=' + that.studentTestPaperId
								});
							} else if (res.cancel) {
								// alert('用户点击取消');
							}
					
						}
					})
				}else
				{
					uni.redirectTo({
						url: '/pages/performance/performance?id=' + this.studentTestPaperId
					});
				}
				
			},
			answerSheet(data) {
				uni.showLoading({
					title: '加载中'
				});
				uni.request({
					url: 'http://10.16.4.5:8080/education/app/answerSheet/add',
					method: 'POST',
					header: {

						'Authorization': "app-829f4a08-d148-4d0f-a4ad-e22695f44426",
						// 'Authorization': uni.getStorageSync('token'),
						// 'content-type': 'application/x-www-form-urlencoded',
						'content-type': 'application/json'
					},
					data: data,
					success: (response) => {

					},
					fail: (err) => {
						return uni.showToast({
							title: '请求接口失败' + err
						})
						reject(err)
					},
					complete: () => {
						uni.hideLoading();
					}
				})
			},
		    handPaper() {
				let that = this;
				if (uni.getStorageSync('isStop')) {
					 that.goPerformance(true);
				}
			},
			//单选判断选中
			changeSingleClass(index) {
				if (index == this.testList[this.serialIndex].answer) {
					return 'active'
				}
				return ''
			},
			//单选判断点击事件
			changeSingleIndex(id) {
				this.testList[this.serialIndex].answer = id;
				this.saveTest();
			},
			changeClass(index) {
				if (index == this.serialIndex) {
					return 'active'
				}
				return ''
			},
			changeIndex(index) {
				this.serialIndex = index;
			},
			changeMultipleClass(item, andList) {
				if (this.testList[this.serialIndex].answer.indexOf(item) != -1) {
					return 'active'
				}
				return ''

			},
			changeMultipleIndex(item) {
				if (this.testList[this.serialIndex].answer.indexOf(item) != -1) {
					this.testList[this.serialIndex].answer.splice(this.testList[this.serialIndex].answer.indexOf(item), 1)
				} else {
					this.testList[this.serialIndex].answer.push(item)
				}
				this.saveTest();
			},
			nextQuestion() {
				let that = this;
				if ((this.serialIndex + 1) == this.testList.length) {
					uni.showModal({
						title: '提醒',
						content: '已经是最后一题了，是否交卷？',
						success: function(res) {
							if (res.confirm) {
								that.goPerformance();
								// alert('用户点击确认');
							} else if (res.cancel) {
								// alert('用户点击取消');
							}

						}
					})
				} else {
					this.serialIndex++;
				}
			},
			upQuestion() {
				this.serialIndex--;
			},
			//简答、填空发生改变 进行本地缓存
			changeInput(e) {
				this.saveTest();
			},
			saveTest() {
				uni.setStorageSync("testData", this.testList);
				uni.setStorageSync("serialIndex", this.serialIndex);
			}
		}
	}
</script>

<style scoped>
	.container {
		position: absolute;
		height: 100%;
		width: 100%;
		background-color: #FFFFFF !important;
		color: #606266;
	}

	.topBox {
		height: 92%;
		background-color: #f7f8fa !important;
		position: relative;
	}

	.contenBox {
		position: absolute;
		bottom: 50rpx;
		width: 80%;
	}

	.footer {
		height: 8%;
		display: flex;
	}

	.footer_left {
		width: 30%;
	}

	.footer_center {
		width: 60%;
	}

	.footer_right {
		width: 30%;

	}

	.footer_flex {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.iconMargin {
		margin-right: 10rpx;
	}

	.topMain {
		width: 80%;
		height: 100%;
		margin: auto;
		display: flex;
		flex-direction: column;
	}

	.testTitle {
		display: flex;
	}

	.titleStyle {
		background-color: rgb(245, 166, 35) !important;
		padding: 4rpx 24rpx;
		border-radius: 5rpx;
		color: #FFFFFF;
		margin-right: 30rpx;
		width: 100rpx;
		height: 45rpx;
	}

	.questionTypes {
		padding: 4rpx 0;
	}

	.topic {
		margin: 40rpx 0;
	}

	.answer {
		height: 68%;
		overflow-y: auto;
	}

	.buttonStyle {
		/* width: 40%; */
		/* margin-top: 60rpx; */
		padding: 0 80rpx;
		font-size: 30rpx;
		background-color: rgb(245, 166, 35) !important;
		border-radius: 50rpx;
	}

	.cursorStyle {
		cursor: pointer;
	}

	.popupMain {
		width: 76vw;
		height: 100vh;
		background-color: #FFFFFF;
		position: relative;

	}

	.iPosition {
		position: absolute;
		right: 20rpx;
		top: 20rpx
	}

	.serial {
		display: flex;
		flex-wrap: wrap;
	}

	.mark {
		width: 50rpx;
		height: 50rpx;
		text-align: center;
		line-height: 50rpx;
		border-radius: 50%;
		margin: 10rpx;
		background-color: #e7ebf3;
		color: #000000;
	}

	.fontTitile {
		text-align: center;
		padding-top: 60rpx;
	}

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

	.active {
		background-color: rgb(245, 166, 35);
		color: #FFFFFF;
	}

	.singleClass {
		display: flex;
	}

	.gapStyle {
		margin-bottom: 20rpx;
	}

	.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;
	}
	.phb {
		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;
	}
</style>
