<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 loadingModal from "@/fmg-components/loading-modal/loading-modal.vue";
import { Form } from "vee-validate";
import { paymentMethods } from "@/constants/payment-method-constants";
import { routerParams } from "@/router/router-constants/router-params";
import baseMixin from "@/mixins/base-mixin.js";
import {
    getDisplayAmountDue,
    getAmountDue,
    getSubTotal,
    getSalesTax,
} from "@/helpers/pricing-helper.js";
// iframeResizer IS loaded into the page and necessary for the package to
//   to auto scale the iFrame this page is loaded in
// Do not remove despite showing as "unused" CASH-309
import iframeResizer from "@iframe-resizer/child";

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

        if (piaError) {
            console.log("Error during payment: " + piaError);
            const paymentPageNavScenario =
                store.getters.order.payment.piaType === paymentMethods.CREDIT_CARD ||
                store.getters.order.payment.piaType === paymentMethods.APPLE_PAY ||
                store.getters.order.payment.piaType === paymentMethods.AFTERPAY;
            if (paymentPageNavScenario) {
                this.$router.navigateWithoutSaving(
                    this.navigationScenarios.PIA_CC_ERROR,
                    this.$route,
                    {
                        [queryStrings.DISPLAY_PIA_ALERT]: store.getters.order.payment.piaType,
                    }
                );
            } else {
                this.$router.navigateWithoutSaving(
                    this.navigationScenarios.PIA_ERROR,
                    this.$route,
                    {
                        [queryStrings.DISPLAY_PIA_ALERT]: true,
                    }
                );
            }
        } else {
            switch (store.getters.order.payment.piaType) {
                case paymentMethods.CREDIT_CARD:
                case paymentMethods.APPLE_PAY:
                case paymentMethods.AFTERPAY:
                    await this.processCreditCardResponse();
                    break;
                case paymentMethods.PAYPAL:
                    await this.processPaypalResponse();
                    break;
                default: {
                    // If we're here, the payment-method did not get properly set in
                    // payment.vue method handleIFrameContentWindowMessage, we will look and see if
                    // if we can default it to credit card.  The payment method type is most likely still
                    // set to PayNow originally set in payment-method.vue
                    const lastFour = getQuerystringParameter(queryStrings.LAST_FOUR);
                    if (lastFour) {
                        console.log(
                            new Date() + ": Payment method credit card selected by default"
                        );
                        this.dispatchStoreAction(
                            storeActions.SAVE_PAYMENT_METHOD_CHOICE,
                            paymentMethods.CREDIT_CARD,
                            false
                        );
                        await this.processCreditCardResponse();
                    } else {
                        var msg = "Unknown Pia type: " + store.getters.order.payment.piaType;
                        console.log(msg);
                        this.$router.navigateWithoutSaving(
                            this.navigationScenarios.PIA_ERROR,
                            this.$route,
                            {},
                            { [routerParams.DISPLAY_PIA_ALERT]: true }
                        );
                    }
                }
            }
        }
    },
    methods: {
        arePagePrerequisitesValid() {
            return true;
        },
        async processPaypalResponse() {
            const token = getQuerystringParameter(queryStrings.TOKEN);
            const payerId = getQuerystringParameter(queryStrings.PAYERID);

            baseMixin.methods.dispatchStoreAction(storeActions.SAVE_PAYPAL_TOKEN, token, false);
            baseMixin.methods.dispatchStoreAction(
                storeActions.SAVE_NEXTGEN_SETTLED_AMOUNT,
                this.getAmountDue(),
                false
            );

            await this.saveAndSubmitWorkOrder();
        },
        async processCreditCardResponse() {
            const subscriptionID = getQuerystringParameter(queryStrings.SUBSCRIPTIONID);

            const referralSeqNum = getQuerystringParameter(queryStrings.REFERRAL_SEQ_NUM);
            if (referralSeqNum != store.getters.order.referralSequenceNumber) {
                console.log(
                    "error: unknown ref:" +
                        referralSeqNum +
                        " " +
                        store.getters.order.referralSequenceNumber
                );
                this.$router.navigateWithoutSaving(
                    this.navigationScenarios.PIA_ERROR,
                    this.$route,
                    {},
                    { [routerParams.DISPLAY_PIA_ALERT]: true }
                );
            } 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
                );
                const lastFour = getQuerystringParameter(queryStrings.LAST_FOUR);

                var ccToken = {
                    subscriptionId: subscriptionID,
                    expMonth: expMonth,
                    expYear: expYear,
                    cardType: cardType,
                    billToPostalCode: billToPostalCode,
                    billToFirstName: billToFirstName,
                    billToLastName: billToLastName,
                    referenceNumber: referenceNumber,
                    authCode: authCode,
                    transactionId: transactionId,
                    transReferenceNumber: transReferenceNumber,
                    lastFour: lastFour,
                };

                baseMixin.methods.dispatchStoreAction(storeActions.SAVE_CCTOKEN, ccToken, false);
                baseMixin.methods.dispatchStoreAction(
                    storeActions.SAVE_NEXTGEN_SETTLED_AMOUNT,
                    this.getAmountDue(),
                    false
                );
                await this.saveAndSubmitWorkOrder();
            }
        },
        getAmountDue() {
            return getAmountDue(store.getters.order.lineItems);
        },
        async saveAndSubmitWorkOrder() {
            // Final work order submit after returning from PIA.
            await this.dispatchStoreAction(storeActions.RESET_SAVE_SESSION_PROMISE);
            try {
                await submitWorkOrder({
                    pageNameToLog: "payment-pia-return",
                    submitAfterSave: true,
                });
            } catch (error) {
                console.log("error: response from submit work order:" + error.message);
                this.$router.navigateWithoutSaving(
                    this.navigationScenarios.PIA_ERROR,
                    this.$route,
                    {},
                    { [routerParams.DISPLAY_PIA_ALERT]: true }
                );
                this.$refs.loadingModal.isModalVisible = false;
                return;
            }

            this.$refs.loadingModal.isModalVisible = false;
            await baseMixin.methods.dispatchStoreAction(storeActions.CREATE_SUBMITTED_STATE);
            this.$router.navigateWithoutSaving(this.navigationScenarios.PIA_SUCCESS, this.$route);
        },
    },
    components: {
        loadingModal,
        Form,
    },
};
</script>

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