<template>
	<div class="testPaper" id="testPaper">
		<div class="content">
			<div class="paper-left">
				<div class="paperName">{{this.paperName}}</div>
				<el-divider></el-divider>
				<div class="bigBox">
					<div class="operating" v-for="(item,index) in this.paperData.questionsInfoVos">
						<div class="title">
							<span>{{index+1}}、</span>
							<span>[{{item.typeName}}] </span>
							<span v-html="item.question"></span>
							<span>({{item.score}}分)</span>
							<div class="title_tag" :class="{ 'isActive': item.tag }" @click="clickTag(item)">
								<i class="el-icon-star-on">标记</i>
							</div>
						</div>
						<div class="operating_content">
							<el-radio-group v-model="item.result" v-if="item.type==1" @change="changeResult">
								<el-radio :label="x.optionKey" v-for="x in item.options">{{x.optionKey}}、<span
										v-html="x.optionContent"></span></el-radio>
							</el-radio-group>
							<el-checkbox-group v-model="item.result" v-if="item.type==2" @change="changeResult">
								<el-checkbox :label="x.optionKey" v-for="x in item.options">{{x.optionKey}}、<span
										v-html="x.optionContent"></span></el-checkbox>
							</el-checkbox-group>
							<el-radio-group v-model="item.result" v-if="item.type==3" @change="changeResult">
								<!-- <el-radio :label="x.optionKey" v-for="x in item.options" > <span v-html="x.optionContent"></span><i :class="el-icon-check"></i></el-radio> -->
								<el-radio label="1">对</el-radio>
								<el-radio label="0">错</i></el-radio>
							</el-radio-group>
							<el-input v-model="item.result" v-if="item.type==4" placeholder="请输入答案"
								@blur="changeResult(item.result)"></el-input>
							<el-input v-model="item.result" v-if="item.type==5" type="textarea" :rows="3"
								@blur="changeResult(item.result)" placeholder="请输入答案">
							</el-input>
							<el-input v-model="item.result" v-if="item.type==6||item.type==7" type="textarea" :rows="3"
								@blur="changeResult(item.result)" placeholder="请输入答案">
							</el-input>
						</div>
					</div>
				</div>
			</div>
			<div class="paper-right">
				<div class="block">
					<el-avatar :size="50" :src="circleUrl"></el-avatar>
				</div>
				<div class="information">
					<span>姓名：{{ $store.state.login.currentUser.username}}</span>
					<el-divider></el-divider>
					<div class="second">
						<div>{{ `${hr}:${min}: ${sec}` }}</div>
						<div>
							<i class="el-icon-alarm-clock" style="color: #2BA5FC;"></i>总剩余时间
						</div>
						<div>总题数:{{this.paperData.totalNumber}}</div>
						<div>总分数:{{this.paperData.totalScore}}</div>
					</div>
					<el-divider></el-divider>
					<div class="third">
						<div>题卡</div>
						<div style="maxHeight:40vh;overflowY:auto">
							<el-tag class="tagBox"
								:class="[{'isTag':(t.result.length!==0&&t.result!=='')}]" type="info"
								v-for="(t,ti) in this.paperData.questionsInfoVos">{{ti+1}}

							<i v-if="t.tag" class="el-icon-star-on"></i>
							</el-tag>
						</div>
					</div>
					<el-divider></el-divider>
					<div class="fourth">
						<el-button type="primary" @click="submitPaper">提交试卷</el-button>
					</div>
				</div>
			</div>
		</div>
		<div class="fullBox" v-if="!isFull">
			<div class="fullScreen" v-if="firstFull">
				<img src="@/assets/img/fullscreen.jpg" alt="">
				<div class="screen">
					当前考试<span>已开启防切屏</span>，您即将进入<span>全屏考试</span>
				</div>
				<span>（退出全屏将判定为切屏一次，请勿退出全屏）</span>
				<div class="footer">
					<el-button type="warning" id="full_screen">进入全屏，开始考试</el-button>
				</div>
			</div>
			<div class="leaveFull" v-if="!firstFull">
				<div class="img">
					<img src="@/assets/img/switch.png" alt="">
				</div>
				<div class="full-content">
					<div>
						您已离开考试{{this.paperData.inSwitchCount}}次
					</div>
					<span>当离开超过{{this.paperData.switchCount}}次时将强制交卷</span>
				</div>
				<div>
					<el-button type="warning" @click="Continue">继续考试</el-button>
				</div>
			</div>
		</div>

	</div>
</template>

<script>
import {TableMixin} from '@/mixins/tableMixin'
import dictUtils from '@/components/dict/DictSelectUtils.js'
import paperMenu from '@/api/examination/paperMenu.js'
import screenfull from 'screenfull'

export default {
		mixins: [TableMixin],
		name: 'formalTestPaper',
		components: {},
		data() {
			return {
				circleUrl: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png", //头像
				hr: 1,
				min: 60,
				sec: 0,
				radio: '',
				checkList: [],
				radio3: '',
				input: '',
				textarea: '',
				end: null,
				paperData: {}, //试卷数据
				topicList: [], //题目类型
				formalType: false, //正式考试
				param: {
					status: 0,
					recordId: null,
					questionOptionList: []
				},
				userKey: null,
				paperName: null,
				newParams: {

				},
				isFull: false,
				firstFull: true, //是否第一次全屏
				isScreen: false,
				nums: 0,
				lastTime: 0, //默认上一次点击时间为0

			}
		},
		created() {
			this.topicList = dictUtils.getDictItemsFromCache('sttx')
		},
		watch: {
			nums(newvalue, oldvalue) {
				if (this.nums == 2) {
					this.nums = 0
					console.log('增加一次');
					this.getswitchCount()
				}
			},
		},
		mounted() {
			const element = document.getElementById('testPaper');
			document.getElementById('full_screen').addEventListener('click', () => {
				if (screenfull.isEnabled) {
					screenfull.request(element); // 元素全屏
					// this.firstFull = false
					this.isFull = true
					this.isScreen = false
				}
			})
			window.addEventListener("resize",
				this.a
			)

		},
		destroyed() {
			window.removeEventListener('resize',this.a)

		},
		methods: {
			Continue() {
				const element = document.getElementById('testPaper');
				if (screenfull.isEnabled) {
					screenfull.request(element); // 元素全屏
					this.isFull = true
					this.firstFull = false
					this.$set(this.isFull)

				}
			},
			b() {
				if (window.outerHeight === screen.availHeight) {
					if (window.outerWidth === screen.availWidth) {
						this.isFull = false
						this.firstFull = false
						this.isScreen = false
						console.log('退出');
						this.getswitchCount()
					} else {
						this.isScreen = false
						console.log('退出1');

					}
				} else {
					if (this.isScreen) {
						this.isFull = false
						this.firstFull = false
						this.nums++
					} else {

					}
					this.isScreen = true

				}
			},
			a() {
				console.log('触发次数+1');
				this.debounce(this.b(), 1000)
			},

			getswitchCount() {
				console.log('增加作弊次数');
				// return
				paperMenu.switchCount(this.param.recordId, res => {
					if (res.errorCode == 201) {
						window.removeEventListener('resize', this.a)
						this.mandatory()
					} else {
						this.loadData()
					}
				})
			},

			debounce(fn, wait) {
				let timeout = null;
				wait = wait || 3000;
				return function() {
					let that = this;
					if (timeout !== null) clearTimeout(timeout);
					timeout = setTimeout(() => {
						fn.apply(that);
					}, wait);
				}
			},
			loadData() {
				console.log(this.$route.params);
				if (this.$route.params.paperId !== {} && typeof(this.$route.params.paperId) === 'string') {
					this.userKey = this.$route.params.paperId
					this.paperName = this.$route.params.name
					sessionStorage.setItem('userkey', this.userKey) //初次收到userKey，存起来
					sessionStorage.setItem('paperName', this.paperName) //初次收到userKey，存起来
				} else {
					if (sessionStorage.getItem('userkey')) {
						this.userKey = sessionStorage.getItem('userkey') //不是第一次了，取出来
						this.paperName = sessionStorage.getItem('paperName') //不是第一次了，取出来
					} else {
						//如果实在是没有了，就直接去store里面取
						this.userKey = store.state.user.userInfo.userKey
						this.paperName = store.state.user.userInfo.paperName
					}
				}

				let params = {
					recordId: this.userKey,
					userId: '',
				}
				paperMenu.startExam(params, res => {
					if (res) {
						let minutes = (res.timeLength / 1000) / 60;
						this.end = Date.parse(new Date()) + ((1 * minutes * 60)) * 1000
						this.countdown()
						res.questionsInfoVos.forEach(e => {
							e.tag = false
							if (e.result) {
								if (e.type == 2) {
									let arr = JSON.parse(JSON.stringify(e.result.split(",")))
									e.result = []
									arr.forEach(re => {
										e.result.push(re)
									})
								}
							} else {
								if (e.type == 2) {
									e.result = []
								} else {
									e.result = ''
								}
							}
							this.topicList.forEach(t => {
								if (e.type == t.value) {
									e.typeName = t.name
								}
							})
						})
						this.paperData = res
						this.$set(this.paperData)
						this.param.recordId = res.recordId

					}
				})


			},
			countdown() {
				const now = Date.parse(new Date())
				let msec = this.end - now
				if (msec < 0) return;
				let day = parseInt(msec / 1000 / 60 / 60 / 24)
				let hr = parseInt(msec / 1000 / 60 / 60 % 24)
				let min = parseInt(msec / 1000 / 60 % 60)
				let sec = parseInt(msec / 1000 % 60)
				this.day = day
				this.hr = hr > 9 ? hr : '0' + hr
				this.min = min > 9 ? min : '0' + min
				this.sec = sec > 9 ? sec : '0' + sec
				const that = this
				if (hr >= 0 && min >= 0 && sec >= 0) {
					//倒计时结束关闭订单
					if (hr == 0 && min == 0 && sec == 0) {
						this.$message({
							type: 'warning',
							message: '考试时间结束,已自动提交试卷'
						});
						clearInterval(this.timer)
						// this.submitPaper()
						this.param.questionOptionList = []
						this.paperData.questionsInfoVos.forEach(e => {
							if (e.type == 2) {
								let ts = ""
								e.result.forEach((r, ri) => {
									if (ri == 0) {
										ts = r
									} else {
										ts += ',' + r
									}
								})
								e.result = ts
							}
							this.param.questionOptionList.push({
								questionId: e.questionId,
								result: e.result

							})
						})
						this.param.status = 1
						paperMenu.submitAnswer(this.param, res => {
							if (res.state) {
								clearInterval(this.timer)
								this.$router.go(-2)
							}
						})
						return
					} else {
						this.timer = setTimeout(function() {
							that.countdown()
						}, 1000)
					}

				}
			},
			changeResult(val) {
				console.log(val);
				if (val.length > 0 || val != '') {
					this.param.status = 0
					this.newParams = {}
					this.param.questionOptionList = []
					this.newParams = JSON.parse(JSON.stringify(this.paperData))
					this.newParams.questionsInfoVos.forEach(e => {
						if (e.type == 2) {
							let ts = ""
							if (e.result.length > 0) {
								e.result.forEach((r, ri) => {
									if (ri == 0) {
										ts = r
									} else {
										ts += ',' + r
									}
								})
							}

							e.result = ts
						}
						this.param.questionOptionList.push({
							questionId: e.questionId,
							result: e.result

						})

					})
					paperMenu.submitAnswer(this.param, res => {
						if (res.state) {}
					})
				}
			},
			//提交试卷
			submitPaper() {

				console.log('提交试卷');
				// return
				this.param.questionOptionList = []
				this.paperData.questionsInfoVos.forEach(e => {
					if (e.type == 2) {
						console.log(e.result);
						let ts = ""
						if (e.result.length > 0) {
							e.result.forEach((r, ri) => {
								if (ri == 0) {
									ts = r
								} else {
									ts += ',' + r
								}
							})
							e.result = ts
						}else{
							e.result = ts
						}

					}
					this.param.questionOptionList.push({
						questionId: e.questionId,
						result: e.result

					})
				})

					this.param.status = 1
					paperMenu.submitAnswer(this.param, res => {
						if (res.state) {
							clearInterval(this.timer)
							this.$message({
								type: 'success',
								message: '提交成功'
							});
							this.$router.go(-2)
						}
					})



				// this.$router.push({
				// 	name: 'paperMenu'
				// })
				// this.$router.go(-1)
			},
			clickTag(item) {
				item.tag = !item.tag
			},
			//强制交卷
			mandatory() {
				console.log('强制交卷');
				this.param.status = 1
				paperMenu.submitAnswer(this.param, res => {
					if (res.state) {
						clearInterval(this.timer)
						this.$message({
							type: 'success',
							message: '已强制交卷'
						});
						this.$router.go(-2)
					}
				})
			}
		}
	}
</script>

<style>
	.testPaper p {
		display: inline !important;
	}
</style>
<style lang="scss" scoped>
	.testPaper {
		background-color: #EBEEF5;
		display: flex;
		justify-content: space-evenly;

		.content {
			width: 1200px;
			display: flex;

			.paper-left {
				padding: 10px 20px;
				box-sizing: border-box;
				background-color: #FFFFFF;
				width: 80%;
				margin-right: 10px;

				.paperName {
					margin-top: 20px;
					text-align: center;
					font-size: 24px;
				}

				.operating {
					margin: 10px 10px 10px 0;

					.title {
						padding: 20px 0;

						span:nth-child(1) {
							font-weight: bold;
						}

						span:nth-child(2) {
							color: #34A9FD;
						}



						.title_tag {
							display: inline-block;
							border: 1px solid #E4E7ED;
							padding-right: 3px;
							box-sizing: border-box;
							margin-left: 5px;
							color: #FFA500;
						}

						.isActive {
							background-color: #FFA500;
							color: #FFFFFF !important;
						}
					}
				}
			}

			.paper-right {
				background-color: #FFFFFF;
				padding: 0 20px;
				width: 20%;

				.block {
					height: 120px;
					display: flex;
					align-items: center;
					justify-content: space-evenly;
				}

				.information {
					.second {
						text-align: center;

						div:nth-child(1) {
							font-size: 26px;
							color: #34A9FD;
						}

						div:nth-child(4) {
							font-weight: 700;
							line-height: 30px;
						}

						div:nth-child(3) {
							margin-top: 20px;
							font-weight: 700;
							line-height: 30px;
						}
					}

					.third {
						// text-align: center;

						div:nth-child(1) {
							text-align: center;
							height: 30px;
						}
					}

					.fourth {
						text-align: center;
					}
				}
			}
		}

	}

	.tagBox {
		width: 40px;
		height: 35px;
		line-height: 35px;
		margin-right: 5px;
		text-align: center;
		margin-bottom: 5px;
		position: relative;
		i{
			position: absolute;
			right: 0;
			top: 0;
			color: #FFA500;
		}
	}

	.tag {
		background-color: #FFA500 !important;
		color: #FFFFFF;
	}

	.isTag {
		background-color: #36AAFD;
		color: #FFFFFF;
	}

	.bigBox {
		height: calc(100% - 100px);
		overflow-y: auto;
	}

	.fullScreen {
		width: 700px;
		height: 500px;
		background-color: #FFFFFF;
		border-radius: 20px;
		position: absolute;
		top: 20%;
		left: 30%;
		z-index: 999;
		overflow: hidden;
		color: #999;

		img {
			width: 100%;
		}

		.screen {
			color: #000;
			font-size: 20px;
			font-weight: bold;

			span {
				font-size: 20px;
				color: #36AAFD;
			}
		}

		.footer {
			margin-top: 20px;
		}
	}

	.leaveFull {
		width: 300px;
		height: 400px;
		top: 20%;
		left: 40%;
		border-radius: 10px;
		position: absolute;
		background-color: #FFFFFF;
		display: flex;
		flex-direction: column;
		justify-content: space-evenly;
		padding: 20px;
		box-sizing: border-box;

		img {
			width: 100%;
		}

		.full-content {
			div {
				font-size: 20px;
				font-weight: bold;
				line-height: 40px;
			}

		}
	}

	.fullBox {
		position: absolute;
		width: 100%;
		height: 100%;
		z-index: 5;
		background-color: rgba(54, 54, 54, .5);
		text-align: center;
	}
	::-webkit-scrollbar {
	   width: 3px !important;
	 }

</style>
