<template>
	<div  >
		<div
			style="padding: 10px;text-align: center;font-size: 20px;font-weight: bold;border-bottom: 2px solid #60A900;position: relative;">
			{{sjConfig.PaperName}}
			<div style="position: absolute;right: 0;bottom: 10px;font-weight: normal;font-size: 14px;">
				{{allNum}}
			</div>
		</div>
		<div style="padding: 10px 20px;position: relative;display: flex;">
			<div style="width:calc(100% - 360px)">
				<div v-for="(v,i) in content" :key="i">
					<div v-for="(item,key) in v" :key="key">
						<div v-if="key == '27'" style="margin-bottom: 10px;">
							<span v-if="i==0">
								一、
							</span>
							<span v-else-if="i==1">
								二、
							</span>
							<span v-else>
								三、
							</span>
							单选题 （{{'共'+item.count+'题,共'+item.score+'分'}}）
						</div>
						<div v-else-if="key == '28'" style="margin-bottom: 10px;">
							<span v-if="i==0">
								一、
							</span>
							<span v-else-if="i==1">
								二、
							</span>
							<span v-else>
								三、
							</span>
							多选题 （{{'共'+item.count+'题,共'+item.score+'分'}}）
						</div>
						<div v-else style="margin-bottom: 10px;">
							<span v-if="i==0">
								一、
							</span>
							<span v-else-if="i==1">
								二、
							</span>
							<span v-else>
								三、
							</span>
							判断题 （{{'共'+item.count+'题,共'+item.score+'分'}}）
						</div>
						<div v-for="(value,index) in item.rubricInfos" :key="value.RubricID">
							<div v-if="key == '27'" style="width:calc(100% - 30px);">
								<danxuan :id="`#question-${value.tihao}`" :content="value" :index="index" :fIndex="i" :show="show" @chooseXx="chooseDanx">
								</danxuan>
							</div>
							<div v-else-if="key == '28'" style="width:calc(100% - 30px);">
								<duoxuan :id="`#question-${value.tihao}`" :content="value" :index="index" :fIndex="i" :show="show" @chooseXx="chooseDuox">
								</duoxuan>
							</div>
							<div v-else style="width:calc(100% - 30px);">
								<panduan :id="`#question-${value.tihao}`" :content="value" :index="index" :fIndex="i" :show="show" @chooseXx="choosePand">
								</panduan>
							</div>
						</div>
					</div>
				</div>
			</div>
			
			<!-- <div class="flex-ac-jc pd-20">
				<el-button type="primary" @click="submitSj">交 卷</el-button> 
			</div> -->
			<div style="position: relative;width: 384px;">
				<div style="position: sticky;top: 10px;width: 384px;background-color: #fff;border: 2px solid #ccc;padding:5px 10px;border-radius: 10px;">
					<div style="color: #F56C6C;font-size: 20px;font-weight: bold;" class="p-b-10">
						考试剩余时间：{{this.min+"分"+this.miao+"秒"}}
					</div>
					<div v-for="(v,i) in content" :key="i">
						<div v-for="(item,key) in v" :key="key" >
							<div v-if="key == '27'" class="m-b-10">
								<span v-if="i==0">
									一、
								</span>
								<span v-else-if="i==1">
									二、
								</span>
								<span v-else>
									三、
								</span>
								单选题 （{{'共'+item.count+'题,共'+item.score+'分'}}）
							</div>
							<div v-else-if="key == '28'" class="m-b-10">
								<span v-if="i==0">
									一、
								</span>
								<span v-else-if="i==1">
									二、
								</span>
								<span v-else>
									三、
								</span>
								多选题 （{{'共'+item.count+'题,共'+item.score+'分'}}）
							</div>
							<div v-else class="m-b-10" >
								<span v-if="i==0">
									一、
								</span>
								<span v-else-if="i==1">
									二、
								</span>
								<span v-else>
									三、
								</span>
								判断题 （{{'共'+item.count+'题,共'+item.score+'分'}}）
							</div>
							<div style="width: 100%;display: flex;flex-wrap: wrap;box-sizing: border-box;border-collapse: collapse;" class="m-b-10"> 
								<div v-for="(value,index) in item.rubricInfos" :key="value.RubricID" style="width: 60px;border:1px solid #ccc;margin-bottom:-1px;margin-right: -1px;" class="pd-10 flex-ac-jc tihao" :style="{backgroundColor:value.userAnswer !=='' && value.userAnswer != null?'#1890ff':'#fff',color:value.userAnswer !=='' && value.userAnswer != null?'#fff':'#606266'}" @click="scrollToQuestion(index,value)"  >
									{{value.tihao}}
								</div>
							</div>
							
						</div>
					</div>
					<div style="display: flex;justify-content: center;position: absolute;bottom: -44px;left: 50%;transform: translateX(-50%);">
						<el-button type="primary" @click="submitSj">提交试卷</el-button>
					</div>
				</div>
				
			</div>
			
		</div>
	</div>
</template>

<script>
	import danxuan from "./danxuan.vue"
	import duoxuan from "./duoxuan.vue"
	import panduan from "./panduan.vue"
	import {
		submitDaan,
		autoSave
	} from "@/api/jianliyuan/index"
	export default {
		name: "Zhengjuan",
		props: {
			content: { // 传入的地址
				type: Object,
				default: null,
			},
			sjConfig: {
				type: Object,
				default: null
			},
			personId:{
				type:Number,
				default:null
			},
			userScore:{
				type:Object,
				default:null
			}
		},
		components: {
			danxuan,
			duoxuan,
			panduan
		},
		data() {
			return {
				show: false,
				answerList: [],
				allNum: null,
				min:null,
				second:59,
				miao:59,
				ti:null,
				startTime:null,
				saveTi:null,
				saveTime:null,
			};
		},
		mounted() { 
			
			if(this.userScore == null){
				this.startTime = this.parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}')
				this.min = this.sjConfig.ExamTime-1
			}else{
				this.startTime = this.userScore.StartTime
				let start = new Date(this.userScore.StartTime).getTime()
				let now = new Date().getTime()
				let cha = Math.floor((now-start)/1000) 
				this.min = this.sjConfig.ExamTime-1-Math.floor(cha/ 60)
				this.second =60 - cha % 60; 
			}
			if(this.sjConfig.AutoSave != 0 && this.sjConfig.AutoSave != "" && this.sjConfig.AutoSave != null ){
				this.saveTime = this.sjConfig.AutoSave*60 
				this.zdSave()
			} 
			this.getAllNum()
			
			this.ti = setInterval(()=>{
				this.second --
				if(this.second == 59){
					this.min --
					if(this.min == 0){
						clearInterval(this.ti) 
						this.$msgbox({
						    title: '提示',
						    message:"答题时间已到，请交卷。",
						    confirmButtonText: '交 卷',
							showCancelButton:false,
							showClose:false,
							closeOnClickModal:false,
							closeOnPressEscape:false,
						    beforeClose: (action, instance, done) => {
						        if (action === 'confirm') {
						            instance.confirmButtonLoading = true;
						            instance.confirmButtonText = '交卷中...';
						            submitDaan({
										startTime:this.startTime,
										endTime:this.parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}'),
										paperInfo:this.sjConfig,
						            	list:arry,
						            	personId:this.personId,
						            	userId:this.$store.state.user.userInfo.ID
						            }).then(res=>{
						            	done();
										instance.confirmButtonLoading = false;
										setTimeout(()=>{
											this.tc(res.data)
										},50)
						            })
						        } else {
									done();
						        }
						    }
						})
					}
				}
				if(this.second>=10){
					this.miao = this.second
				}else if(this.second<10 ){
					this.miao = '0'+this.second
				}
				if(this.second == 0){
					this.second = 60
				}
				
			},1000)
		},
		beforeDestroy(){
			clearInterval(this.saveTi)
			clearInterval(this.ti)
		},
		methods: { 
			getAllNum() {
				let num = 0
				let score = 0
				for (let i in this.content) {
					this.answerList.push([])
					for (let q in this.content[i]) {
						this.answerList[i] = this.content[i][q].rubricInfos
						num += this.content[i][q].count
						score += this.content[i][q].score
					}
				}
				this.allNum = "总共" + num + "题 共" + score + "分" 
			},
			//选择单选
			chooseDanx(e) { 
				this.answerList[e.fIndex][e.index].userAnswer = e.xx
			},
			//多选
			chooseDuox(e) {
				this.answerList[e.fIndex][e.index].userAnswer = e.xx
			},
			//判断
			choosePand(e) {
				this.answerList[e.fIndex][e.index].userAnswer = e.xx
			},
			//提交试卷
			submitSj() {
				let arry = [].concat(...this.answerList)
				for (let i in arry) {
					if (arry[i].userAnswer === "" || arry[i].userAnswer == null) {
						this.$msgbox({
						    title: '提示',
						    message:"题目未全部答完，是否交卷?",
						    showCancelButton: true,
						    confirmButtonText: '交 卷',
						    cancelButtonText: '取 消', 
							showClose:false,
							closeOnClickModal:false,
							closeOnPressEscape:false,
						    beforeClose: (action, instance, done) => {
						        if (action === 'confirm') {
						            instance.confirmButtonLoading = true;
						            instance.confirmButtonText = '交卷中...';
									clearInterval(this.saveTi)
						            submitDaan({
										startTime:this.startTime,
										endTime:this.parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}'),
										paperInfo:this.sjConfig,
						            	list:arry,
						            	personId:this.personId,
						            	userId:this.$store.state.user.userInfo.ID
						            }).then(res=>{
						            	done();
										instance.confirmButtonLoading = false;
										setTimeout(()=>{
											this.tc(res.data)
										},50)
						            })
						        } else {
									done();
						        }
						    }
						})
						return
					}
				}
				this.$msgbox({
				    title: '提示',
				    message:"是否进行交卷?",
				    showCancelButton: true,
				    confirmButtonText: '交 卷',
				    cancelButtonText: '取 消', 
					showClose:false,
					closeOnClickModal:false,
					closeOnPressEscape:false,
				    beforeClose: (action, instance, done) => {
				        if (action === 'confirm') {
				            instance.confirmButtonLoading = true;
				            instance.confirmButtonText = '交卷中...';
							clearInterval(this.saveTi)
				            submitDaan({
								startTime:this.startTime,
								endTime:this.parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}'),
								paperInfo:this.sjConfig,
				            	list:arry,
				            	personId:this.personId,
				            	userId:this.$store.state.user.userInfo.ID
				            }).then(res=>{
				            	done();
								instance.confirmButtonLoading = false;
								setTimeout(()=>{
									this.tc(res.data)
								},50)
				            })
				        } else {
							done();
				        }
				    }
				})
			},
			scrollToQuestion(index,value) {  
			  const questionId = `#question-${value.tihao}`;  
			  const questionElement = document.getElementById(questionId);  
		  
			  if (questionElement) {    
				questionElement.scrollIntoView({ behavior: 'smooth' });  
			  }  
			}, 
			//成绩弹窗
			tc(data){
				const h = this.$createElement;
				if(data.PassState == 1){ 
					this.$msgbox({
					  title: '消息',
					  message: h('p', null, [
						h('span', null, `您的成绩是${data.TotalMark}分，`),
						h('i', { style: 'color: #67C23A' },'成绩合格' ),
						h('span',null,'，试卷详情请到“考试成绩”菜单进行查看。' ),
					  ]),
					  showCancelButton: false,
					  showClose:false,
					  closeOnClickModal:false,
					  closeOnPressEscape:false,
					  confirmButtonText: '确定',
					  cancelButtonText: '取消', 
					}).then(action => {
						this.$emit("subSuccess",data)
					});
				}else{ 
					this.$msgbox({
					  title: '消息',
					  message: h('p', null, [
						h('span', null, `您的成绩是${data.TotalMark}分，`),
						h('i', { style: 'color: #F56C6C' },'成绩不合格' ),
						h('span',null,'，试卷详情请到“考试成绩”菜单进行查看。' ),
					  ]),
					  showCancelButton: false,
					  showClose:false,
					  closeOnClickModal:false,
					  closeOnPressEscape:false,
					  confirmButtonText: '确定',
					  cancelButtonText: '取消',
					  
					}).then(action => {
						this.$emit("subSuccess",data)
					});
				}
			 
			},
			//自动保存
			zdSave(){
				this.saveTi = setInterval(()=>{
					if(this.saveTime == 0){
						this.baocun()
						return
					}
					this.saveTime-- 
				},1000)
			},
			baocun(){
				clearInterval(this.saveTi)
				let arry = [].concat(...this.answerList)
				autoSave({
					startTime:this.startTime,
					endTime:this.parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}'),
					paperInfo:this.sjConfig,
					list:arry,
					personId:this.personId,
					userId:this.$store.state.user.userInfo.ID
				}).then(res=>{ 
					this.saveTime = this.sjConfig.AutoSave*60
					this.zdSave()
				}).catch(error => { 
					this.saveTime = this.sjConfig.AutoSave*60
					this.zdSave()
				})
			}
		},
	};
</script>

<style scoped lang="scss">
	.b-t-2{
		border-top: 2px solid #ccc;
	}
	.b-t-1{
		border-top: 1px solid #ccc;
	}
	.b-l-2{
		border-left: 2px solid #ccc;
	}
	.b-l-1{
		border-left: 1px solid #ccc;
	}
	.b-r-2{
		border-right: 2px solid #ccc;
	}
	.b-r-1{
		border-right: 1px solid #ccc;
	}
	.b-b-2{
		border-bottom: 2px solid #ccc;
	}
	.b-b-1{
		border-bottom: 1px solid #ccc;
	}
	.tihao:hover{
		cursor: pointer;
	}
</style>