<template>
  <div>
    <div class="d-flex justify-content-center align-items-center vh-50" v-if="isLoading('esacCountryRelationLoading')">
      <icon class="icon-size-4" name="spinner" pulse />
    </div>
    <keep-alive v-else>
      <component :is="getEsacComponentName" />
    </keep-alive>
  </div>
</template>
<script>
import ProductSelection from './blocks/ProductSelection'
import ReviewAndShipping from './blocks/ReviewAndShipping'
import MakePayment from './blocks/MakePayment'
import OrderCompleted from './blocks/OrderCompleted'
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'EsacVoucherList',
  props: {
    saleId: {
      type: String,
      required: false,
    },
  },
  components: {
    ProductSelection,
    ReviewAndShipping,
    MakePayment,
    OrderCompleted,
  },
  data() {
    return {}
  },
  mounted() {
    let { redirect, cb } = this.$route.query
    let saleId = parseInt(parseFloat(this.saleId)) || null

    if (cb && !redirect) {
      // Catch payment gateway payment fail
      saleId = null
    }

    if (saleId) {
      if (redirect === 'true') {
        this.clickEsacMakePaymentComplete()
      } else {
        // redirect back from external payment gateway
        this.loadEsacCountryRelation({ country_id: this.getEsacCountryId }).then(response => {
          let transactionLocationId = this.getEsacTransactionLocationId
          if (transactionLocationId !== null) {
            this.loadEsacStockLocationByTransactionLocation({ location_id: transactionLocationId }).then(response => {
              this.redirectToEsacMakePaymentScreen({ saleId })
            })
          } else {
            this.redirectToEsacMakePaymentScreen({ saleId })
          }
        })
      }
    } else {
      if (this.getEsacVisibleVoucherCount > 0) {
        this.showProductSelectionScreen()
      } else {
        this.redirectToEsacVoucherListScreen()
      }
    }
  },
  methods: {
    ...mapActions([
      'loadEsacCountryRelation',
      'loadEsacStockLocationByTransactionLocation',
      'showProductSelectionScreen',
      'redirectToEsacVoucherListScreen',
      'redirectToEsacMakePaymentScreen',
      'clickEsacMakePaymentComplete',
    ]),
  },
  computed: {
    ...mapGetters([
      'isLoading',
      'getEsacCountryId',
      'getEsacComponentName',
      'getEsacCountryRelationData',
      'getEsacTransactionLocationId',
      'getEsacVisibleVoucherCount',
      'getEsacTotalVoucherValue',
    ]),
  },
}
</script>
