<template>
  <div :class="wrapperClasses">
    <b-container :fluid="!wrapperClasses" class="p-sm-d-0" :class="containerClasses">
      <b-row v-if="!hideTitle">
        <b-col class="pb-2">
          <h4 class="mt-sm-d-3 text-medium text-sm-d-center">
            {{ $t('Eshop.Order.OrderConfirmationList.Title') }}
          </h4>
        </b-col>
      </b-row>
      <b-row no-gutters="">
        <b-col class="bg-white p-sm-d-0" :class="[...childContainerClasses, { 'p-4': !wrapperClasses }]">
          <div>
            <div>
              <div class="border-sm-d-bottom mb-sm-d-3">
                <div
                  class="row py-1 text-center text-md-left align-items-end"
                  :class="[
                    {
                      'text-danger':
                        paymentStatus === 0 &&
                        $helpers.getValue(saleDetails, 'order_status', '').toLowerCase() !== 'completed',
                      'text-info-green':
                        paymentStatus === 1 ||
                        paymentStatus === 3 ||
                        (paymentStatus === 2 &&
                          (saleDetails.is_paylater === 1 || saleDetails.is_cash_on_delivery === 1) &&
                          onHoldPaymentCheckOption) ||
                        $helpers.getValue(saleDetails, 'order_status', '').toLowerCase() === 'completed',
                    },
                    paymentMessageHeading,
                  ]"
                >
                  <div class="col-12 col-md-auto align-items-center align-self-center">
                    <div
                      v-if="
                        paymentStatus === 1 ||
                          paymentStatus === 3 ||
                          getCurrentPaymentIsQr ||
                          ((saleDetails.is_paylater === 1 || saleDetails.is_cash_on_delivery === 1) &&
                            onHoldPaymentCheckOption) ||
                          $helpers.getValue(saleDetails, 'order_status', '').toLowerCase() === 'completed'
                      "
                    >
                      <icon name="tick-icon" class="icon-size-md-4 icon-size-5" />
                    </div>
                    <div v-else-if="paymentStatus === 0 || paymentStatus === false">
                      <icon name="remove-icon" class="icon-size-md-4 icon-size-5" />
                    </div>
                    <div v-else ref="lavPending" class="lottie-size-4 mx-auto"></div>
                  </div>
                  <div class="col-12 col-md-auto px-0 align-self-center mt-2 mt-md-0">
                    <div v-if="paymentStatus === 1 && getAppStatus('enrolment')">
                      {{ $t('Common.Congratulation') }}
                    </div>
                    <small>{{ getTransactionStatusMessage }}</small>
                  </div>
                </div>
              </div>

              <b-table head-variant="light" :fields="getTableField" :items="[saleDetails]" stacked="lg">
                <template v-slot:cell(transaction_date)>
                  {{ getTransactionDate }}
                </template>

                <template v-slot:cell(document_number)="row">
                  <b-button
                    v-if="row.item.invoice_id && downloadEsacInvoice"
                    class="p-0"
                    variant="link"
                    @click="downloadDocument"
                  >
                    {{ row.value }}
                  </b-button>
                  <span v-else>{{ row.value || '-' }}</span>
                </template>

                <template v-slot:cell(order_by)>
                  {{ salesUser }}
                </template>

                <template v-slot:cell(payment_method)>
                  {{ getPaymentMethod || '-' }}
                </template>

                <template v-slot:cell(total_bv)="row">
                  <span v-if="$appSettings.evo.enable">{{ $helpers.getValue(row.item, 'cvs.total_bv', '0.00') }}</span>
                  <span v-else>{{ $helpers.getValue(row.item, 'cvs.total_cv', 0) }}</span>
                </template>

                <template v-slot:cell(total_sv)="row">
                  {{ $helpers.getValue(row.item, 'cvs.total_sv', 0) }}
                </template>

                <template v-slot:cell(total_cbp)="row">
                  {{ $helpers.getValue(row.item, 'cvs.total_cbp', '0.0000') }}
                </template>

                <template v-slot:cell(order_fees)="row">
                  {{ currency }}
                  {{ $helpers.getValue(row.value, 'total_gmp', '0.00') }}
                </template>

                <template v-slot:cell(delivery_method)="row">
                  {{ $helpers.getValue(row, 'item.translated_delivery_method.content', row.value) }}
                </template>

                <template v-slot:cell(status)>
                  {{ orderStatus }}
                </template>
              </b-table>
            </div>
          </div>
        </b-col>
      </b-row>

      <b-row v-if="saleDetails.campaign">
        <b-col>
          <div class="border p-3 mb-3">
            <h5 class="mb-3 text-black text-capitalize">
              {{ $helpers.getValue(saleDetails, 'campaign.name', '-') }}
            </h5>

            <b-row v-if="showITokenVoucherNo">
              <b-col cols="12" md="4" lg="3" class="text-md-right">{{ $t('Common.Voucher.VoucherNo') }}</b-col>
              <b-col class="font-weight-bold">
                {{ $helpers.getValue(saleDetails, 'redemption.voucher.voucher_no', '-') }}
              </b-col>
            </b-row>

            <b-row v-if="showITokenTotalPoints">
              <b-col cols="12" md="4" lg="3" class="text-md-right">
                {{ $t('Itoken.Redemption.TotalPointsEarned') }}
              </b-col>
              <b-col class="font-weight-bold">
                {{ $helpers.getValue(saleDetails, 'campaign.calculation.total_point', 0) }}
              </b-col>
            </b-row>

            <b-row>
              <b-col cols="12" md="4" lg="3" class="text-md-right">
                {{ $t('Itoken.Redemption.TotalPointsRedeemed') }}
              </b-col>
              <b-col class="font-weight-bold">
                {{ $helpers.getValue(saleDetails, 'campaign.calculation.selected_point', 0) }}
              </b-col>
            </b-row>

            <b-row v-if="showITokenAccumulatedPoints">
              <b-col cols="12" md="4" lg="3" class="text-md-right">
                {{ $t('Itoken.Redemption.TotalPointsAccumulated') }}
              </b-col>
              <b-col class="font-weight-bold">
                {{ $helpers.getValue(saleDetails, 'campaign.calculation.accumulated_point', 0) }}
              </b-col>
            </b-row>
          </div>
        </b-col>
      </b-row>

      <b-row>
        <b-col>
          <div v-if="orderDetail.collectionCode !== '' || orderDetail.orderForId !== ''" class="border mb-3">
            <div v-if="$helpers.getValue(orderDetail, 'collectionCode', null) !== null" class="bg-white p-3">
              <span class="font-weight-bold">
                {{ $t('Eshop.Order.Completed.CollectionCode') }}
              </span>
              <h5>{{ orderDetail.collectionCode }}</h5>
              <b-row class="collpoint-details">
                <b-col>
                  <b-row>
                    <strong>[ {{ orderDetail.orderForName }} ]</strong>
                  </b-row>
                  <b-row>
                    {{ orderDetail.collectionAddress }}
                  </b-row>
                  <b-row> {{ $t('Eshop.Order.OrderConfirmationList.Tel') }} : {{ orderDetail.collectionTel }} </b-row>
                </b-col>
              </b-row>
              <div class="pt-2">
                {{ $t('Eshop.Order.Completed.PleaseContactStockist') }}
              </div>
            </div>
            <div v-if="orderDetail.orderForId !== ''" class="bg-white mt-3 py-3 px-4">
              <span class="font-weight-bold">
                {{ $t('Eshop.Order.GlobalWords.OrderMadeFor') }}
              </span>
              <b-row>
                <b-col class="col-xl-1">
                  {{ $t('Common.IboId') }}
                </b-col>
                <b-col class="col-xl-4">
                  {{ orderDetail.orderForId }}
                </b-col>
              </b-row>
              <b-row>
                <b-col class="col-xl-1 text-nowrap">
                  {{ $t('Common.IboName') }}
                </b-col>
                <b-col class="col-xl-4">
                  {{ orderDetail.orderForName }}
                </b-col>
              </b-row>
            </div>
          </div>
        </b-col>
      </b-row>
      <b-row>
        <b-col>
          <div
            v-if="typeof getEvouchers !== 'undefined' && getEvouchers.length > 0 && paymentStatus === 1"
            class="mt-3 py-3 px-4 bg-white"
          >
            <span class="h5 text-black">
              {{ $t('Eshop.Order.GlobalWords.EVoucher') }}
            </span>
            <b-row v-for="(voucher, index) in getEvouchers" :key="index" class="py-1">
              <b-col>
                {{ getVoucherDescription(voucher) }}
              </b-col>
            </b-row>
          </div>
        </b-col>
      </b-row>
      <b-row>
        <b-col>
          <div v-if="documentData.length > 0" class="pb-2">
            <div class="row no-gutters mt-3" v-for="(paymentDoc, index) in documentData" :key="`payment-doc-${index}`">
              <div class="col-12 col-lg-9 pt-4 bg-white">
                <div class="font-weight-bold-extra px-3 pb-2">
                  {{ $t('Eshop.Order.Completed.PleaseSubmitDocument') }}
                </div>
                <div class="overflow-x-auto">
                  <table class="table table-sm border-0 border-top m-0 font-size-sm-d-8">
                    <thead>
                      <tr>
                        <th class="align-middle border-right" colspan="2">
                          {{ $t('Eshop.Order.Completed.DocumentTable.Header.Document') }}
                        </th>
                        <th class="align-middle border-right">
                          {{ $t('Eshop.Order.Completed.DocumentTable.Header.Employed') }}
                        </th>
                        <th class="align-middle text-nowrap">
                          {{ $t('Eshop.Order.Completed.DocumentTable.Header.SelfEmployed') }}
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(document, idx) in paymentDoc.list" :key="idx">
                        <td class="align-middle border-right">
                          {{ document.document_title }}
                        </td>
                        <td class="align-middle border-right">
                          {{ document.document_type }}
                        </td>
                        <td class="align-middle border-right text-center" v-if="document.employed === 'Yes'">
                          <icon name="selected-icon" />
                        </td>
                        <td class="align-middle border-right text-center" v-else />
                        <td class="align-middle text-center" v-if="document.self_employed === 'Yes'">
                          <icon name="selected-icon" />
                        </td>
                        <td class="align-middle text-center" v-else />
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              <div class="col col-sm-12 col-md-7 col-lg ml-0 ml-lg-3 pt-4 mt-3 mt-lg-0 w-100 bg-white">
                <div class="px-3 font-weight-bold-extra pb-2">
                  {{ $t('Eshop.Order.Completed.MailingAddress') }}
                </div>
                <div class="border-top">
                  <label class="px-3 py-2" v-html="paymentDoc.address" />
                  <!-- new change -->
                </div>
              </div>
            </div>
          </div>
        </b-col>
      </b-row>
    </b-container>
  </div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import { CurrencyMixin, AddressMixin, PhoneMixin, mapMasterDataId } from '@/app/_global/mixins'
import CircleLoader from '@/elements/lottie/circle_loader.json'
import lottie from 'lottie-web'
import * as L from '@/store/utils/localStorageKeys'
import _ from 'lodash'
import moment from 'moment'

export default {
  name: 'OrderComplete',
  mixins: [CurrencyMixin, AddressMixin, PhoneMixin],
  inject: {
    /**
     * Callback returns sales details getter
     * @callback returnGetterCallback
     * @return vuex/Getter
     */
    /** Sale details
     *
     * Should return the sales details getter
     *
     * @return returnGetterCallback
     */
    _order_complete_get_current_sales_details: {
      default: function() {
        return function() {
          return this.getSalesDetails
        }
      },
    },
    /** User that created the sales, in case of guest the user who creates sales can be overriden
     *
     * Should return the sales details getter
     *
     * @return returnGetterCallback
     */
    _order_complete_get_sales_created_user: {
      default: function() {
        return function() {
          return this.$helpers.getValue(this.getSalesDetails, 'downline_member.name', '-N/A-')
        }
      },
    },
    /** Selected Country
     *
     * Should return the sales details getter
     *
     * @return returnGetterCallback
     */
    _general_selected_country_id: {},
    /** User that created the sales, in case of guest the user who creates sales can be overriden
     *
     * Should return the sales details getter
     *
     * @return returnGetterCallback
     */
    _order_complete_get_sales_create_status: {
      default: function() {
        return this.checkPaymentStatus
      },
    },
    /** User that created the sales, in case of guest the user who creates sales can be overriden
     *
     * Should return the sales details getter
     *
     * @return returnGetterCallback
     */
    _order_complete_message_map: {
      default: function() {
        return function() {
          return new Map([
            [false, this.$t('Eshop.Order.GlobalWords.ThankYouLoading')],
            [0, this.$t('Eshop.Order.GlobalWords.SorryYourPaymentWasNotProcessed')],
            [1, this.$t('Eshop.Order.GlobalWords.ThankYouOrderCompleted')],
            [2, this.$t('Eshop.Order.GlobalWords.ThankYouLoading')],
            [3, this.$t('Eshop.Order.GlobalWords.ThankYouForYourOrder')],
          ])
        }
      },
    },
  },
  props: {
    showPaymentModeDeliveryDetails: {
      type: Boolean,
      default: true,
    },
    hideTitle: {
      type: Boolean,
      default: false,
    },
    wrapperClasses: {
      type: Array,
      default: () => ['p-2'],
    },
    containerClasses: {
      type: Array,
      default: () => [],
    },
    paymentMessageHeading: {
      type: String,
      default: 'h4',
    },
    onHoldPaymentCheckOption: {
      type: Boolean,
      default: true,
    },
    isUseCurrentPaymentMethodOnly: {
      type: Boolean,
      default: false,
    },
    downloadInvoice: {
      type: Boolean,
      default: true,
    },
    childContainerClasses: {
      type: Array,
      default: () => [],
    },
    showITokenTotalPoints: {
      type: Boolean,
      default: false,
    },
    showITokenAccumulatedPoints: {
      type: Boolean,
      default: false,
    },
    showITokenVoucherNo: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      paymentStatus: null,
      statusMap: new Map([
        [false, this.$t('Sales.Payment.Status.Failed')],
        [0, this.$t('Sales.Payment.Status.Failed')],
        [1, this.$t('Sales.Payment.Status.Success')],
        [2, this.$t('Sales.Payment.Status.Pending')],
        [3, this.$t('Sales.Payment.Status.PreOrder')],
        [4, this.$t('Sales.Payment.Status.Qr')],
      ]),
      messageMap: new Map(),
      statusClassMap: new Map([
        [false, 'text-info'],
        [0, 'text-warning'],
        [1, 'text-info-green'],
        [2, 'text-info'],
        [3, 'text-info-green'],
      ]),
      loadingData: false,
      orderDetail: {
        invoiceId: null,
        orderDate: '',
        documentNo: '',
        orderBy: '',
        paymentMethod: '',
        totalCv: '',
        currency: '',
        totalAmount: '',
        shippingMethod: '',
        status: '',
        orderForId: '',
        orderForName: '',
        collectionCode: '',
        collectionAddress: '',
        collectionTel: '',
        eVoucher: [],
        selectedPaymentProviderModeId: 7,
        paymentMethodName: '',
      },
      documentData: [],
    }
  },
  async mounted() {
    this.paymentStatus = 2
    let self = this
    if (this.getCurrentSaleId) {
      let forceLoad = this.$route.query.redirect === 'true'
      await this.loadSalesDetailsData({ saleId: parseInt(this.getCurrentSaleId), forceLoad })
    }
    this.messageMap = this._order_complete_message_map()
    if (typeof window['___payment_status_checker'] !== 'undefined') {
      clearInterval(window['___payment_status_checker'])
    }
    this.loadAnimations()
    await this.getDeliveryDetails()
    /**
     * Payment status checking logic for code block below:
     * 1) If current payment method is QR pay                                                                           --> skip checking and immediately success
     * 2) If `onHoldPaymentCheckOption` is 'true' and 'is_paylater', 'is_cash_on_delivery' either or both 'true'        --> skip checking and immediately success
     * 3) If `onHoldPaymentCheckOption` is 'true' and 'is_paylater', 'is_cash_on_delivery' both are 'false'             --> proceed payment status checks
     * 4) If `onHoldPaymentCheckOption` is 'false' and 'is_paylater', 'is_cash_on_delivery' either or both 'true'       --> proceed payment status checks
     * 5) If `onHoldPaymentCheckOption` is 'false' and 'is_paylater', 'is_cash_on_delivery' both are 'false'            --> proceed payment status checks
     */
    let isPaymentCompleted = self.$helpers.getValue(self.saleDetails, 'order_status', '').toLowerCase() === 'completed'
    if (
      self.getCurrentPaymentIsQr ||
      (self.onHoldPaymentCheckOption &&
        (self.$helpers.getValue(self.saleDetails, 'is_paylater') === 1 ||
          self.$helpers.getValue(self.saleDetails, 'is_cash_on_delivery') === 1)) ||
      isPaymentCompleted
    ) {
      if (isPaymentCompleted) {
        this.paymentStatus = 1
      } else {
        await self.loadCart()
        setTimeout(() => {
          self.$emit('payment-success', true)
        }, 1500)
      }
    } else {
      this.startPaymentStatusChecking()
    }
    //TODO: Caroline - Change this part to mutation clear
    localStorage.removeItem(L.SUPPORTING_DOC_DETAILS)
    localStorage.removeItem(L.NRIC_DOCS_DETAILS)
    localStorage.removeItem(L.BANK_CARD_DETAILS)
    localStorage.removeItem(L.MPAY_DETAILS)
    localStorage.removeItem(L.CARD_RENTAL_DETAILS)
    this.setRentalCardDetails({
      card_type_id: '',
      card_company_id: '',
      card_holder_name: '',
      country_bank_id: '',
      card_number: '',
      card_expiry_date: '',
      credit_card_photocopy: [],
      income_proof: [],
    })
    this.setNRICDocDetails([])
    this.setSupportingDocDetails([])
    this.setBankCardDetails({
      bank_country_name: '',
      bank_account_ic: '',
      account_holder_name: '',
      swift_code: '',
      country_bank_id: '',
      acccount_number: '',
      payout_company: '',
      account_type: '',
    })
    this.setMPayDetails({
      card_country_name: '',
      card_holder_name: '',
      card_expiry_date: '',
      card_expiry_year: '',
      payout_company: '',
    })
  },
  methods: {
    ...mapActions(['loadEsacSaleDetail', 'downloadEsacInvoice', 'checkPaymentStatus', 'loadSalesDetailsData']),
    ...mapActions('eshop', ['fetchPaymentDocumentDetails', 'loadCart']),
    ...mapActions('enrolment', [
      'setRentalCardDetails',
      'setBankCardDetails',
      'setMPayDetails',
      'setNRICDocDetails',
      'setSupportingDocDetails',
    ]),
    downloadDocument: function() {
      if (this.saleDetails.invoice_id !== null) {
        this.downloadEsacInvoice({ invoice_id: this.saleDetails.invoice_id }).then(() => {
          window.open(this.getEsacDownloadInvoiceData.download_link)
        })
      }
    },
    startPaymentStatusChecking: function() {
      let self = this
      if (this.getWillPaymentPend(this.getCurrentSaleId) === false) {
        window['___payment_status_checker'] = window.setInterval(() => {
          if (self.paymentStatus === 2) {
            self.checkPaymentStatus().then(status => {
              if (status === false) {
                status = 0
              }
              self.paymentStatus = status
            })
          }
        }, 10000)
      } else {
        self.paymentStatus = 3
      }
    },
    loadAnimations() {
      if (this.$refs.lavPending !== undefined) {
        this.$nextTick(() => {
          lottie.loadAnimation({
            container: this.$refs.lavPending,
            renderer: 'svg',
            loop: true,
            animationData: CircleLoader,
          })
        })
      }
    },
    getDeliveryDetails() {
      let salesDeliveryMethodId = this.$helpers.getValue(
        this.saleDetails,
        'selected.shipping.sale_delivery_method',
        null
      )
      if (salesDeliveryMethodId === this.shippingMethodDeliveryId) {
        // this.orderDetail.orderForId = this.saleDetails.downline_member.old_member_id
        let orderFor = this.$helpers.getValue(this.saleDetails, 'downline_member.name')
        if (orderFor) {
          this.orderDetail.orderForName = orderFor
        }
        let address = this.$helpers.getValue(this.saleDetails, 'selected.shipping.recipient_addresses')
        if (address) {
          if (Array.isArray(address)) {
            this.addresses = address
          } else {
            this.addresses = [address]
          }
          this.initMixin(true, false)
          this.orderDetail.orderAddress = this.getAddressString(this.addresses[0])
        }
      } else if (salesDeliveryMethodId === this.shippingMethodSelfCollectionId) {
        if (
          typeof this.saleDetails.self_collection_point !== 'undefined' &&
          this.saleDetails.self_collection_point !== null
        ) {
          if (
            this.saleDetails.self_collection_point.telephone_code !== null &&
            this.saleDetails.self_collection_point.telephone_num !== null
          ) {
            this.orderDetail.collectionTel = this.phoneNumber(
              this.saleDetails.country_id,
              this.saleDetails.self_collection_point.telephone_num
            )
          }
          let address = this.saleDetails.self_collection_point.address_data
          this.addresses = address
          this.initMixin(true, false)
          this.orderDetail.orderForName = this.saleDetails.self_collection_point.location_detail.name
          this.orderDetail.collectionCode = this.saleDetails.self_pick_up_number
          this.orderDetail.collectionAddress = this.getAddressString(address[0])
        }
      }
    },
    getPaymentDetails() {
      let paymentMethod = []
      let promises = []
      this.$helpers.getValue(this.saleDetails, 'selected.payments.paid', []).forEach(payment => {
        paymentMethod.push(payment.payment_mode_provider.name)
        this.orderDetail.paymentMethodName = paymentMethod.join(',')
        promises.push(
          this.fetchPaymentDocumentDetails({
            payment_mode_provider_id: payment.payment_mode_provider_id,
            country_id: this._general_selected_country_id(),
          }).then(() => {
            if (this.getPaymentDocumentDetails.document_data !== null) {
              let documentData = this.getPaymentDocumentDetails.document_data
              if (documentData) {
                this.documentData.push({
                  list: documentData.data,
                  address: documentData.mailing_address.replace(/(?:\\r\\n)/g, '<br/>'),
                })
              }
            }
          })
        )
      })
      return Promise.all(promises)
    },
    isVoucherSelected() {
      let result = false
      let evouchers = this.getCartIsAllDummiesSelected.evoucher
      if (typeof evouchers !== 'undefined' && evouchers !== null) {
        evouchers.forEach(evoucher => {
          if (evoucher.quantity > 0) {
            result = true
          }
        })
      }
      return result
    },
    getVoucherDescription(voucher) {
      return [voucher.evoucher_number, voucher.name].join(': ') || ''
    },
  },
  computed: {
    ...mapGetters([
      'getAppStatus',
      'getEsacSaleData',
      'getEwalletUserCurrency',
      'getEsacDownloadInvoiceData',
      'getSalesDetails',
      'getCurrentSaleId',
      'getSelectedCountry',
      'getCurrentPayment',
      'getEvouchers',
      'getWillPaymentPend',
      'getCurrentPaymentIsQr',
    ]),
    ...mapGetters('eshop', ['getPaymentDocumentDetails', 'getCartIsAllDummiesSelected', 'getProductOrKittingDetails']),
    ...mapMasterDataId({
      SALE_DELIVERY_METHOD: {
        shippingMethodDeliveryId: 'DELIVERY',
        shippingMethodSelfCollectionId: 'SELF_PICKUP',
      },
    }),
    saleDetails() {
      return this._order_complete_get_current_sales_details()
    },
    salesUser() {
      return this._order_complete_get_sales_created_user() || '-N/A-'
    },
    paymentMethod() {
      let payments = []

      if (this.isUseCurrentPaymentMethodOnly) {
        payments.push(this.$helpers.getValue(this.getCurrentPayment, 'payment', {}))
      } else if (this.$helpers.getValue(this.saleDetails, 'selected.payments.paid').length > 0) {
        payments.push(_.last(this.saleDetails.selected.payments.paid))
      } else {
        payments = this.getCurrentPayment.payments
      }
      return Array.isArray(payments)
        ? _.map(payments, payment => payment.payment_mode_provider && payment.payment_mode_provider.name).join(', ')
        : ''
    },
    getPaymentMethod() {
      if (!this.onHoldPaymentCheckOption) {
        return this.paymentMethod
      } else if (
        this.$helpers.getValue(this.saleDetails, 'order_status', '').toLowerCase() === 'completed' &&
        parseFloat(this.$helpers.getValue(this.saleDetails, 'order_fees.total_gmp', '0')) === 0 &&
        parseFloat(this.$helpers.getValue(this.saleDetails, 'order_fees.total_nmp', '0')) === 0
      ) {
        return '-'
      } else {
        return (
          (this.saleDetails.is_paylater === 1 && this.$t('Sales.Payment.Status.PayLater')) ||
          (this.saleDetails.is_cash_on_delivery === 1 && this.$t('Sales.Payment.Status.CashOnDelivery')) ||
          this.paymentMethod
        )
      }
    },
    orderStatus() {
      if (!this.onHoldPaymentCheckOption) {
        return this.statusMap.get(this.paymentStatus)
      } else {
        return (
          ((this.saleDetails.is_paylater === 1 || this.saleDetails.is_cash_on_delivery === 1) &&
            this.statusMap.get(2)) ||
          this.statusMap.get(this.paymentStatus)
        )
      }
    },
    getTransactionStatusMessage() {
      if (
        this.getCurrentPaymentIsQr ||
        (this.onHoldPaymentCheckOption &&
          (this.$helpers.getValue(this.saleDetails, 'is_paylater') === 1 ||
            this.$helpers.getValue(this.saleDetails, 'is_cash_on_delivery') === 1)) ||
        this.$helpers.getValue(this.saleDetails, 'order_status', '').toLowerCase() === 'completed'
      ) {
        return this.messageMap.get(3)
      } else {
        if (this.paymentStatus === 1 && this.getAppStatus('enrolment')) {
          return this.$t('Enrolment.Order.RegistrationApplicationSubmitted')
        }
        return this.messageMap.get(this.paymentStatus)
      }
    },
    getTransactionDate() {
      return moment(this.saleDetails.transaction_date).format('DD/MM/YYYY')
    },
    getTableField() {
      return [
        { key: 'transaction_date', label: this.$t('Common.Sales.TransactionDate') },
        { key: 'document_number', label: this.$t('Eshop.Order.OrderConfirmationList.TableHeader.DocumentNo') },
        { key: 'order_by', label: this.$t('Eshop.Order.OrderConfirmationList.TableHeader.OrderBy') },
        { key: 'payment_method', label: this.$t('Common.Sales.PaymentMethod') },
        { key: 'total_bv', label: this.$t('Common.Terminology.TotalBV') },
        { key: 'total_sv', label: this.$t('Common.Terminology.TotalSv'), show: this.$appSettings.evo.enable },
        { key: 'total_cbp', label: this.$t('Common.Terminology.TotalCbp'), show: this.$appSettings.evo.enable },
        { key: 'order_fees', label: `${this.$t('Common.TotalAmount')} (${this.currency})`, class: 'text-lg-right' },
        { key: 'delivery_method', label: this.$t('Common.ShippingMethod') },
        { key: 'status', label: this.$t('Common.Status') },
      ].filter(field => field.show !== false)
    },
  },
  watch: {
    paymentStatus: function() {
      if (this.paymentStatus === 1 || this.paymentStatus === 3) {
        if (this.showPaymentModeDeliveryDetails) {
          this.loadSalesDetailsData({ saleId: parseInt(this.getCurrentSaleId) })
            .then(async () => {
              await this.getDeliveryDetails()
              return await this.getPaymentDetails()
            })
            .finally(async () => {
              await this.loadCart()
              this.$emit('payment-success', true)
            })
        } else {
          this.$emit('payment-success', true)
        }
      }
    },
  },
  beforeDestroy() {
    if (typeof window['___payment_status_checker'] !== 'undefined') {
      clearInterval(window['___payment_status_checker'])
    }
  },
}
</script>
