<template>
    <Form
        ref="theForm"
        v-slot="{ meta }"
        @submit="onSubmit"
        @invalidSubmit="onInvalidSubmit">
        <questionsPageLayout
            ref="questionsPageLayout"
            v-model="selectedAnswers"
            isRequired
            :isMetaValid="meta.valid"
            :questionsData="questionsData"
            :validationRules="rules.optionRequired"
            :index="currentGlassIndex"
            @forwardButtonAction="forwardButtonAction"
            @backClick="navigateBackByVehicleQuestions"
            @needHelpClick="requestCallbackBailout" />
    </Form>
</template>
<script>
// Import Supporting Files
import { fetchCmsContentForPage } from '@/helpers/cms-content-helper';
import settleAllPromises from '@/helpers/layout-helper';

// Import Component
import baseFormMixin from '@/mixins/base-form-mixin';
import issPageValues from '@/router/router-constants/issPage-values';
import { Form } from 'vee-validate';
import { useMainStore } from '@/store';
import globalRules from '@/constants/global-rules';
import vehicleQuestionsMixin from '@/mixins/vehicle-questions-mixin';
import questionsPageLayout from '@/iss-components/questions-page-layout/questions-page-layout.vue';
import bailoutMessage from '@/constants/bailoutMessage';
import navigationScenarios from '@/router/router-constants/navigation-scenarios';

export default {
    name: 'capability-questions',
    components: {
        Form,
        questionsPageLayout
    },
    mixins: [baseFormMixin, vehicleQuestionsMixin],
    async beforeRouteEnter(to, from, next) {
        const cmsContentPromise = fetchCmsContentForPage(to.query.issPage);

        // Settle promises and get results
        const promiseResultMap = [
            {
                resultKey: 'cmsContent',
                promise: cmsContentPromise
            }
        ];

        const resultMap = await settleAllPromises(promiseResultMap);

        next((vm) => {
            vm.setCmsContent(resultMap.cmsContent);
        });
    },
    data() {
        return {
            questionsData: [],
            selectedAnswers: {},
            currentGlassIndex: 0,
            rules: {
                optionRequired: globalRules.OPTION_REQUIRED
            }
        };
    },
    computed: {
        partsOrQuestionsData() {
            return useMainStore().pageData(issPageValues.CAPABILITY_QUESTIONS)
                .partsOrQuestions;
        }
    },
    mounted() {
        this.getInitialQuestionData();
    },
    methods: {
        arePagePrerequisitesValid() {
            const capabilityQuestionsFromPageData = useMainStore().pageData(issPageValues.CAPABILITY_QUESTIONS);
            return (
                capabilityQuestionsFromPageData?.partsOrQuestions?.some((part) => part?.glassName)
                && capabilityQuestionsFromPageData?.partsOrQuestions?.some((part) => part?.capabilityQuestions?.length > 0)
            );
        },
        getInitialQuestionData() {
            // get any questions that were already answered
            const alreadyAnsweredQuestions =
                useMainStore().damage.capabilityQuestionAnswers;
            this.questionsData = this.partsOrQuestionsData
                .filter((x) => x.capabilityQuestions)
                .map((glass, index) => {
                    // NOTE: questions for property "questions" can differ between layouts
                    glass.questions = glass.capabilityQuestions;
                    glass.answerKey = `${glass.glassLocation}-${glass.glassName}`;
                    // reset selectedAnswers for this glass
                    this.selectedAnswers[glass.answerKey] = [];
                    const updatedGlass = this.setupInitialData(
                        glass,
                        index,
                        alreadyAnsweredQuestions
                    );
                    // Set up watch for each set of glass questions
                    this.$watch(
                        `selectedAnswers.${glass.answerKey}`,
                        (newValue) => {
                            if (newValue && Object.keys(newValue).length > 0) {
                                this.handleAnswerUpdates(
                                    newValue,
                                    glass.answerKey
                                );
                            }
                        },
                        { deep: true }
                    );
                    return updatedGlass;
                });
        },
        async forwardButtonAction() {
            const questionAnswersArray = this.questionsData.map((glass) => {
                const { glassLocation, glassName, isSuppressedPart, answerData, questions } = glass;
                const { answerResult, answeredQuestions } = answerData
                return {
                    glassLocation,
                    glassName,
                    result: answerResult,
                    result1: answerResult,
                    result2: questions
                        .flatMap(q => q.answers)
                        .find(a => a.answerResult === answerData.answerResult)?.answerResult2,
                    answeredQuestions,
                    isSuppressedPart
                };
            });
            // clear out answerData for future page loads; must occur prior to store save
            this.questionsData.forEach((glass) => {
                glass.answerData = {};
            });
            // save to store as order.damage.moldingQuestionArrays (array)
            await this.mainStore.saveCapabilityQuestionAnswers(questionAnswersArray);

            // set recalibration properties of parts based on capability question answers
            const promiseResultMap = questionAnswersArray.map((answer, i) => {
                const partData = this.partsOrQuestionsData.find(x => x.glassLocation === answer.glassLocation);
                return {
                    resultKey: i,
                    promise: useMainStore().updatePartFromCapabilityQuestionAnswer(partData.parts[0], answer)
                };
            });
            const resultMap = await settleAllPromises(promiseResultMap);
            questionAnswersArray.forEach((answer, i) => {
                const partData = this.partsOrQuestionsData.find((x) => x.glassLocation === answer.glassLocation);
                partData.parts[0] = resultMap[i];
            });

            this.navigateForward(this.partsOrQuestionsData, null);
        },
        requestCallbackBailout() {
            this.$router.navigateBailout(bailoutMessage.NeedHelp());
        }
    }
};
</script>
