<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";
import { paymentMethods } from "@/constants/payment-method-constants";

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);
            baseMixin.methods.dispatchStoreAction(
                storeActions.SAVE_PIA_ERROR_CODE,
                piaError,
                false
            );
            this.$router.navigateWithoutSaving(this.navigationScenarios.PIA_ERROR, this.$route);
        } else {
            switch (store.getters.order.payment.piaType) {
                case paymentMethods.CREDIT_CARD:
                case paymentMethods.AFTERPAY:
                    await this.processCreditCardResponse();
                    break;
                case paymentMethods.PAYPAL:
                    await this.processPaypalResponse();
                    break;
                default:
                    var msg = "Unknown Pia type: " + store.getters.order.payment.piaType;
                    console.log(msg);
                    baseMixin.methods.dispatchStoreAction(
                        storeActions.SAVE_PIA_ERROR_CODE,
                        msg,
                        false
                    );
                    this.$router.navigateWithoutSaving(
                        this.navigationScenarios.PIA_ERROR,
                        this.$route
                    );
            }
        }
    },
    methods: {
        arePagePrerequisitesValid() {
            return true;
        },
        async processPaypalResponse() {
            const token = getQuerystringParameter(queryStrings.TOKEN);
            const payerId = getQuerystringParameter(queryStrings.PAYERID);
            baseMixin.methods.dispatchStoreAction(storeActions.SAVE_PIA_ERROR_CODE, null, false);
            baseMixin.methods.dispatchStoreAction(storeActions.SAVE_WORK_ORDER_FLAG, true, false);
            baseMixin.methods.dispatchStoreAction(storeActions.SAVE_PAYPAL_TOKEN, token, false);

            await this.saveAndSubmitWorkOrder();
        },
        async processCreditCardResponse() {
            const subscriptionID = getQuerystringParameter(queryStrings.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>
