<template>
	<view class="ques-details-page">
		<ch-nav-bar :height="66" title="试题详情" :rightWidth="140">
			<block v-slot:right>
				<ch-nav-btn icon="paperplane-filled" iconSize="28" color="#fff" @click.native="print">
					打印
				</ch-nav-btn>
			</block>
		</ch-nav-bar>
		<ch-flex items="center">
			<button class="toggle-btn" type="warn" :disabled="questionId == quesIds[0]" @click="toggleQues(-1)">
				<uni-icons type="arrow-left" size="28" color="#fff"></uni-icons>
			</button>
			<view class="ques-content">
				<view v-html="question.questioncontent"></view>
				<view class="ques-options">
					<view class="option" v-for="item in question.option">
						{{ item.optionnumber }}. <view v-html="item.optioncontent"></view>
					</view>
				</view>
				<view class="answer">
					<text>答案</text>
					<view v-html="question.questionanswer"></view>
				</view>
				<view class="analysis">
					<text>解析</text>
					<view v-html="question.questionexplain"></view>
				</view>
			</view>
			<button class="toggle-btn" type="warn" :disabled="questionId == quesIds[quesIds.length - 1]" @click="toggleQues(1)">
				<uni-icons type="arrow-right" size="28" color="#fff"></uni-icons>
			</button>
		</ch-flex>
	</view>
</template>

<script setup>
import ChFlex from '@/components/ch-flex/ch-flex.vue';
import ChNavBtn from '@/components/ch-nav-btn/ch-nav-btn.vue'
import { onBeforeUnmount, onMounted, reactive, toRefs } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getQuestionInfo } from '@/api/question.js';

const data = reactive({
	question: {},
	questionId: 1,
	quesIds: []
})

const { question, questionId, quesIds } = toRefs(data)

onLoad(option => {
	console.log(option)
	questionId.value = option.id;
})

onMounted(() => {
	const params = {
		questionid: questionId.value
	}
	getQuestionInfo(params).then(info => {
		question.value = info;
	})
	
	uni.getStorage({
		key: 'quesIds',
		success: (res) => {
			res.data && (quesIds.value = JSON.parse(res.data))
		}
	})
})

onBeforeUnmount(() => {
	quesIds.length && uni.removeStorage({
		key: 'quesIds'
	})
})

// 切换试题
function toggleQues(step) {
	const cIndex = quesIds.value.findIndex(id => questionId.value == id)
	console.log(cIndex)
	if (cIndex == -1) return;
	const id = quesIds.value[cIndex + step]
	getQuestionInfo({ questionid: id }).then(info => {
		question.value = info;
		questionId.value = id;
	})
}

function print () {
	uni.setStorage({
		key: 'questions',
		data: JSON.stringify([question.value])
	})
	uni.navigateTo({
		url: '/pages/print/print'
	})
}
</script>

<style lang="scss" scoped>
@import 'quesDetail.scss';
</style>
