<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 store from "@/store";
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();
        // from paypal
        const piaError = getQuerystringParameter(queryStrings.ERROR);
        const token = getQuerystringParameter(queryStrings.TOKEN);
        const payerId = getQuerystringParameter(queryStrings.PAYERID);

        // from credit card
        const subscriptionID = getQuerystringParameter(queryStrings.SUBSCRIPTIONID);

        if (piaError) {
            console.log("Error during payment: " + piaError);
            baseMixin.methods.dispatchStoreAction(
                storeActions.SAVE_PIA_ERROR_CODE,
                piaError,
                false
            );
            this.$router.navigateWithoutSaving(this.navigationScenarios.PIA_ERROR, this.$route);
        } else {
            if (token && payerId) {
                await this.processPaypalResponse();
            } else {
                if (subscriptionID) {
                    await this.processCreditCardResponse(subscriptionID);
                } else {
                    console.log(
                        "Error during payment: " + token + " : " + payerId + " : " + subscriptionID
                    );
                    baseMixin.methods.dispatchStoreAction(
                        storeActions.SAVE_PIA_ERROR_CODE,
                        piaError,
                        false
                    );
                    this.$router.navigateWithoutSaving(
                        this.navigationScenarios.PIA_ERROR,
                        this.$route
                    );
                }
            }
        }
    },
    methods: {
        arePagePrerequisitesValid() {
            return true;
        },
        async processPaypalResponse() {
            baseMixin.methods.dispatchStoreAction(storeActions.SAVE_PIA_ERROR_CODE, null, false);
            baseMixin.methods.dispatchStoreAction(storeActions.SAVE_WORK_ORDER_FLAG, true, false);

            await this.saveAndSubmitWorkOrder();
        },
        async processCreditCardResponse(subscriptionID) {
            baseMixin.methods.dispatchStoreAction(storeActions.SAVE_PIA_ERROR_CODE, null, false);
            baseMixin.methods.dispatchStoreAction(storeActions.SAVE_WORK_ORDER_FLAG, true, false);

            const referralSeqNum = getQuerystringParameter(queryStrings.REFERRAL_SEQ_NUM);
            if (referralSeqNum != store.getters.order.referralSequenceNumber) {
                console.log(
                    "error: unknown ref:" +
                        referralSeqNum +
                        " " +
                        store.getters.order.referralSequenceNumber
                );
                baseMixin.methods.dispatchStoreAction(
                    storeActions.SAVE_PIA_ERROR_CODE,
                    "unknown error",
                    false
                );
                this.$router.navigateWithoutSaving(this.navigationScenarios.PIA_ERROR, this.$route);
            } else {
                const expMonth = getQuerystringParameter(queryStrings.CARD_EXPIRATION_MONTH);
                const expYear = getQuerystringParameter(queryStrings.CARD_EXPIRATION_YEAR);
                const cardType = getQuerystringParameter(queryStrings.CARD_TYPE);
                const billToPostalCode = getQuerystringParameter(queryStrings.BILL_TO_POSTAL_CODE);
                const billToFirstName = getQuerystringParameter(queryStrings.BILL_TO_FIRST_NAME);
                const billToLastName = getQuerystringParameter(queryStrings.BILL_TO_LAST_NAME);
                const referenceNumber = getQuerystringParameter(queryStrings.REFERENCE_NUMBER);
                const authCode = getQuerystringParameter(queryStrings.AUTH_CODE);
                const transactionId = getQuerystringParameter(queryStrings.TRANSACTION_ID);
                const transReferenceNumber = getQuerystringParameter(
                    queryStrings.TRANS_REFERENCE_NUMBER
                );

                var ccToken = {
                    subscriptionId: subscriptionID,
                    expMonth: expMonth,
                    expYear: expYear,
                    cardType: cardType,
                    billToPostalCode: billToPostalCode,
                    billToFirstName: billToFirstName,
                    billToLastName: billToLastName,
                    referenceNumber: referenceNumber,
                    authCode: authCode,
                    transactionId: transactionId,
                    transReferenceNumber: transReferenceNumber,
                };
                baseMixin.methods.dispatchStoreAction(storeActions.SAVE_CCTOKEN, ccToken, false);
                await this.saveAndSubmitWorkOrder();
            }
        },
        async saveAndSubmitWorkOrder() {
            // 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);
        },
        forwardButtonAction() {
            this.$router.navigateWithoutSaving(this.navigationScenarios.PIA_SUCCESS, this.$route);
        },
    },
    components: {
        loadingModal,
        Form,
    },
};
</script>

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