<template>
  <div>
    <div class="bg-secondary p-2 lifted sticky-top">
      <b-container fluid="lg" class="text-white px-0 py-2">
        <div class="d-flex align-items-center">
          <b-button :to="{ name: 'iToken' }" variant="link" data-qa="iToken-backToITokenCampaignList-btn">
            <icon name="back-arrow" class="icon-size-3 text-white" />
          </b-button>

          <b-img class="ml-2 mr-3 d-none d-md-block icon-size-4" :src="companyLogo" />
          <span class="font-size-5 font-md-size-3">{{ $t('Itoken.Redemption.Title') }}</span>
        </div>
      </b-container>
    </div>

    <div>
      <order-steps-template
        class="eshop"
        :steps="selectedOrder"
        :show-stepper="showStepper"
        :stepper-class="['overflow-hidden']"
        :content-wrapper-class="['container', 'mb-5']"
      >
        <router-view
          :current-route="currentRoute()"
          :voucher-details="voucherDetails"
          :navigate-next="validateAndContinue"
          :navigate-previous="previous"
          ref="routeView"
        />
      </order-steps-template>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { mapActions } from 'vuex'
import OrderStepsTemplate from '@/app/_global/components/templates/OrderStepsTemplate'
import iTokenRedemptionRouteMixins from '@/app/i-token/mixins/iTokenRedemptionRouteMixins'

export default {
  name: 'ITokenRedemptionProcessTemplate',
  components: { OrderStepsTemplate },
  mixins: [iTokenRedemptionRouteMixins],
  props: {
    voucherId: { type: [String, Number], required: true },
  },
  data() {
    return {
      companyLogo: this.$const.constImage.COMPANY_LOGO,
      voucherDetails: {},
    }
  },
  computed: {
    showStepper() {
      return this.$route.meta.showStepper === undefined || this.$route.meta.showStepper
    },
  },
  created() {
    this.$route.query.session === 'active' ? this.loadMemberDetails() : this.clearLoadedData('iToken')
  },
  async mounted() {
    this.loadITokenVoucherDetails(this.voucherId).then(result => {
      if (result) {
        this.voucherDetails = {
          id: result.id,
          campaign_name: this.$helpers.getValue(result, 'campaign.name', ''),
          voucher_no: result.voucher_no,
          voucher_points: result.voucher_point,
          expiry_date: moment(result.expiry_date).format('YYYY-MM-DD'),
          items: this.$helpers.getValue(result, 'campaign.items', []),
          currency_code: this.$helpers.getValue(result, 'campaign.currency.code', ''),
        }
      } else {
        this.$swal({
          type: 'error',
          title: this.$t('Itoken.Redemption.Error.InvalidVoucher'),
        })
        this.$router.replace({ name: 'iToken' })
      }
    })
    await this.initRouting(true)
  },
  methods: {
    ...mapActions(['clearLoadedData', 'loadMemberDetails']),
    ...mapActions('itoken', ['loadITokenVoucherDetails']),
    validateAndContinue(skipRouting = false) {
      // Map validation on component level
      let componentValidationFunction = this.$refs.routeView.validateAndSubmit

      // If cant find the validation method, set default function
      if (typeof componentValidationFunction !== 'function') {
        componentValidationFunction = () => true
      }
      Promise.resolve(componentValidationFunction()).then(valid => {
        if (valid) {
          // Map validation on route mixin level
          let routeValidationFunction = this.currentRoute().validate
          // If cant find the validation method, set default function
          if (typeof routeValidationFunction !== 'function') {
            routeValidationFunction = () => valid
          }
          // If pass move to next route
          return Promise.resolve(routeValidationFunction()).then(valid => {
            if (valid && !skipRouting) {
              this.next()
            }
          })
        }
      })
    },
  },
}
</script>
