<template>
	<div class="app-contain">
		<a-row class="do-exam-title">
			<a-col :span="24">
				<span v-for="item in answer.answerItems" :key="item.itemOrder">
					<a-tag
						:color="questionCompleted(item.completed)"
						class="do-exam-title-tag"
						@click="goAnchor(`#question-${item.itemOrder}`)"
					>
						{{ item.itemOrder }}
					</a-tag>
				</span>
				<span class="do-exam-time">
					<label>剩余时间：</label>
					<label>{{ formatSeconds(remainTime) }}</label>
				</span>
			</a-col>
		</a-row>
		<a-row class="do-exam-title-hidden">
			<a-col :span="24">
				<span v-for="item in answer.answerItems" :key="item.itemOrder">
					<a-tag class="do-exam-title-tag">{{ item.itemOrder }}</a-tag>
				</span>
				<span class="do-exam-time">
					<label>剩余时间：</label>
				</span>
			</a-col>
		</a-row>
		<a-layout class="app-item-contain">
			<a-layout-header class="align-center">
				<h1>{{ form.name }}</h1>
				<div>
					<span class="question-title-padding">试卷总分：{{ form.score }}</span>
					<span class="question-title-padding">考试时间：{{ form.suggestTime }}分钟</span>
				</div>
			</a-layout-header>
			<a-layout-content>
				<a-form :model="form" ref="formRef" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }" :loading="formLoading">
					<template v-for="(titleItem, index) in form.titleItems" :key="index">
						<h3 class="question-title">{{ titleItem.name }}</h3>
						<a-card class="exampaper-item-box" v-if="titleItem.questionItems && titleItem.questionItems.length">
							<a-form-item
								v-for="questionItem in titleItem.questionItems"
								:key="questionItem.itemOrder"
								:label="`${questionItem.itemOrder}.`"
								class="exam-question-item"
								:id="`question-${questionItem.itemOrder}`"
								:label-col="{ span: 0 }"
								:wrapper-col="{ span: 24 }"
								:colon="false"
							>
								<QuestionEdit
									:qType="questionItem.questionType"
									:question="questionItem"
									:answer="answer.answerItems[questionItem.itemOrder - 1]"
									@update:answerCompleted="answer.answerItems[questionItem.itemOrder - 1].completed = true"
									@update:answerContent="answer.answerItems[questionItem.itemOrder - 1].content = $event"
									@update:answerContentArray="answer.answerItems[questionItem.itemOrder - 1].contentArray = $event"
								/>
							</a-form-item>
						</a-card>
					</template>
					<a-row class="do-align-center">
						<a-button type="primary" @click="submitForm">提交</a-button>
						<a-button style="margin-left: 12px">取消</a-button>
					</a-row>
				</a-form>
			</a-layout-content>
		</a-layout>
	</div>
</template>

<script setup>
	import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
	import { useRoute, useRouter } from 'vue-router'
	import { useExamStore } from '@/store/exam'
	import { formatSeconds } from '@/utils/exam'
	import QuestionEdit from '../components/QuestionEdit.vue'
	import examPaperApi from '@/api/student/examPaper'
	import examPaperAnswerApi from '@/api/student/examPaperAnswer'
	import { Modal } from 'ant-design-vue'
	import '../../style.less'
	const route = useRoute()
	const router = useRouter()
	const examStore = useExamStore()

	const form = reactive({})
	const formLoading = ref(false)
	const answer = reactive({
		questionId: null,
		doTime: 0,
		answerItems: []
	})
	const timer = ref(null)
	const remainTime = ref(0)
	const formRef = ref()

	function questionCompleted(completed) {
		// doCompletedTag: [{ key: false, value: 'info' }, { key: true, value: 'success' }]
		return examStore.enumFormat(examStore.exam.question.answer.doCompletedTag, completed)
	}

	function goAnchor(selector) {
		const el = document.querySelector(selector)
		if (el) {
			el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'nearest' })
		}
	}

	function initAnswer() {
		answer.id = form.id
		answer.answerItems = []
		const titleItemArray = form.titleItems || []
		for (const tItem of titleItemArray) {
			const questionArray = tItem.questionItems || []
			for (const question of questionArray) {
				answer.answerItems.push({
					questionId: question.id,
					content: null,
					contentArray: [],
					completed: false,
					itemOrder: question.itemOrder
				})
			}
		}
	}

	function timeReduce() {
		timer.value = setInterval(() => {
			if (remainTime.value <= 0) {
				submitForm()
			} else {
				answer.doTime++
				remainTime.value--
			}
		}, 1000)
	}

	function submitForm() {
		clearInterval(timer.value)
		formLoading.value = true
		examPaperAnswerApi
			.answerSubmit(answer)
			.then((re) => {
				Modal.success({
					title: '考试结果',
					content: `试卷得分：${re}分`,
					okText: '返回考试记录',
					onOk: () => {
						router.push('/student/record/')
					}
				})
				formLoading.value = false
			})
			.catch(() => {
				formLoading.value = false
			})
	}

	onMounted(() => {
		const id = route.query.id
		if (id && parseInt(id) !== 0) {
			formLoading.value = true
			examPaperApi.select(id).then((re) => {
				Object.assign(form, re)
				remainTime.value = re.suggestTime * 60
				initAnswer()
				timeReduce()
				formLoading.value = false
			})
		}
	})

	onBeforeUnmount(() => {
		clearInterval(timer.value)
	})
</script>
