Files
PORTAL_COD2/src/front/src/components/testing/DetailCardTest.vue
T

347 lines
9.5 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<v-container class="pa-4">
<!-- Верхняя панель -->
<HeaderDetailTesting
:testStarted="testStarted"
:formattedTime="formattedTime"
:finishTest="openFinishDialog"
:currentQuestion="currentQuestion"
:totalQuestions="data?.question_count"
@change-question="changeQuestion"
:data="data"
/>
<!-- Блок информации о тесте -->
<BodyDetailTesting v-if="!testStarted && !testFinished" :data="data" :startTest="startTest" />
<!-- Вопросы теста -->
<QuestionBlock
v-if="testStarted"
:question="data.questions[currentQuestion]"
:currentQuestion="currentQuestion"
:totalQuestions="data.question_count"
:answers="answers"
:finishTest="openFinishDialog"
@change-question="changeQuestion"
/>
<!-- Результаты теста -->
<TestResults
v-if="testFinished"
:testFinished="testFinished"
:testPassed="testPassed"
:correctAnswers="correctAnswers"
:answeredQuestions="answeredQuestions"
:totalQuestions="data.question_count"
:formattedTime="formatSpentTime"
:questions="data?.questions"
:userAnswers="answers"
@restart="startTest"
/>
<!-- Диалог подтверждения завершения теста -->
<v-dialog v-model="showFinishDialog" persistent max-width="400px">
<v-card>
<v-card-title class="text-h6">Завершить тест?</v-card-title>
<v-card-text>Вы уверены, что хотите завершить тестирование?</v-card-text>
<v-card-actions class="d-flex justify-end">
<v-btn variant="tonal" color="teal-darken-4" @click="finishTest">
<v-icon start>mdi-check</v-icon>
Да, завершить
</v-btn>
<v-btn variant="outlined" color="grey" @click="showFinishDialog = false">
<v-icon start>mdi-close</v-icon>
Отмена
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-container>
</template>
<script>
import { computed, ref, onUnmounted, onMounted, watch } from 'vue';
import HeaderDetailTesting from '@/components/testing/HeaderDetailTesting.vue';
import BodyDetailTesting from '@/components/testing/BodyDetailTesting.vue';
import QuestionBlock from '@/components/testing/QuestionBlock.vue';
import TestResults from '@/components/testing/TestResults.vue';
import { axiosApiInstance } from '@/utils/axios-api';
import { useRoute } from 'vue-router';
export default {
components: { BodyDetailTesting, HeaderDetailTesting, QuestionBlock, TestResults },
setup() {
const route = useRoute();
const testId = route.params.id;
const testStarted = ref(false);
const testFinished = ref(false);
const showFinishDialog = ref(false);
const currentQuestion = ref(0);
let timer = null;
const data = ref(null);
const testingId = ref(null);
const testResults = ref(null);
const spentTime = ref(0);
const formatSpentTime = computed(() => {
const minutes = Math.floor(spentTime.value / 60);
const seconds = spentTime.value % 60;
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
});
const getTestById = async (id) => {
const resp = await axiosApiInstance.get(`/api/tests/testdetail/${id}`);
data.value = resp.data;
try {
const testingResp = await axiosApiInstance.get(`/api/tests/testingview/?test_id=${id}`);
const userTestings = testingResp.data;
if (userTestings?.length > 0) {
const testMode = route.query.mode;
const isFormalTesting = testMode === 'exam' || testMode === 'retry';
const sortedTestings = [...userTestings].sort((a, b) => {
return new Date(b.completion_date) - new Date(a.completion_date);
});
const activeTestings = sortedTestings.filter(t =>
isFormalTesting ? !t.completed : true
);
if (activeTestings.length > 0) {
testingId.value = activeTestings[0].id;
} else if (sortedTestings.length > 0) {
testingId.value = sortedTestings[0].id;
}
}
} catch (error) {
console.error('Error getting testing record:', error);
}
};
const formattedTime = computed(() => {
if (!data.value?.time) return '00:00';
if (!testStarted.value && !testFinished.value) {
return `${String(data.value.time).padStart(2, '0')}:00`;
}
const minutes = Math.floor(data.value.time / 60);
const seconds = data.value.time % 60;
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
});
const startTest = async () => {
await getTestById(testId);
testStarted.value = true;
testFinished.value = false;
answers.value = Array(data.value.questions.length).fill(null);
const initialTime = data.value.time * 60;
data.value = { ...data.value, time: initialTime };
spentTime.value = 0;
if (timer) {
clearInterval(timer);
}
timer = setInterval(() => {
if (data.value?.time > 0) {
data.value = { ...data.value, time: data.value.time - 1 };
spentTime.value += 1;
} else {
finishTest();
}
}, 1000);
};
const finishTest = async () => {
clearInterval(timer);
testStarted.value = false;
testFinished.value = true;
showFinishDialog.value = false;
try {
let answersToSubmit = [];
answers.value.forEach((answer, questionIndex) => {
if (answer === null) return;
const question = data.value.questions[questionIndex];
if (Array.isArray(answer)) {
answer.forEach((answerText) => {
const selectedAnswer = question.answers.find((a) => a.name === answerText);
if (selectedAnswer) {
answersToSubmit.push({ answer: selectedAnswer.id });
}
});
}
else {
const selectedAnswer = question.answers.find((a) => a.name === answer);
if (selectedAnswer) {
answersToSubmit.push({ answer: selectedAnswer.id });
}
}
});
const testMode = route.query.mode;
const isFormalTesting = testMode === 'exam' || testMode === 'retry';
const queryParams = new URLSearchParams();
if (isFormalTesting) {
queryParams.append('status', 'testing');
}
const response = await axiosApiInstance.post(
`/api/tests/testresultview/?${queryParams.toString()}&id=${testId}`,
answersToSubmit,
);
testResults.value = response.data;
} catch (error) {
console.error('Ошибка при отправке результатов теста:', error);
}
};
const answers = ref([]);
watch(data.value?.questions, (newData) => {
if (newData && Array.isArray(newData.questions)) {
answers.value = newData.questions.map(() => null);
}
});
const correctAnswers = computed(
() =>
answers.value.filter((answer, index) => {
const correctAnswerObjs = data?.value.questions[index].answers.filter(
(a) => a.right_wrong,
);
if (!correctAnswerObjs.length) return false;
const correctNames = correctAnswerObjs.map((a) => a.name);
if (Array.isArray(answer)) {
return (
answer.length === correctNames.length &&
answer.every((ans) => correctNames.includes(ans))
);
}
return correctNames.includes(answer);
}).length,
);
const answeredQuestions = computed(
() => answers.value.filter((answer) => answer !== null).length,
);
const testPassed = computed(() => testResults.value?.is_passed ?? false);
const changeQuestion = (newIndex) => {
if (newIndex >= 0 && newIndex < data?.value.questions.length) {
currentQuestion.value = newIndex;
}
};
const openFinishDialog = () => {
showFinishDialog.value = true;
};
onUnmounted(() => {
if (timer) clearInterval(timer);
});
onMounted(() => {
getTestById(testId);
});
return {
testStarted,
testFinished,
formattedTime,
formatSpentTime,
startTest,
finishTest,
answers,
currentQuestion,
changeQuestion,
showFinishDialog,
openFinishDialog,
correctAnswers,
answeredQuestions,
testPassed,
data,
};
},
};
</script>
<style>
.v-container {
background-color: #f5f5f5;
border-radius: 8px;
}
.v-btn {
transition: transform 0.2s;
}
.v-btn:hover {
transform: translateY(-2px);
}
.v-dialog .v-card {
border-radius: 8px;
}
.v-dialog .v-card-title {
background-color: #004d40;
color: white;
padding: 16px;
border-top-left-radius: 8px;
border-top-right-radius: 8px;
}
.v-dialog .v-card-actions {
padding: 16px;
background-color: #f5f5f5;
border-bottom-left-radius: 8px;
border-bottom-right-radius: 8px;
}
:deep(.v-label) {
margin-bottom: 8px;
color: #004d40;
}
:deep(.v-img) {
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.timer {
font-size: 1.2rem;
color: #004d40;
font-weight: bold;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(-20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.question-enter-active {
animation: fadeIn 0.3s ease-out;
}
</style>