<template>
  <div>
    <b-row>
      <b-col cols="12" lg="8" xl="9">
        <i-token-selected-products-table
          :currency="currency"
          class="bg-white mb-3"
          :selected-items="getRedeemedProductList"
        />

        <order-payment-block
          allow-zero-balance
          :balance="getGrandTotal"
          :on-payment="navigateNext"
          :check-epp-payments="false"
          :create-sales="createRedemption"
          :show-on-hold-payment-options="false"
          :on-hold-payment-options-key="['itoken_on_hold_payment_options']"
          :show-payment-options="isReady && getRedeemedProductList.length > 0"
        />
      </b-col>

      <b-col cols="12" lg="4" xl="3">
        <order-summary v-bind="orderSummaryProps" />
      </b-col>
    </b-row>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import OrderSummary from '@/app/_global/components/blocks/OrderSummary'
import OrderPaymentBlock from '@/app/_global/components/blocks/OrderPayment'
import ITokenOrderCommonMixins from '@/app/i-token/mixins/iTokenOrderCommonMixins'
import ITokenSelectedProductsTable from '@/app/i-token/_global/components/elements/ITokenSelectedProductsTable'

export default {
  name: 'ITokenRedemptionPaymentStep',
  components: { OrderSummary, ITokenSelectedProductsTable, OrderPaymentBlock },
  mixins: [ITokenOrderCommonMixins],
  data() {
    return {
      isReady: false,
    }
  },
  created() {
    this.clearLoadedData('sales')
  },
  async mounted() {
    this.clearPaymentStatus()
    await this.getRedemptionDeliveryFees()
    this.isReady = true
  },
  methods: {
    ...mapActions(['clearLoadedData', 'clearPaymentStatus']),
    ...mapActions('itoken', ['createITokenRedemption']),
    async createRedemption(paymentMode) {
      let payload = {
        voucherId: this.voucherDetails.id,
        items: this.getRedeemedProductList,
        shipping: this.getITokenRedemptionFormDetails.shippingInfo,
      }

      return await this.createITokenRedemption(payload).then(response => {
        if (response) {
          // code below tries to direct modify the initial payload and cause a side effect to the payment function in global component
          // ps: is not a good approach
          // TODO: refactor this issue, but make changes cautiously since it been working for years and watch out the impact
          paymentMode.sale_id = response.sale_id || 0
          return paymentMode
        } else {
          return false
        }
      })
    },
  },
}
</script>
