Files
PORTAL_COD2/src/front/src/components/vote/VoteConstructor.vue
T

458 lines
16 KiB
Vue

<template>
<v-container>
<template v-if="isVoteCreated">
<v-card class="text-center pa-8" flat>
<v-icon color="success" size="48">mdi-check-circle</v-icon>
<h2 class="mt-4">Голосование создано!</h2>
<v-btn class="mt-4" color="teal-darken-4" @click="resetForm">Создать ещё</v-btn>
</v-card>
</template>
<template v-else>
<v-stepper v-model="step" editable>
<v-stepper-header>
<v-stepper-item :complete="step > 0" step="1">Основная информация</v-stepper-item>
<v-divider></v-divider>
<v-stepper-item :complete="step > 1" step="2">Создание опроса</v-stepper-item>
<v-divider></v-divider>
<v-stepper-item :complete="step > 2" step="3">Подтверждение</v-stepper-item>
</v-stepper-header>
<v-stepper-window>
<!-- Основная информация -->
<v-stepper-window-item step="1">
<v-card flat>
<v-card-title>Основная информация</v-card-title>
<v-card-text>
<v-text-field
v-model="form.title"
:rules="[rules.required]"
label="Название голосования"
outlined
></v-text-field>
<v-textarea
v-model="form.description"
:rules="[rules.required]"
label="Описание"
outlined
></v-textarea>
<div>
<h6 class="text-h6">Дата начала:</h6>
<date-select :datedefault="form.startDate" @returndate="returnstart" />
<v-select
v-model="selectedTimeStart"
:items="timeOptions"
dense
label="Время начала"
outlined
prepend-icon="mdi-calendar-clock"
/>
</div>
<div>
<h6 class="text-h6">Дата окончания:</h6>
<date-select :datedefault="form.endDate" @returndate="returnend" />
<v-select
v-model="selectedTimeEnd"
:items="timeOptions"
dense
label="Время окончания"
outlined
prepend-icon="mdi-calendar-clock"
/>
</div>
</v-card-text>
<v-card-actions>
<v-btn color="teal-darken-4" size="medium" @click="step = 1">Далее</v-btn>
</v-card-actions>
</v-card>
</v-stepper-window-item>
<!-- Создание опроса -->
<v-stepper-window-item step="2">
<v-card flat>
{{form}}
<v-card-title>Создание опроса</v-card-title>
<v-card-text>
<div v-for="(question, index) in form.questions" :key="index" class="mb-4">
<div class="d-flex">
<v-text-field
v-model="question.text"
:label="'Вопрос ' + (index + 1)"
:rules="[rules.required]"
outlined
></v-text-field>
<v-btn color="error" @click="removeQuestion(index)">
<v-icon>mdi-delete</v-icon>
</v-btn>
</div>
<v-file-input
v-model="question.image"
accept="image/*"
label="Картинка для вопроса"
outlined
></v-file-input>
<v-select
v-model="question.settings.type"
:items="questionTypes"
label="Тип ответа"
outlined
></v-select>
<v-text-field
v-model="question.settings.multiChoice"
:rules="[rules.required && question.settings.multiChoice > 0]"
hide-details="auto"
label="Число возможных ответов"
></v-text-field>
<v-card-text>
<div v-if="question.settings.type === 'Ввести вручную'">
<div
v-for="(answer, index) in question.answers"
:key="index"
class="d-flex align-start mb-4"
>
<v-text-field
v-model="answer.text"
:label="'Ответ ' + (index + 1)"
:rules="[rules.required]"
class="mr-4"
outlined
></v-text-field>
<v-file-input
v-model="answer.image"
accept="image/*"
dense
hide-details
label="Картинка"
outlined
></v-file-input>
<v-btn color="error" @click="removeAnswer(index)">
<v-icon>mdi-delete</v-icon>
</v-btn>
</div>
<v-btn color="teal-darken-4" @click="addAnswer">Добавить ответ</v-btn>
</div>
<div v-else>
<v-autocomplete
clearable
v-model="selectedEmployees"
:items="allEmployees"
item-title="fio"
item-value="id"
label="Выберите сотрудников"
multiple
outlined
:value-comparator="(a, b) => a === b"
@update:model-value="onEmployeesChange"
>
<template #prepend-item>
<v-checkbox
v-model="isAllSelected"
label="Все"
@change="() => handleSelectAll(['all'])"
></v-checkbox>
</template>
</v-autocomplete>
<div
v-for="(person, index) in question.answers"
:key="person"
class="d-flex align-center mb-4"
>
<v-chip>{{ findEmployeeById(person.text)?.fio }}</v-chip>
<v-file-input
v-model="person.image"
accept="image/*"
class="ml-4"
dense
hide-details
label="Картинка"
outlined
></v-file-input>
<v-btn color="error" @click="removeEmployee(index)">
<v-icon>mdi-delete</v-icon>
</v-btn>
</div>
</div>
</v-card-text>
</div>
<v-btn color="teal-darken-4" @click="addQuestion">Добавить вопрос</v-btn>
</v-card-text>
<v-card-actions>
<v-btn color="teal-darken-4" size="medium" @click="step -= 1">Назад</v-btn>
<v-btn color="teal-darken-4" size="medium" @click="step = 2">Далее</v-btn>
</v-card-actions>
</v-card>
</v-stepper-window-item>
<!-- Подтверждение -->
<v-stepper-window-item step="3">
<v-card flat>
<v-card-title>Подтверждение</v-card-title>
<v-card-text>
<p><strong>Название:</strong> {{ form.title }}</p>
<p><strong>Описание:</strong> {{ form.description }}</p>
<p><strong>Дата начала:</strong> {{ form.startDate.toLocaleDateString() }}</p>
<p><strong>Дата окончания:</strong> {{ form.endDate.toLocaleDateString() }}</p>
<p><strong>Вопросы:</strong></p>
<ul>
<li v-for="(question, index) in form.questions" :key="index" class="mb-4">
<p><strong>Вопрос {{ index + 1 }}:</strong> {{ question.text }} ({{ question.type }})</p>
<div v-if="question.settings.type === 'Ввести вручную' && question.answers.length">
<p><strong>Варианты ответов:</strong></p>
<ul>
<li v-for="(answer, answerIndex) in question.answers" :key="answerIndex">
{{ answer.text }}
</li>
</ul>
</div>
<div v-if="question.settings.type === 'Выбрать сотрудника' && question.answers.length">
<p><strong>Выбранные сотрудники:</strong></p>
<ul>
<li
v-for="employeeId in question.answers"
:key="employeeId"
>
{{ findEmployeeById(employeeId.text).fio }}
</li>
</ul>
</div>
</li>
</ul>
</v-card-text>
<v-card-actions>
<v-btn color="teal-darken-4" size="medium" @click="step -= 1">Назад</v-btn>
<v-btn color="teal-darken-4" size="medium" @click="saveVoting">Сохранить</v-btn>
</v-card-actions>
<v-alert v-if="errorMessage" class="mb-4" type="error">
{{ errorMessage }}
</v-alert>
</v-card>
</v-stepper-window-item>
</v-stepper-window>
</v-stepper>
</template>
</v-container>
</template>
<script>
import {computed, ref, watch} from "vue";
import {createVote, getEmployees} from "@/utils/axios-api";
import DateSelect from "@/components/UI/date-select.vue";
import {useAccountStore} from "@/store/AccountStore";
export default {
components: {DateSelect},
emits: ['updating'],
setup(props, {emit}) {
const accountStore = useAccountStore();
const user = accountStore.user;
const step = ref(0);
const isVoteCreated = ref(false);
const form = ref({
title: "",
description: "",
startDate: new Date(),
endDate: new Date(new Date().setDate(new Date().getDate() + 14)),
questions: [],
});
const rules = {
required: (value) => !!value || "Это поле обязательно для заполнения",
};
const currentQuestionIndex = ref(0);
const questionTypes = ["Ввести вручную", "Выбрать сотрудника"];
const groupedEmployees = ref([]);
const allEmployees = computed(() => [
...groupedEmployees.value,
]);
getEmployees()
.then(r => groupedEmployees.value = r)
const currentQuestion = computed(() =>
form.value.questions[currentQuestionIndex.value] || null
);
const findEmployeeById = (id) =>
groupedEmployees.value.find((employee) => employee.id === id) || {};
const removeEmployee = (index) => {
currentQuestion.value.answers.splice(index, 1);
};
const handleSelectAll = (selected) => {
if (selected.includes("all")) {
currentQuestion.value.answers = groupedEmployees.value.map((employee) => ({
text: employee.id,
image: null
}));
} else if (
selected.length === groupedEmployees.value.length &&
!selected.includes("all")
) {
currentQuestion.value.answers = selected.map((id) => ({ text: id, image: null }));
} else {
currentQuestion.value.answers = selected.map((id) => ({ text: id, image: null }));
}
};
const isAllSelected = computed(
() => currentQuestion.value.answers.length === groupedEmployees.value.length);
const addQuestion = () => {
form.value.questions.push({
text: "",
settings: {type: "Ввести вручную", multiChoice: 1},
image: null,
answers: [],
});
};
const removeQuestion = (index) => {
form.value.questions.splice(index, 1);
if (currentQuestionIndex.value >= form.value.questions.length) {
currentQuestionIndex.value = form.value.questions.length - 1;
}
};
const addAnswer = () => {
if (currentQuestion.value) {
currentQuestion.value.answers.push({text: "", image: null});
}
};
const removeAnswer = (index) => {
if (currentQuestion.value) {
currentQuestion.value.answers.splice(index, 1);
}
};
const errorMessage = ref("");
const saveVoting = async () => {
if (!form.value.title || !form.value.description || form.value.questions.length < 1) {
errorMessage.value = "Все обязательные поля должны быть заполнены";
return;
}
try {
const response = await createVote(form.value);
console.log("Голосование успешно создано:", response);
isVoteCreated.value = true;
emit('updating', 'active')
} catch (error) {
console.error("Ошибка при создании голосования:", error);
}
};
const resetForm = () => {
form.value = {
title: "",
description: "",
startDate: new Date(),
endDate: new Date(new Date().setDate(new Date().getDate() + 14)),
questions: [],
};
step.value = 0;
isVoteCreated.value = false;
};
const timeOptions = Array.from({length: 48}, (_, i) => {
const hours = String(Math.floor(i / 2)).padStart(2, "0");
const minutes = i % 2 === 0 ? "00" : "30";
return `${hours}:${minutes}`;
});
const selectedTimeStart = ref(
`${form.value.startDate.getHours().toString().padStart(2, "0")}:${form.value.startDate
.getMinutes()
.toString()
.padStart(2, "0")}`
);
const selectedTimeEnd = ref(
`${form.value.endDate.getHours().toString().padStart(2, "0")}:${form.value.endDate
.getMinutes()
.toString()
.padStart(2, "0")}`
);
watch(form.value, () => {
if (!form.value.title || !form.value.description || form.value.questions < 1) {
errorMessage.value = "Все обязательные поля должны быть заполнены";
} else {
errorMessage.value = "";
}
})
watch(selectedTimeStart, () => {
updateStartDate()
})
watch(selectedTimeEnd, () => {
updateEndDate()
})
const updateStartDate = () => {
const [hours, minutes] = selectedTimeStart.value.split(":").map(Number);
form.value.startDate.setHours(hours, minutes);
};
const updateEndDate = () => {
const [hours, minutes] = selectedTimeEnd.value.split(":").map(Number);
form.value.endDate.setHours(hours, minutes);
};
const returnstart = (dates) => {
form.value.startDate = dates
}
const returnend = (dates) => {
form.value.endDate = dates
}
const selectedEmployees = ref([]);
const onEmployeesChange = (selected) => {
currentQuestion.value.answers = selected.map((id) => ({ text: id, image: null }));
};
return {
selectedEmployees,
onEmployeesChange,
returnend,
returnstart,
step,
form,
questionTypes,
groupedEmployees,
currentQuestionIndex,
currentQuestion,
addQuestion,
removeQuestion,
addAnswer,
removeAnswer,
findEmployeeById,
removeEmployee,
saveVoting,
isVoteCreated,
resetForm,
rules,
errorMessage,
timeOptions,
selectedTimeStart,
selectedTimeEnd,
allEmployees,
handleSelectAll,
isAllSelected
};
},
};
</script>
<style>
.v-input--horizontal .v-input__prepend {
margin-inline-end: 4px;
}
</style>