<template>
  <b-container fluid class="eshop">
    <div class="summary">
      <div class="container">
        <resume-payment-page-loader v-if="getErrors('FetchSalesDetail') || isLoading('loadingSalesDetails')" />
        <order-page-template
          v-else
          v-bind="customerOrderProps()"
          :show-continue-button="false"
          :show-promo-code="false"
        >
          <div slot="items">
            <template v-if="getOrderItemsTable">
              <div v-html="getOrderItemsTable"></div>
            </template>
            <order-payment
              v-if="pageReady"
              class="order-payment"
              :on-payment="navigateNext"
              :create-sales="setSalesId"
              :balance="getOrderTotalPrice"
              :check-epp-payments="isEppPayment"
              :cross-domain="isCrossDomainPayment"
              :show-on-hold-payment-options="false"
            />
          </div>
        </order-page-template>
      </div>
    </div>
  </b-container>
</template>

<script>
import Helpers from '@/helpers'
import { mapActions, mapGetters } from 'vuex'
import orderCommonsMixin from '@/app/_global/mixins/orderCommonsMixin'
import OrderPayment from '@/app/_global/components/blocks/OrderPayment'
import OrderPageTemplate from '@/app/_global/components/templates/OrderPageTemplate'
import ResumePaymentPageLoader from '@@@@/app/payment/components/elements/ResumePaymentPageLoader'

export default {
  name: 'OrderSummaryPage',
  components: { ResumePaymentPageLoader, OrderPayment, OrderPageTemplate },
  mixins: [orderCommonsMixin],
  props: {
    id: { type: String, default: null },
  },
  data() {
    return {
      pageReady: false,
    }
  },
  async mounted() {
    await this.loadSalesDetails()
  },
  computed: {
    ...mapGetters(['getCountryById', 'isLoading', 'getErrors']),
    ...mapGetters('3rdPartyPayment', ['getResumePaymentDetails', 'getSalesCountryId']),
    getOrderItemsTable() {
      return Helpers.getValue(this.getResumePaymentDetails, 'resume_payment_html')
    },
    getOrderTotalPrice() {
      return parseFloat(Helpers.getValue(this.getResumePaymentDetails, 'sales_data.order_fees.total_gmp', 0))
    },
    isEppPayment() {
      return Helpers.getValue(this.getResumePaymentDetails, 'order_fees.is_epp_moto_payment')
    },
    isCrossDomainPayment() {
      return this.$appSettings.payment.cross_domain
    },
  },
  methods: {
    ...mapActions('3rdPartyPayment', ['retrieveSalesDetails']),
    async loadSalesDetails() {
      let payload = { salesId: this.id, signature: this.$route.query.signature }
      await this.retrieveSalesDetails(payload).then(() => {
        this.setOrderSummaryDetails()
        this.pageReady = true
      })
    },
    customerOrderProps() {
      return {
        showItemImage: false,
        showItemCv: false,
        orderItem: [],
        showNoteForFocPwpItems: false,
        currencySymbol:
          (this.getSalesCountryId &&
            Helpers.getValue(this.getCountryById(this.getSalesCountryId), 'currency.code', '-')) ||
          '-',
        continueText: this.$t('Common.Continue'),
        summaryCount: this.summaryCount,
        summaryAmount: this.summaryAmount,
        grandTotal: this.getOrderTotalPrice,
      }
    },
    setOrderSummaryDetails() {
      let temp = {}
      let salesData = Helpers.getValue(this.getResumePaymentDetails, 'sales_data', {})
      temp['totalNmpFormatted'] = this.currencyFormatter(Helpers.getValue(salesData, 'order_fees.total_nmp', 0))
      temp['totalAdminFeeFormatted'] = Helpers.getValue(salesData, 'order_fees.admin_fee', 0)
      temp['totalDeliveryFeeFormatted'] = this.currencyFormatter(
        Helpers.getValue(salesData, 'order_fees.delivery_fee', 0)
      )
      temp['totalTaxFormatted'] = this.currencyFormatter(Helpers.getValue(salesData, 'order_fees.tax_amount', 0))
      temp['totalPriceRoundingAdjustmentFormatted'] = this.currencyFormatter(
        Helpers.getValue(salesData, 'order_fees.rounding_adjustment', 0)
      )
      temp['totalItems'] = this.getTotalItemQuantity(salesData)
      temp['totalBv'] = Helpers.getValue(salesData, 'cvs.total_cv', 0)
      this.orderSummaryDetails = temp
    },
    getTotalItemQuantity(salesData) {
      let quantity = 0
      let items = [
        ...Helpers.getValue(salesData, 'products', []),
        ...Helpers.getValue(salesData, 'kittings', []),
        ...Helpers.getValue(salesData, 'selected.promotions', []),
      ]

      items.forEach(item => {
        if (item !== undefined && item.quantity) {
          quantity += Number(item.quantity)
        }
      })

      return quantity
    },
    navigateNext() {
      this.$router.push({ name: 'OrderComplete', params: { id: this.id }, query: this.$route.query })
    },
    setSalesId(paymentMode) {
      paymentMode.sale_id = parseInt(this.id)
      return Promise.resolve(paymentMode)
    },
    currencyFormatter(value) {
      return Helpers.getCurrencyValue(value)
    },
  },
}
</script>
