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

398 lines
14 KiB
Vue

<template>
<v-row class="pt-2 mx-1 flex-column fill-height flex-grow-0">
<CreatedVote v-if="isVoteCreated">
<v-btn class="mt-4" color="teal-darken-4" @click="resetForm">Создать ещё</v-btn>
</CreatedVote>
<template v-else>
<div class="v-col flex-grow-1 flex-shrink-0">
<v-stepper v-model="step" class="d-flex flex-column fill-height" editable>
<v-stepper-header class="flex-grow-0 flex-shrink-1">
<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 class="fill-height">
<!-- Основная информация -->
<v-stepper-window-item class="fill-height" step="1">
<MainInfo v-model:form="form" :rules="rules">
<v-card-actions>
<v-btn color="teal-darken-4" size="medium" @click="step = 1">Далее</v-btn>
</v-card-actions>
</MainInfo>
</v-stepper-window-item>
<!-- Создание опроса -->
<v-stepper-window-item class="fill-height" step="2">
<v-card class="fill-height d-flex flex-column" flat>
<v-card-title>Создание опроса:</v-card-title>
<v-card-text style="max-height: 62vh; overflow-y: auto">
<NewQuestion
:form="form"
:rules="rules"
:quests="quests"
@update:form="val => form.value = val"
:allEmployees="allEmployees"
:allEmployeesgroupedbydep="allEmployeesgroupedbydep"
:handleSelectAll="handleSelectAll"
:onEmployeesChange="onEmployeesChange"
:findEmployeeById="findEmployeeById"
:onlyDepdict="onlyDepdict"
/>
<v-divider class="ma-2 pa-1"></v-divider>
<div class="d-flex justify-center">
<v-btn color="orange-darken-4" size="small" @click="addQuestion"
>Добавить вопрос
</v-btn
>
</div>
</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 class="fill-height" step="3">
<v-card class="fill-height d-flex flex-column" flat>
<v-card-title>Подтверждение</v-card-title>
<v-card-text style="max-height: 62vh; overflow-y: auto">
<v-alert v-if="errorMessage" class="mb-4" type="error">
{{ errorMessage }}
</v-alert>
<p>
<v-icon
:class="form.title === null || form.title.length === 0 ? '' : 'opacity-0'"
color="red"
icon="mdi-alert"
size="xsmall"
/>
<strong class="px-2">Название:</strong> {{ form.title }}
</p>
<p>
<v-icon
:class="
form.description === null || form.description.length === 0
? ''
: 'opacity-0'
"
color="red"
icon="mdi-alert"
size="xsmall"
/>
<strong class="px-2">Описание:</strong> {{ form.description }}
</p>
<p>
<strong class="px-2">Дата начала:</strong>
{{ form.startDate.toLocaleDateString() }}
</p>
<p>
<strong class="px-2">Дата окончания:</strong>
{{ form.endDate.toLocaleDateString() }}
</p>
<p><strong class="px-2">Вопросы:</strong></p>
<v-card
v-for="(question, index) in form.questions"
:key="index"
class="mb-4 pa-3"
>
<div class="pa-2">
<p>
<strong>Вопрос {{ index + 1 }}:</strong> {{ question.text }} ({{
question.type
}})
</p>
<div v-if="question.settings.choice === 'free' && 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.choice === 'employee' && question.answers.length"
>
<div>
Количество допустимых ответов: {{ question.settings.multiChoice }}
</div>
<div class="">
Голосование по отделам:
{{ onlyDepdict.find((e) => e.value === question.settings.onlyDep).name }}
</div>
<p><strong>Выбранные сотрудники:</strong></p>
<ul>
<li v-for="employeeId in question.answers" :key="employeeId">
{{ findEmployeeById(employeeId.text).fio }}
</li>
</ul>
</div>
</div>
</v-card>
</v-card-text>
<v-card-actions>
<v-btn color="teal-darken-4" size="medium" @click="step -= 1">Назад</v-btn>
<v-btn
:disabled="errorMessage !== ''"
color="teal-darken-4"
size="medium"
@click="saveVoting"
>
Сохранить
</v-btn>
</v-card-actions>
</v-card>
</v-stepper-window-item>
</v-stepper-window>
</v-stepper>
</div>
</template>
</v-row>
</template>
<script>
import { computed, ref, watch } from 'vue';
import { createVote, getEmployees } from '@/utils/axios-api';
import DateSelect from '@/components/UI/date-select.vue';
import MainInfo from '@/components/vote/ConstructorVote/MainInfo.vue';
import CreatedVote from '@/components/vote/ConstructorVote/CreatedVote.vue';
import NewQuestion from '@/components/vote/ConstructorVote/NewQuestion.vue';
export default {
components: { NewQuestion, CreatedVote, MainInfo, DateSelect },
emits: ['updating'],
setup(props, { emit }) {
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: [],
createnews: false,
appoint: false
});
const rules = {
required: (value) => !!value || 'Это поле обязательно для заполнения',
};
const currentQuestionIndex = ref(0);
const groupedEmployees = ref([]);
const allEmployees = computed(() => [...groupedEmployees.value]);
getEmployees().then((r) => (groupedEmployees.value = r));
const currentQuestion = computed(
() => form.value.questions[currentQuestionIndex.value] || null,
);
const allEmployeesgroupedbydep = computed(() => {
let groupped = [];
for (let x of allEmployees.value.sort(
(a, b) => a.id_dict_department - b.id_dict_department,
)) {
if (!groupped.includes(x.department)) groupped.push(x.department);
groupped.push(x);
}
return groupped;
});
const findEmployeeById = (id) =>
groupedEmployees.value.find((employee) => employee.id === id) || {};
const handleSelectAll = (selected, index) => {
if (!selected) {
form.value.questions[index].answers = groupedEmployees.value.map((employee) => ({
text: employee.id,
image: null,
}));
form.value.questions[index].selectedEmployees = groupedEmployees.value.map(
(employee) => employee.id,
);
} else {
form.value.questions[index].answers = [];
form.value.questions[index].selectedEmployees = [];
}
};
const isAllSelected = computed(
() => currentQuestion.value.answers.length === groupedEmployees.value.length,
);
const addQuestion = () => {
form.value.questions.push({
text: '',
settings: { choice: 'free', multiChoice: 1, onlyDep: null },
image: null,
answers: [],
selectedEmployees: [],
});
currentQuestionIndex.value = form.value.questions.length - 1;
};
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 = (index) => {
if (currentQuestion.value) {
form.value.questions[index].answers.push({ text: '', image: null });
}
};
const removeAnswer = (index, ind) => {
form.value.questions[index].answers.splice(ind, 1);
};
const errorMessage = ref('');
const validateAnswers = () => {
return form.value.questions.some((question) => {
if (question.settings.choice === 'free') {
return question.answers.some((answer) => !answer.text || answer.text.trim() === '');
}
return false;
});
};
const saveVoting = async () => {
const hasEmptyQuestions = quests.value.includes(false);
const hasInvalidAnswers = validateAnswers();
if (
!form.value.title ||
!form.value.description ||
form.value.questions.length < 1 ||
hasEmptyQuestions ||
hasInvalidAnswers
) {
errorMessage.value = 'Все обязательные поля и ответы должны быть заполнены';
return;
}
try {
await createVote(form.value);
isVoteCreated.value = true;
emit('updating', 'active');
} catch (error) {
return new 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;
};
watch(
form.value,
() => {
if (!form.value.title || !form.value.description || form.value.questions.length < 1) {
errorMessage.value = 'Все обязательные поля должны быть заполнены';
} else {
errorMessage.value = '';
}
},
{ deep: true },
);
watch(
() => form.value.questions,
(newQuestions) => {
quests.value = newQuestions.map((q) => !!q.text.trim());
// Проверяем, есть ли пустые вопросы или невалидные ответы
const hasEmptyQuestions = newQuestions.some((q) => !q.text || q.text.trim() === '');
const hasInvalidAnswers = validateAnswers();
errorMessage.value =
hasEmptyQuestions || hasInvalidAnswers
? 'Все вопросы и ответы должны быть заполнены'
: '';
},
{ deep: true },
);
const onEmployeesChange = (selected, index) => {
let ind = form.value.questions[index].selectedEmployees.findIndex((e) => e === selected);
if (ind > -1) {
form.value.questions[index].selectedEmployees.splice(ind, 1);
let answ = form.value.questions[index].answers.findIndex((a) => a.text === selected);
form.value.questions[index].answers.splice(answ, 1);
} else {
form.value.questions[index].selectedEmployees.push(selected);
form.value.questions[index].answers.push({ text: selected, image: null });
}
};
const onlyDepdict = [
{ name: 'За любого сотрудника', value: null },
{
name: 'Кроме своего отдела',
value: false,
},
{ name: 'Только за свой отдел', value: true },
];
const quests = computed(() => form.value.questions.map((question) => question.text.length > 0));
return {
quests,
onlyDepdict,
allEmployeesgroupedbydep,
onEmployeesChange,
step,
form,
addQuestion,
removeQuestion,
addAnswer,
removeAnswer,
findEmployeeById,
saveVoting,
isVoteCreated,
resetForm,
rules,
errorMessage,
allEmployees,
handleSelectAll,
isAllSelected,
};
},
};
</script>
<style>
.v-input--horizontal .v-input__prepend {
margin-inline-end: 4px;
}
.list-enter-active,
.list-leave-active {
transition: all 0.5s ease;
}
.list-enter-from,
.list-leave-to {
opacity: 0;
transform: translateX(50px);
}
</style>