import { Box, Button, Typography, useTheme } from "@mui/material"; import { useCallback, useMemo, useState } from "react"; import { enqueueSnackbar } from "notistack"; import type { AnyTypedQuizQuestion, QuizQuestionBase } from "../../model/questionTypes/shared"; import { checkEmptyData } from "./tools/checkEmptyData"; import type { QuizQuestionResult } from "@model/questionTypes/result"; import { useQuizViewStore } from "@stores/quizView/store"; import { useQuizData } from "@utils/hooks/useQuizData"; import { useRootContainerSize } from "../../contexts/RootContainerWidthContext"; type FooterProps = { setCurrentQuestion: (step: AnyTypedQuizQuestion) => void; question: AnyTypedQuizQuestion; setShowContactForm: (show: boolean) => void; setShowResultForm: (show: boolean) => void; }; export const Footer = ({ setCurrentQuestion, question, setShowContactForm, setShowResultForm }: FooterProps) => { const theme = useTheme(); const { settings, questions } = useQuizData(); const answers = useQuizViewStore(state => state.answers); const [stepNumber, setStepNumber] = useState(1); const isMobileMini = useRootContainerSize() < 382; const isLinear = !questions.some(({ content }) => content.rule.parentId === "root"); const getNextQuestionId = useCallback(() => { console.log("Смотрим какой вопрос будет дальше. Что у нас сегодня вкусненького? Щя покажу от какого вопроса мы ищем следующий шаг"); console.log(question); console.log("От вот этого /|"); let readyBeNextQuestion = ""; //вопрос обязателен, анализируем ответ и условия ветвления if (answers.length) { const answer = answers.find(({ questionId }) => questionId === question.id); (question as QuizQuestionBase).content.rule.main.forEach(({ next, rules }) => { const longerArray = Math.max( rules[0].answers.length, answer?.answer && Array.isArray(answer?.answer) ? answer?.answer.length : [answer?.answer].length ); for ( let i = 0; i < longerArray; i++ // Цикл по всем эле­мен­там бОльшего массива ) { if (Array.isArray(answer?.answer)) { if (answer?.answer.find((item) => String(item === rules[0].answers[i]))) { readyBeNextQuestion = next; // Ес­ли хоть один эле­мент от­ли­ча­ет­ся, мас­си­вы не рав­ны } return; } if (String(rules[0].answers[i]) === answer?.answer) { readyBeNextQuestion = next; // Ес­ли хоть один эле­мент от­ли­ча­ет­ся, мас­си­вы не рав­ны } } }); if (readyBeNextQuestion) return readyBeNextQuestion; } if (!question.required) {//вопрос не обязателен и не нашли совпадений между ответами и условиями ветвления console.log("вопрос не обязателен ищем дальше"); const defaultQ = question.content.rule.default; if (defaultQ.length > 1 && defaultQ !== " ") return defaultQ; //Вопросы типа страница, ползунок, своё поле для ввода и дата не могут иметь больше 1 ребёнка. Пользователь не может настроить там дефолт //Кинуть на ребёнка надо даже если там нет дефолта if ( (question?.type === "date" || question?.type === "text" || question?.type === "number" || question?.type === "page") && question.content.rule.children.length === 1 ) return question.content.rule.children[0]; } //ничё не нашли, ищем резулт console.log("ничё не нашли, ищем резулт "); return questions.find(q => { console.log('q.type === "result"', q.type === "result"); console.log('q.content.rule.parentId', q.content.rule.parentId); console.log('question.content.id', question.content.id); return q.type === "result" && q.content.rule.parentId === question.content.id; })?.id; }, [answers, questions, question]); const isPreviousButtonDisabled = useMemo(() => { // Логика для аргумента disabled у кнопки "Назад" if (isLinear) { const questionIndex = questions.findIndex(({ id }) => id === question.id); const previousQuestion = questions[questionIndex - 1]; return previousQuestion ? false : true; } else { return question?.content.rule.parentId === "root" ? true : false; } }, [questions, isLinear, question?.content.rule.parentId, question.id]); const isNextButtonDisabled = useMemo(() => { // Логика для аргумента disabled у кнопки "Далее" const answer = answers.find(({ questionId }) => questionId === question.id); if ("required" in question.content && question.content.required && answer) { return false; } if ("required" in question.content && question.content.required && !answer) { return true; } if (isLinear) { return false; } const nextQuestionId = getNextQuestionId(); if (nextQuestionId) { return false; } else { const questionId = question.content.rule.default; const nextQuestion = questions.find(q => q.id === questionId || q.content.id === questionId) || null; if (nextQuestion?.type) { return false; } } }, [answers, getNextQuestionId, isLinear, question.content, question.id]); const showResult = (nextQuestion: QuizQuestionResult) => { if (!nextQuestion) return; const isEmpty = checkEmptyData({ resultData: nextQuestion }); if (nextQuestion) { if (nextQuestion && settings?.cfg.resultInfo.showResultForm === "before") { if (isEmpty) { setShowContactForm(true); //до+пустая = кидать на ФК } else { setShowResultForm(true); //до+заполнена = показать } } if (nextQuestion && settings?.cfg.resultInfo.showResultForm === "after") { if (isEmpty) { setShowContactForm(true); //после+пустая } else { setShowContactForm(true); //после+заполнена = показать ФК } } } }; const followPreviousStep = () => { if (isLinear) { setStepNumber(q => q - 1); const questionIndex = questions.findIndex(({ id }) => id === question.id); const previousQuestion = questions[questionIndex - 1]; if (previousQuestion) { setCurrentQuestion(previousQuestion); } return; } if (question?.content.rule.parentId !== "root") { const questionId = question?.content.rule.parentId; const parent = questions.find(q => q.id === questionId || q.content.id === questionId) || null; if (parent?.type) { setCurrentQuestion(parent); } else { enqueueSnackbar("не могу получить предыдущий вопрос"); } } else { enqueueSnackbar("вы находитесь на первом вопросе"); } }; const followNextStep = () => { if (isLinear) { setStepNumber(q => q + 1); const questionIndex = questions.findIndex(({ id }) => id === question.id); const nextQuestion = questions[questionIndex + 1]; if (nextQuestion && nextQuestion.type !== "result") { setCurrentQuestion(nextQuestion); } else { //@ts-ignore showResult(questions.find(q => q.content.rule.parentId === "line")); } return; } const nextQuestionId = getNextQuestionId(); if (nextQuestionId) { const nextQuestion = questions.find(q => q.id === nextQuestionId || q.content.id === nextQuestionId) || null; if (nextQuestion?.type && nextQuestion.type === "result") { showResult(nextQuestion); } else { //@ts-ignore setCurrentQuestion(nextQuestion); } } else { enqueueSnackbar("не могу получить последующий вопрос"); } }; return ( {/*{mode[settings.cfg.theme] ? (*/} {/* */} {/*):(*/} {/* */} {/*)}*/} {isLinear && Шаг {stepNumber} Из {questions.filter(q => q.type !== "result").length} } {/* Шаг {stepNumber} */} {/* */} {/* Из {questions.length} */} ); };