<template>
    <view class="mx-question tabs-swiper-content">
        <mx-question-content ref="q" v-model="userData.answer" :disabled="!allowAnswer" :sys-answer="sysAnswerIf"
                             v-model:attachments="userData.attachments" :question="question" class="p-40"/>
        <mx-question-parse v-if="!allowAnswer" :question="question" class="p-40"/>
    </view>
</template>

<script setup>
import {computed, watch, ref, nextTick} from 'vue'
import {createPropDefine} from "@/utils";
import {useInjectQuestionService} from "@/components/mx-question/useQuestionInjection";
import {useInjectPaperService} from "@/components/mx-paper/usePaperInjection";
import {array} from "@/uni_modules/uv-ui-tools/libs/function/test";
import MxQuestionParse from "@/components/mx-question/components/mx-question-parse.vue";
import {sleep} from "@/uni_modules/uv-ui-tools/libs/function";

const props = defineProps({
    question: createPropDefine({}, Object),
    autoNext: createPropDefine(true, Boolean),
    // 自动随机答题，有时候题太多了，测试不方便，注意随时关闭 !important.
    autoAnswer: createPropDefine(false, Boolean)
})

const q = ref(null)
const {isRadio, tryGoNext, index, current, questions, hasNext, allowAnswer} = useInjectPaperService()
const {getUserData, pushChunk, isAnswered, isScored} = useInjectQuestionService()
const userData = computed(() => getUserData(props.question) || {})
const sysAnswerIf = computed(() => allowAnswer.value ? '' : array(props.question.answers) ? props.question.answers[0] : '')

watch(index, async () => {
    if (!props.autoAnswer) return
    if (isAnswered(current)) return
    await nextTick()
    q.value?.tryRandomAnswer()
}, {immediate: true})

watch([() => userData.value.answer, () => userData.value.attachments], async () => {
    pushChunk(userData.value)
    // 自动前往一下题
    if (props.autoNext && isRadio(props.question) && hasNext.value) {
        const next = questions.value[index.value + 1]
        if (!isAnswered(next)) {
            await sleep(300)
            tryGoNext()
        }
    }
})

watch(() => userData.value.score, async () => {
    pushChunk(userData.value)
    // 自动前往下一题
    if (props.autoNext && hasNext.value) {
        const next = questions.value[index.value + 1]
        if (!isScored(next)) {
            await sleep(300)
            tryGoNext()
        }
    }
})
</script>

<style scoped>

</style>