<template>
	<view class="examPaper">
		<view class="examPaper_bg">
			<img src="../../../static/img/bg/exam.png">
			<view class="examPaper_header">
				<view class="examPaper_header_name">
					{{examPaper.name || ''}}
				</view>
				<view class="examPaper_header_score">
					(总分:{{examPaper.totalScore || 0}}分)
				</view>
				<u-line-progress :percentage="calcPercent" :showText="false"></u-line-progress>
			</view>
		</view>
		<view class="examPaper_content">
			<view class="examPaper_content_topic">
				<view class="examPaper_content_topic_label"
					:style="examItem[currentIndex]['examItem.questionTypeLabel']==='多选'?'background-color:#F7A64A;':''">
					{{examItem[currentIndex]['examItem.questionTypeLabel'] || ''}}题
				</view>
				<view class="examPaper_content_topic_content">
					{{currentIndex+1}}.{{examItem[currentIndex]['examItem.stem']}}
				</view>
			</view>
			<view class="examPaper_content_checkItem" v-for="(item,index) in examItem[currentIndex].result" :key="index"
				@click="choiceItem(item.id)"
				:style="examItem[currentIndex].choice.has(item.id)?'background-color:#F0F8FF;color:#2E75E6;':''">
				{{String.fromCharCode(65+index)}}.{{item.option}}
			</view>
		</view>
		<view class="detailFoot">
			<button @click="back" v-if="currentIndex === 0">返回</button>
			<button @click="backProblem" v-else>上一题</button>

			<button v-if="currentIndex === (examItem.length - 1)" :disabled="!canSubmit()"
				:style="!canSubmit()?'opacity: .3':''" @click="submitResult">提交</button>
			<button @click="nextProblem" :disabled="!canClickNext()" :style="!canClickNext()?'opacity: .3':''"
				v-else>下一题</button>
		</view>
	</view>
</template>

<script>
	import {
		GetDriverExamItem,
		GetDriverExamItemInfo,
		ReportExamPaperResult,
		userMobileOperation,
		GetDriverExamResult
	} from '../../../api/apiList.js'

		let timeoutId;
	

	
	export default {
		data() {
			return {
				currentIndex: 0,
				id: '',
				examItem: [],
				examPaper: {},
				userInfo: {},
				examTime: '',
				examMinutes: '',
				isSubmit: true

			};
		},
		methods: {
			back() {
				uni.navigateBack()
			},
			nextProblem() {
				this.currentIndex++
				if (this.examItem[this.currentIndex].result.length === 0) {
					this.getDriverExamItemInfo()
				}
			},
			backProblem() {
				this.currentIndex--
			},
			getDriverExamItem() {
				GetDriverExamItem({
					"aux": {
						"id": this.id
					}
				}).then(res => {
					this.examPaper = res.data.data.header
					const examItem = res.data.data.items.rows

					examItem.map((val, index) => {
						this.examItem.push(Object.assign(val, {
							result: [],
							choice: new Set()
						}))
						if (index === 0) {
							this.getDriverExamItemInfo(val['examItem.id'])
						}
					})

				})
			},
			getDriverExamItemInfo(id) {
				GetDriverExamItemInfo({
					"aux": {
						"id": id ? id : this.examItem[this.currentIndex]['examItem.id']
					}
				}).then(res => {
					this.examItem[this.currentIndex]['result'] = res.data.data.items.rows
				})
			},
			choiceItem(itemId) {
				const result = this.examItem[this.currentIndex].result
				if (this.examItem[this.currentIndex]['choice'].has(itemId)) {
					this.examItem[this.currentIndex]['choice'].delete(itemId)
				} else {
					if (this.examItem[this.currentIndex]['examItem.questionTypeLabel'] === '单选') {
						this.examItem[this.currentIndex]['choice'].clear()
						this.examItem[this.currentIndex]['choice'].add(itemId)

					} else {
						this.examItem[this.currentIndex]['choice'].add(itemId)
					}
				}
				this.examItem[this.currentIndex].result = []
				this.$nextTick(() => {
					this.examItem[this.currentIndex].result = result
				})

			},
			canClickNext() {
				if (this.examItem[this.currentIndex]) {
					return this.currentIndex !== (this.examItem.length - 1) && Array.from(this.examItem[this.currentIndex]
						.choice.values()).length !== 0
				}
				return false
			},
			canSubmit() {
				return Array.from(this.examItem[this.currentIndex].choice.values()).length !== 0 && this.isSubmit
			},
			submitResult() {

					clearTimeout(timeoutId);
					
					timeoutId = setTimeout(() => {
						const that = this
						this.isSubmit = false
						this.examMinutes = new Date().getTime() - this.examTime.getTime()
						const result = []
						this.examItem.map(val => {
							result.push({
								"exam_item_id": val["examItem.id"],
								"answer": Array.from(val.choice.values()).join(',')
							})
						})
						ReportExamPaperResult({
							"aux": {
								"answers": result,
								"paperId": this.id,
								"driverTel": this.userInfo.userExt.mobile,
								"driverName": this.userInfo.name,
								"examTime": this.examTime,
								"examMinutes": Math.ceil((new Date().getTime() - new Date(this.examTime).getTime()) /
									1000 / 60)
						
							},
						}).then(res => {
							GetDriverExamResult({
								"args": {
									"pageNum": 1,
									"pageSize": 10000,
									"restrictions": [{
										"field": "examPaper.id",
										"type": "EQ",
										"value": this.id
									}, {
										"field": "driverTel",
										"type": "EQ",
										"value": this.userInfo.userExt.mobile
									}, {
										"field": "driverName",
										"type": "EQ",
										"value": this.userInfo.name
									}]
								},
							}).then(res => {
								const result = {
									examMinutes: res.data.data.datas[0]['examMinutes'],
									passed: res.data.data.datas[0]['passed'],
									watched: res.data.data.datas[0]['watched'],
									isViewAnswers: res.data.data.datas[0]['examPaper.isViewAnswers'],
									isTakeVideo: res.data.data.datas[0]['examPaper.isTakeVideo'],
									examPaperId: res.data.data.datas[0]['examPaper.id'],
									id: res.data.data.datas[0]['id'],
									score: res.data.data.datas[0]['score'],
									examTime: res.data.data.datas[0]['examTime']
								}
								uni.showToast({
									title: '操作成功',
									icon: 'success',
									duration: 3000,
									success() {
										that.isSubmit = true
										uni.redirectTo({
											url: `/subpkg/exam/examResult/examResult?result=${JSON.stringify(result)}`
										})
									}
								})
							})
						})
					}, 500)
				
					
			
			},

			getUserInfo() {
				userMobileOperation('getUserInfo').then(res => {
					const data = res.data.data
					this.userInfo = {
						...data
					}
				})
			}
		},
		onLoad(option) {
			const {
				id,
			} = option
			this.id = id
			this.getDriverExamItem()
			this.getUserInfo()
			this.examTime = new Date()
		},
		computed: {
			calcPercent() {
				return ((this.currentIndex + 1) / this.examItem.length) * 100
			},
		}
	}
</script>

<style lang="scss">
	.examPaper {
		background-color: #FFFFFF;
		min-height: 100vh;

		&_bg {
			position: relative;
			height: 357rpx;
			overflow: hidden;

			image {
				width: 100%;
				height: 650rpx;
			}

		}

		&_header {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			color: #FFFFFF;
			padding: 23rpx;

			&_name {
				margin-top: 73rpx;
				font-size: 40rpx;
				font-weight: bolder;
			}

			&_score {
				margin: 16rpx 0 97rpx 0;
				font-size: 28rpx;
			}
		}

		&_content {
			background-color: #FFFFFF;
			border-top-left-radius: 32rpx;
			border-top-right-radius: 32rpx;
			min-height: 953rpx;
			transform: translateY(-32rpx);
			padding: 0 25rpx;
			padding-top: 48rpx;

			&_topic {
				margin-bottom: 51rpx;

				&_label {
					border-radius: 8rpx;
					padding: 4rpx 24rpx;
					color: #FFFFFF;
					font-size: 28rpx;
					margin-bottom: 24rpx;
					background-color: #66CCCC;
					display: inline-block;
				}

				&_content {
					color: #434343;
					font-size: 32rpx;
					font-weight: bolder;
				}
			}

			&_checkItem {
				height: 93rpx;
				background-color: #FAFAFA;
				margin-bottom: 24rpx;
				border-radius: 8rpx;
				font-size: 32rpx;
				font-weight: bolder;
				padding: 24rpx;
			}
		}

		.detailFoot {
			position: sticky;
			display: flex;
			justify-content: space-between;
			bottom: 0;
			width: 100%;
			padding-bottom: 28rpx;
			background-color: #FAFAFA;
			padding-top: 24rpx;
			z-index: 100;

			button {
				width: 339rpx;
				height: 88rpx;
				line-height: 88rpx;
				border-radius: 44rpx;
				color: #2E75E6;
				padding: 0 24rpx;
				border: 3rpx solid transparent;
				position: relative;
				background-clip: padding-box, border-box;
				background-origin: padding-box, border-box;
				background-image: linear-gradient(90deg, #FAFAFA, #FAFAFA), linear-gradient(90deg, #2E75E6, #5E58EE);

				&:after {
					content: "";
				}

				&:last-child {
					background-image: linear-gradient(90deg, #2E75E6, #5E58EE), linear-gradient(90deg, #2E75E6, #5E58EE);
					color: #FFFFFF;
				}
			}

		}

	}
</style>
