<template>
    <Form @submit="onSubmit" @invalid-submit="onInvalidSubmit" ref="theForm">
        <loadingModal notFullScreen ref="loadingModal" />
    </Form>
</template>

<script>
import { submitWorkOrder } from "@/helpers/heritage-integration/order-helper.js";
import { queryStrings } from "@/constants/query-strings";
import { getQuerystringParameter } from "@/helpers/querystring-helper";
import { storeActions } from "@/constants/store-actions";
import baseMixin from "@/mixins/base-mixin.js";
import loadingModal from "@/fmg-components/loading-modal/loading-modal.vue";
import { Form } from "vee-validate";

export default {
    name: "payment-pia-return",
    async mounted() {
        this.$refs.loadingModal.showModal();
        const piaError = getQuerystringParameter(queryStrings.ERROR);
        const token = getQuerystringParameter(queryStrings.TOKEN);
        const payerId = getQuerystringParameter(queryStrings.PAYERID);

        if (piaError) {
            baseMixin.methods.dispatchStoreAction(
                storeActions.SAVE_PIA_ERROR_CODE,
                piaError,
                false
            );
            this.$router.navigateWithoutSaving(this.navigationScenarios.PIA_ERROR, this.$route);
        } else {
            if (token && payerId) {
                baseMixin.methods.dispatchStoreAction(
                    storeActions.SAVE_PIA_ERROR_CODE,
                    null,
                    false
                );
                baseMixin.methods.dispatchStoreAction(
                    storeActions.SAVE_WORK_ORDER_FLAG,
                    true,
                    false
                );

                // Final work order submit after returning from PIA.
                await this.dispatchStoreAction(storeActions.RESET_SAVE_SESSION_PROMISE);
                await submitWorkOrder({ pageNameToLog: "payment-pia-return" });
                this.$refs.loadingModal.isModalVisible = false;
                this.$router.navigateWithoutSaving(
                    this.navigationScenarios.PIA_SUCCESS,
                    this.$route
                );
            } else {
                baseMixin.methods.dispatchStoreAction(
                    storeActions.SAVE_PIA_ERROR_CODE,
                    piaError,
                    false
                );
                this.$router.navigateWithoutSaving(this.navigationScenarios.PIA_ERROR, this.$route);
            }
        }
    },
    methods: {
        arePagePrerequisitesValid() {
            return true;
        },
        forwardButtonAction() {
            this.$router.navigateWithoutSaving(this.navigationScenarios.PIA_SUCCESS, this.$route);
        },
    },
    components: {
        loadingModal,
        Form,
    },
};
</script>

<style lang="scss">
.confirm {
    visibility: hidden;
}
</style>
