<template>
	<view>
		<view class="cu-custom" :style="[{height:CustomBar + 'px'}]">
			<view class="cu-bar fixed bg-gradual-blueness" :style="style">
				<view class="action" @tap="BackPage">
					<text class="cuIcon-back"></text>
					<slot name="backText">返回</slot>
				</view>
				<view class="content" :style="[{top:StatusBar + 'px'}]">
					<slot name="content">{{ titleContext }}</slot>
				</view>
				<view class="right">
					<slot name="right"></slot>
				</view>
				<!-- <slot name="right"></slot> -->
			</view>
		</view>
		<view class="course">
			<!-- <view v-show="!isExamStart" class="course-header">
				<view class="course-name">
					<text>试卷名称:{{ form.EXAMNAME }}</text>
				</view>
				<view class="course-name">
					<text>答卷时间:{{ form.ANSWERSHEETTIME }}</text>
				</view>
				<view class="course-obj">
					<text>试卷总共{{ form.QUESTIONNUM }}道题，答题时间共计{{ form.ANSWERSHEETTIME }}分钟，开始答题后计时到答卷时间后会自动提交试卷，请学员尽快答题。</text>
				</view>

				<view >
					<button class="cu-btn bg-green" @click="$noMultipleClicks(handleBegin)" >开始答题</button>
				</view>
			</view> -->
			<view v-show="isExamStart" class="course-aa">
				<view class="course-items" v-for="(row,i) in form.QUESTIONLIST" :key="row.QUESTION_ID">
					<view class="course-ask">
						{{ i + 1 }}.
						<text v-if="row.QUESTIONTYPE === '1'" class="mark">(单选题)</text>
						<text v-if="row.QUESTIONTYPE === '2'" class="mark">(多选题)</text>
						<text v-if="row.QUESTIONTYPE === '3'" class="mark">(判断题)</text>
						{{ row.QUESTIONDRY }}
					</view>
					<view class="course-answer">
						<radio-group v-if="row.QUESTIONTYPE == '1'" :disabled="isDisabled" v-model="form.ANSWER[i]" @change="radioQuestionChange($event,i)">
							<label class="answer-lable">
								<radio class="blue" :class="form.ANSWER[i]=='A'?'checked':''" :checked="form.ANSWER[i]=='A'?true:false" value="A"></radio>
								<text class="title">A.{{ row.OPTIONA }}</text>
							</label>
							<label class="answer-lable">
								<radio class="blue" :class="form.ANSWER[i]=='B'?'checked':''" :checked="form.ANSWER[i]=='B'?true:false" value="B"></radio>
								<text class="title">B.{{ row.OPTIONB }}</text>
							</label>
							<label class="answer-lable">
								<radio class="blue" :class="form.ANSWER[i]=='C'?'checked':''" :checked="form.ANSWER[i]=='C'?true:false" value="C"></radio>
								<text class="title">C.{{ row.OPTIONC }}</text>
							</label>
							<label class="answer-lable">
								<radio class="blue" :class="form.ANSWER[i]=='D'?'checked':''" :checked="form.ANSWER[i]=='D'?true:false" value="D"></radio>
								<text class="title">D.{{ row.OPTIOND }}</text>
							</label>
						</radio-group>
						<checkbox-group v-if="row.QUESTIONTYPE == '2'" class="checkbox" :disabled="isDisabled" v-model="form.ANSWER[i]"
						 @change="checkQuestionChange($event,i)">
							<label class="answer-lable">
								<checkbox :id="'checkA'+i" value="A"></checkbox>
								<text class="title">A.{{ row.OPTIONA }}</text>
							</label>
							<label class="answer-lable">
								<checkbox :id="'checkB'+i" value="B" :checked="form.ANSWER[i].includes('B')?true:false"></checkbox>
								<text class="title">B.{{ row.OPTIONB }}</text>
							</label>
							<label class="answer-lable">
								<checkbox :id="'checkC'+i" value="C" :checked="form.ANSWER[i].includes('C')?true:false"></checkbox>
								<text class="title">C.{{ row.OPTIONC }}</text>
							</label>
							<label class="answer-lable">
								<checkbox :id="'checkD'+i" value="D" :checked="form.ANSWER[i].includes('D')?true:false"></checkbox>
								<text class="title">D.{{ row.OPTIOND }}</text>
							</label>
						</checkbox-group>
						<radio-group v-if="row.QUESTIONTYPE == '3'" :disabled="isDisabled" v-model="form.ANSWER[i]" @change="radioQuestionChange($event,i)">
							<label class="answer-lable">
								<radio class="blue" :class="form.ANSWER[i]=='A'?'checked':''" :checked="form.ANSWER[i]=='A'?true:false" value="A"></radio>
								<text class="title">A.{{ row.OPTIONA }}</text>
							</label>
							<label class="answer-lable">
								<radio class="blue" :class="form.ANSWER[i]=='B'?'checked':''" :checked="form.ANSWER[i]=='B'?true:false" value="B"></radio>
								<text class="title">B.{{ row.OPTIONB }}</text>
							</label>
						</radio-group>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-tabbar-height"></view>
		<view v-show="isExamStart" class="bottom-fixed">
			<button class="cu-btn bg-green" @click="$noMultipleClicks(confirm)">提交</button>
		</view>
	</view>
</template>

<script>
  import { decryptAes } from "@/common/aesUtil";
	import {
		basePath,
		corpinfoId,
		deptId,
		loginSession,
		formatDate,
		loginUser
	} from '@/common/tool.js'

	export default {
		components: {},
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				bgImage: '',
				isExamStart: false,
				isDisabled: true,
				titleContext: '我的考试',
				STUDYTASK_ID: '',
				STAGEEXAMPAPER_ID: '',
				STAGESTUDENTRELATION_ID: '',
				timer: '',
				hour: 0,
				minutes: 0,
				seconds: 0,
				showRight: false,
				dataFlag: 'noData',
				sTop: 0,
				totalHeight: 0,
				form: {
					STAGEEXAMPAPER_ID: '', // 阶考ID
					EXAMNAME: '', // 试卷名称
					EXAMTIME: '', // 考试时间（开始时间）
					ANSWERSHEETTIME: '', // 答卷时间（持续时间）
					EXAMSCORE: 100, // 试卷分数
					QUESTIONNUM: '', // 试题数量（10、20、50、100）
					QUESTION_ID: [], // 试题ID数组
					QUESTIONTYPE: [], // 试题类型数组
					QUESTIONSCORE: [], // 试题分值
					ANSWER: [], // 学员答案
					ANSWERRIGHT: [] // 正确答案
				}, //页面数据
				subForm: {}, //交卷数据
				list: [], //返回数据
				page: 1, //分页参数--页数
				rows: 10, //分页参数--每页数据条数
				totalCount: 0, //分页参数--初始化页数
				isEnd: false, //防止多次刷新
				totalPage: 0, //分页参数--分页数量
				noClick: true
			}
		},
		computed: {
			style() {
				var StatusBar = this.StatusBar;
				var CustomBar = this.CustomBar;
				var bgImage = this.bgImage;
				var style = `height:${CustomBar}px;padding-top:${StatusBar}px;`;
				if (this.bgImage) {
					style = `${style}background-image:url(${bgImage});`;
				}
				return style
			}
		},
		onReady() {},
		onLoad(event) {
			this.STUDYTASK_ID = event.STUDYTASK_ID
			this.STAGEEXAMPAPER_ID = event.STAGEEXAMPAPER_ID
			this.STAGESTUDENTRELATION_ID = event.STAGESTUDENTRELATION_ID
			this.getData();
			loginSession();
		},
		onShow() {
		},
		onBackPress(options) {
			this.BackPage()
			return true
		},
		beforeDestroy(){
			if(this.timer) {
				clearInterval(this.timer) // 满足条件时 停止计时
				this.timer = null
				this.seconds = 0
				this.minutes = 0
			}
		},
		methods: {
			getData() {
				var _this = this;
				uni.showLoading({
					title: '请稍候'
				})
				uni.request({
					url: basePath + '/app/stageexampaper/getExam',
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						STAGEEXAMPAPER_ID: this.STAGEEXAMPAPER_ID,
            CORPINFO_ID:loginUser.CORPINFO_ID,
            USER_ID:loginUser.USER_ID,
					},
					success: (res) => {
            res.data = decryptAes(res.data);
						if ("success" == res.data.result) {
							uni.hideLoading();
							_this.form = Object.assign(_this.form, res.data.pd)
							_this.handleBegin()
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000
							});
						}
					}
				});
			},
			handleBegin() {
				// this.form.EXAMTIME = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')

				var new_date = new Date() // 新建一个日期对象，默认现在的时间
				var old_date = new_date // 设置过去的一个时间点，"yyyy-MM-dd HH:mm:ss"格式化日期
				var end_date = old_date.getTime() + (this.form.ANSWERSHEETTIME * 60 * 1000)
				// if (old_date.getTime() > new_date.getTime()) {
				// 	uni.showModal({
				// 		title: '提示',
				// 		content: '答题时间未到，不能进行考试！',
				// 		showCancel: false,
				// 		confirmText: '确定',
				// 		success: res => {
				// 			if (res.confirm) {
				// 				uni.redirectTo({
				// 					url: '/pages/application/onlinexxks/my-study?STAGESTUDENTRELATION_ID=' + this.STAGESTUDENTRELATION_ID
				// 				})
				// 			}
				// 		}
				// 	})
				// } else if (new_date.getTime() > end_date) {
				// 	uni.showModal({
				// 		title: '提示',
				// 		content: '答题时间已过，不能进行考试！',
				// 		showCancel: false,
				// 		confirmText: '确定',
				// 		success: res => {
				// 			if (res.confirm) {
				// 				uni.redirectTo({
				// 					url: '/pages/application/onlinexxks/my-study?STAGESTUDENTRELATION_ID=' + this.STAGESTUDENTRELATION_ID
				// 				})
				// 			}
				// 		}
				// 	})
				// } else if (old_date.getTime() <= new_date.getTime() && new_date.getTime() < end_date) { // 答题时间内才能作答
					if(this.timer) {
						clearInterval(this.timer) // 满足条件时 停止计时
						this.timer = null
						this.seconds = 0
						this.minutes = 0
					}
					this.form = Object.assign(this.form, {
						'EXAMTIMEBEGIN': formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
					})
					this.isExamStart = true
					this.isDisabled = false
					var difftime = new_date.getTime() - old_date.getTime() // 计算时间差（毫秒）

					// 计算相差分钟数
					var leave2 = difftime % (3600 * 1000) // 计算小时数后剩余的毫秒数
					this.minutes = Math.floor(leave2 / (60 * 1000))
					// 计算相差秒数
					var leave3 = leave2 % (60 * 1000) // 计算分钟数后剩余的毫秒数
					this.seconds = Math.round(leave3 / 1000)
					this.titleContext = '00:00'
					this.titleContext = (this.minutes < 10 ? '0' + this.minutes : this.minutes) + ':' + (this.seconds < 10 ? '0' + this.seconds : this.seconds)
					this.timer = setInterval(this.startTimer, 1000)
				// }
			},
			startTimer() {
				this.seconds += 1
				if (this.seconds >= 60) {
					this.seconds = 0
					this.minutes = this.minutes + 1
				}
				this.titleContext = (this.minutes < 10 ? '0' + this.minutes : this.minutes) + ':' + (this.seconds < 10 ? '0' + this
					.seconds : this.seconds)
				if (this.minutes == Number(this.form.ANSWERSHEETTIME) && this.seconds == 0) {
					if(this.timer) {
						clearInterval(this.timer) // 满足条件时 停止计时
						this.timer = null
						this.seconds = 0
						this.minutes = 0
					}
					this.subForm = Object.assign({}, this.form)
					for (let i = 0; i < this.subForm.ANSWER.length; i++) {
						if (this.subForm.QUESTIONTYPE[i] == '2') {
							this.subForm.ANSWER[i] = this.trimSpace(this.subForm.ANSWER[i])
							this.subForm.ANSWER[i] = this.subForm.ANSWER[i].length > 0 ? this.subForm.ANSWER[i].sort() : []
							if (this.subForm.ANSWER[i].length == 0) {
								this.subForm.ANSWER[i] = '-'
							}
						} else {
							if (this.subForm.ANSWER[i].length == 0) {
								this.subForm.ANSWER[i] = '-'
							}
						}
					}
					this.assignSubFormData()

					uni.showModal({
						title: '',
						content: '计时时间已到提交试卷！',
						showCancel: false,
						confirmText: '确定',
						success: res => {
							if (res.confirm) {
								this.submitForm()
							}
						}
					})
				}
			},
			radioQuestionChange(e, i) {
				this.form.ANSWER[i] = e.detail.value;
			},
			checkQuestionChange(e, i) {
				this.form.ANSWER[i] = e.detail.value;
			},
			confirm() {
				var confirmMsg = '试卷试题第'
				// this.subForm = Object.assign({}, this.form)  // 赋值会自动修改form中的数据，改为下面这种赋值方式
        this.subForm = JSON.parse(JSON.stringify(this.form));
				for (let i = 0; i < this.subForm.ANSWER.length; i++) {
					if (this.subForm.QUESTIONTYPE[i] == '2') {
						this.subForm.ANSWER[i] = this.trimSpace(this.subForm.ANSWER[i])
						this.subForm.ANSWER[i] = this.subForm.ANSWER[i].length > 0 ? this.subForm.ANSWER[i].sort() : []
						if (this.subForm.ANSWER[i].length == 0) {
							confirmMsg += (i + 1) + ','
							this.subForm.ANSWER[i] = '-'
						}
					} else {
						if (this.subForm.ANSWER[i].length == 0) {
							confirmMsg += (i + 1) + ','
							this.subForm.ANSWER[i] = '-'
						}
					}
				}
				confirmMsg = confirmMsg.length == 5 ? '确定要提交试卷吗？' : (confirmMsg.slice(0, confirmMsg.length - 1) +
					'题还没有作答，确定要提交试卷吗？')
				this.assignSubFormData()
				uni.showModal({
					title: '',
					content: confirmMsg,
					cancelColor: '#000000',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.submitForm()
						}
					}
				})
			},
			assignSubFormData() {
				var ANSWER_STR = ''
				for (let i = 0; i < this.subForm.ANSWER.length; i++) {
					if (this.subForm.QUESTIONTYPE[i] == '2') {
						ANSWER_STR += (this.subForm.ANSWER[i] == '-' ? '-' : this.subForm.ANSWER[i].join('')) + ','
					} else {
						ANSWER_STR += this.subForm.ANSWER[i] + ','
					}
				}
				this.subForm.ANSWER = ANSWER_STR.length > 0 ? ANSWER_STR.slice(0, ANSWER_STR.length - 1) : ''
				this.subForm.QUESTION_ID = this.subForm.QUESTION_ID.join(',')
				this.subForm.QUESTIONTYPE = this.subForm.QUESTIONTYPE.join(',')
				this.subForm.QUESTIONSCORE = this.subForm.QUESTIONSCORE.join(',')
				this.subForm.COURSEWAREID = this.subForm.COURSEWAREID.join(',')
				this.subForm.COURSEWARETYPE = this.subForm.COURSEWARETYPE.join(',')
				this.subForm.ANSWERRIGHT = this.subForm.ANSWERRIGHT.join(',')
				this.subForm.QUESTIONLIST = ''
				this.subForm.CORPINFO_ID = corpinfoId
				this.subForm.USER_ID = loginUser.USER_ID
				this.subForm.USERNAME = loginUser.USERNAME
				this.subForm.STAGESTUDENTRELATION_ID = this.STAGESTUDENTRELATION_ID
				this.subForm.STUDYTASK_ID = this.STUDYTASK_ID
			},
			submitForm() {
				uni.showLoading({
					title: '处理中'
				})
				if(this.timer) {
					clearInterval(this.timer) // 满足条件时 停止计时
					this.timer = null
					this.seconds = 0
					this.minutes = 0
				}
				this.isDisabled = true
				uni.request({
					url: basePath + '/app/stageexam/submit',
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
							...this.subForm,
							CORPINFO_ID:loginUser.CORPINFO_ID,
							USER_ID:loginUser.USER_ID,
						},
					success: (res) => {
            res.data = decryptAes(res.data);
						uni.hideLoading();
						const examScore = res.data.pd.EXAMSCORE
						var modelContent = '本次考试成绩' + examScore + '分'
						// if (examScore >= 60) {
						// 	modelContent += '，考试通过'
						// } else {
						// 	modelContent += '，考试未通过'
						// }
						uni.showModal({
							title: '考试结果',
							content: modelContent,
							showCancel: false,
							confirmText: '确定',
							success: res => {
								if (res.confirm) {
									uni.redirectTo({
										// url: '/pages/application/onlinexxks/my-study?STAGESTUDENTRELATION_ID=' + this.STAGESTUDENTRELATION_ID
										url: '/pages/application/onlinexxks/my-tasks'
									})
								}
							}
						})
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showModal({
							content: err.errMsg,
							showCancel: false
						});
					}
				})
			},
			trimSpace(array) {
				for (var i = 0; i < array.length; i++) {
					if (array[i] == '' || array[i] == null || typeof(array[i]) == 'undefined') {
						array.splice(i, 1)
						i = i - 1
					}
				}
				return array
			},
			BackPage() {
				if (!this.isDisabled) {
					uni.showModal({
						title: '',
						content: '考试已开始，确定要退出考试么？',
						cancelColor: '#000000',
						cancelText: '取消',
						confirmText: '确定',
						success: res => {
							if (res.confirm) {
								if(this.timer) {
									clearInterval(this.timer) // 满足条件时 停止计时
									this.timer = null
									this.seconds = 0
									this.minutes = 0
								}
								uni.redirectTo({
									// url: '/pages/application/onlinexxks/my-tasks'
									url: '/pages/application/onlinexxks/my-study?STAGESTUDENTRELATION_ID=' + this.STAGESTUDENTRELATION_ID
								})
							}
						}
					})
				} else {
					uni.redirectTo({
						url: '/pages/application/onlinexxks/my-study?STAGESTUDENTRELATION_ID=' + this.STAGESTUDENTRELATION_ID
					})
				}
			}
		}
	}
</script>

<style>
	.course {
		background-color: #fff;
	}

	.course-header {
		padding: 20upx;
		border-bottom: 1upx solid #F1F1F1;
		line-height: 1.6;
	}

	.course-name {
		font-weight: bold;
		font-size: 30upx;
	}

	.course-int {
		color: #888;
	}

	.course-obj {
		color: #888;
	}

	.course-aa {
		padding: 0 20upx;
	}

	.course-items {
		border-bottom: 1px dashed #F1F1F1;
		padding: 20upx 0;
	}

	.course-items .course-ask {
		line-height: 1.6;
		font-size: 28upx;
		/* margin-bottom: 10upx; */
	}

	.course-answer {
		padding-left: 40upx;
		margin-top: 20upx;
	}

	.answer-lable {
		display: block;
		margin-bottom: 20upx;
	}

	.answer-lable:last-child {
		margin-bottom: 0;
	}

	.answer-lable radio {
		margin-right: 20upx;
	}
</style>
