<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm" v-slot="{ meta }">
        <questions-page-layout
            ref="questionsPageLayout"
            :isMetaValid="meta.valid"
            :alertFewMoreQuestionsHeader="AlertFewMoreQuestionsHeader"
            :alertFewMoreQuestionsCopy="AlertFewMoreQuestionsCopy"
            v-if="questionsData"
            :questionsData="questionsData"
            validationRules="questions-required"
            v-model="selectedAnswers"
            @forwardButtonAction="forwardButtonAction"
            @back-click="navigateBack"
            :key="currentGlassIndex"
            :index="currentGlassIndex">
            <!-- save progress goes into <slot> on questions-page-layout -->
            <saveProgressModalQuestion
                modalWidgetName="SaveProgressModalWidget"
                pageName="capability-questions"
                v-if="showSaveProgressModal" />
        </questions-page-layout>
    </Form>
</template>

<script>
// Components
import questionsPageLayout from "@/fmg-components/layouts/questions-page-layout/questions-page-layout";
import saveProgressModalQuestion from "@/fmg-components/save-progress-modal-question/save-progress-modal-question";

// Supporting Files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import store from "@/store";
import { storeActions } from "@/constants/store-actions";
import { fmgPageValues } from "@/router/router-constants/fmgPage-values";
import { Form, defineRule } from "vee-validate";
import { required } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";
import vehicleQuestionsMixin from "@/mixins/vehicle-questions-mixin";
import baseMixin from "@/mixins/base-mixin.js";

// DEFINE VALIDATION RULES
defineRule("questions-required", required(errorMessages.OPTION_REQUIRED));

export default {
    name: "capability-questions",
    mixins: [vehicleQuestionsMixin],
    async beforeRouteEnter(to, from, next) {
        // Call APIs
        const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);

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

        const resultMap = await settleAllPromises(promiseResultMap);

        const emailFromStore = store.getters.order.customer.emailAddress;

        // Call the "next" function to complete the transition to this page.
        next(async (vm) => {
            vm.setCmsContent(resultMap.cmsContent);
            vm.showSaveProgressModal = !(emailFromStore?.length > 0);
            if (store.getters.externalParameterState?.isExternalParameter) {
                if (store.getters.externalParameterServiceZip.zipCode) {
                    await baseMixin.methods.dispatchStoreAction(
                        storeActions.SAVE_SERVICE_ZIP_CODE_INFO,
                        {
                            zipCode: store.getters.externalParameterServiceZip.zipCode,
                            state: null,
                            zipCodeCtu: null,
                        },
                        false
                    );
                }
                baseMixin.methods.ResetExternalParamsAndHideModal();
            }
        });
    },
    data() {
        return {
            questionsData: null,
            selectedAnswers: {},
            currentGlassIndex: 0,
            showSaveProgressModal: null,
        };
    },
    computed: {
        AlertFewMoreQuestionsHeader() {
            return this.getCmsContent("AdditionalPartsQuestionsAlert", "HeadlineText");
        },
        AlertFewMoreQuestionsCopy() {
            return this.getCmsContent("AdditionalPartsQuestionsAlert", "BodyText");
        },
        partsOrQuestionsData() {
            return this.$store.getters.pageData(fmgPageValues.CAPABILITY_QUESTIONS)
                .partsOrQuestions;
        },
    },
    mounted() {
        this.getInitialQuestionData();
    },
    methods: {
        arePagePrerequisitesValid() {
            const capabilityQuestionsPageData = store.getters.pageData(
                fmgPageValues.CAPABILITY_QUESTIONS
            );
            return (
                // has capabilityQuestions array and has glassName not null
                capabilityQuestionsPageData?.partsOrQuestions?.some((part) => part?.glassName) &&
                capabilityQuestionsPageData?.partsOrQuestions?.some(
                    (part) => part?.capabilityQuestions?.length > 0
                )
            );
        },
        getInitialQuestionData() {
            // get any questions that were already answered
            const alreadyAnsweredQuestions = store.getters.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.handleCompletedQuestionChainAnswers(newValue, glass.answerKey);
                            }
                        },
                        { deep: true }
                    );

                    return updatedGlass;
                });

            // if no preanswered questions then make sure index starts with the correct value
            this.currentGlassIndex = this.calculateQuestionIndex(
                this.currentGlassIndex,
                this.questionsData
            );
        },
        async forwardButtonAction() {
            const questionAnswersArray = this.questionsData.map((glass) => {
                // get answerResult2 of returned answer
                let selectedAnswerResult2;
                glass.questions.forEach((q) => {
                    const idx = q.answers.findIndex(
                        (a) => a.answerResult === glass.answerData.answerResult
                    );
                    if (idx !== -1) {
                        selectedAnswerResult2 = q.answers[idx].answerResult2;
                    }
                });

                return {
                    glassLocation: glass.glassLocation,
                    glassName: glass.glassName,
                    result: glass.answerData.answerResult,
                    result1: glass.answerData.answerResult,
                    result2: selectedAnswerResult2,
                    answeredQuestions: glass.answerData.answeredQuestions,
                    isSuppressedPart: glass.isSuppressedPart,
                };
            });

            // clear out answerData for future page loads; must occur prior to store save
            this.questionsData.forEach((glass) => {
                glass.answerData = {};
            });

            // save to vuex store as order.damage.capabilityQuestionAnswers (array)
            // used in GET_PART_FROM_CAPABILITY_QUESTION_ANSWER call following this one
            await this.dispatchStoreAction(
                this.storeActions.SAVE_CAPABILITY_QUESTION_ANSWERS,
                questionAnswersArray,
                false
            );

            // get parts from the capabilityQuestionAnswers
            const partsOrQuestions = this.partsOrQuestionsData;
            for (let answer of questionAnswersArray) {
                const partFromCapabilityQuestionAnswer = (
                    await this.dispatchStoreActionWithLogging(
                        this.storeActions.GET_PART_FROM_CAPABILITY_QUESTION_ANSWER,
                        answer.glassLocation,
                        "capability-questions",
                        false
                    )
                ).data;

                partsOrQuestions.find(
                    (partOrQuestion) => partOrQuestion.glassLocation === answer.glassLocation
                ).parts = partFromCapabilityQuestionAnswer;
            }

            this.navigateForward(partsOrQuestions);
        },
    },
    components: {
        Form,
        questionsPageLayout,
        saveProgressModalQuestion,
    },
};
</script>
