<template>
  <div class="container p-4 border bg-white mb-4">
    <div>
      <tick-or-choose
        v-model="additionalAgreements"
        class="pb-3"
        :options="agreementAdditionalMessages"
        :title="$t('Eshop.Order.GlobalWords.Agreement')"
        :container-class="[{ 'px-0': $appSettings.evo.enable }]"
        :title-class="[{ 'text-uppercase h5 font-weight-bold-semi': $appSettings.evo.enable }]"
        :class="{ 'border border-danger bg-important px-2 pt-3': !$appSettings.evo.enable }"
      />
      <div>
        <div v-if="!allowZeroBalance || balance !== 0" class="my-3">
          <span :class="{ 'text-uppercase h5 font-weight-bold-semi': $appSettings.evo.enable }">
            {{ $t('Eshop.Order.Payment.Title') }}
          </span>
        </div>

        <template>
          <div v-if="showPaymentOptions">
            <b-tooltip
              v-if="!canPay"
              :target="() => $refs.paymentMethods"
              :title="$t('Eshop.Order.GlobalWords.PleaseAcceptAgreementAbove')"
            />

            <div ref="paymentMethods">
              <payment-methods-collapse
                :balance="balance"
                :disabled="!canPay"
                :fixed-amount="true"
                class="animated fadeIn"
                :field-types="fieldTypes"
                :cross-domain="crossDomain"
                :payment-success-callback="onPayment"
                :allow-zero-balance="allowZeroBalance"
                :before-payment-callback="createSales"
                :check-epp-payments="checkEppPayments"
                :lottie-loader-file="lottieLoaderFile"
                :lottie-loader-class="lottieLoaderClass"
                :rounded-corner="$appSettings.evo.enable"
                :exclude-payment-mode="excludePaymentMode"
                :on-hold-payment-callback="createOnHoldPaymentSales"
                :on-hold-payment-options-key="onHoldPaymentOptionsKey"
                :show-on-hold-payment-options="displayOnHoldPaymentOptions"
              />
            </div>
          </div>

          <b-skeleton-img v-else height="50px" no-aspect />
        </template>
      </div>
    </div>
  </div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import store from '@/store'
import PaymentMethodsCollapse from './PaymentMethodsCollapse'
import { mapMasterDataId } from '@/app/_global/mixins'
import tickOrChoose from '@/elements/choice-boxes/TickOrChoose'

export default {
  name: 'OrderPayment',
  $_veeValidate: {
    validator: 'new',
  },
  components: {
    PaymentMethodsCollapse,
    tickOrChoose,
  },
  props: {
    createSales: {
      type: Function,
      default: () => {
        return mode => Promise.resolve(mode)
      },
    },
    onPayment: {
      type: Function,
      default: () => {
        return mode => Promise.resolve(mode)
      },
    },
    balance: {
      type: Number,
      default: 0,
    },
    allowZeroBalance: {
      type: Boolean,
      default: false,
    },
    excludePaymentMode: {
      type: Array,
      default: () => [],
    },
    fieldTypes: {
      type: Map,
      default: () =>
        new Map([
          ['field', 'b-form-input'],
          ['dropdown', 'b-form-select'],
        ]),
    },
    checkEppPayments: {
      type: Boolean,
      default: true,
    },
    agreementAdditionalMessages: {
      type: Array,
      default() {
        return store.getters.getCheckoutAgreement
      },
    },
    showOnHoldPaymentOptions: {
      type: Boolean,
      default: true,
    },
    lottieLoaderFile: {
      type: Object,
    },
    lottieLoaderClass: {
      type: String,
    },
    crossDomain: {
      type: Boolean,
      default: false,
    },
    onHoldPaymentOptionsKey: {
      type: Array,
      default: () => [],
    },
    showAmpPreference: {
      type: Boolean,
      default: false,
    },
    showPaymentOptions: {
      type: Boolean,
      default: true,
    },
  },
  async mounted() {
    this.resolveMasters.then(() => {
      this.getEformLink([this.tncId])
    })
  },
  data() {
    return {
      payLater: false,
      showLoadingPopup: false,
      additionalAgreements: [],
      ampPreferenceData: null,
    }
  },
  methods: {
    ...mapActions(['setShowLoadingPopup', 'getEformLink', 'loadBackendSetting']),
    createOnHoldPaymentSales() {
      this.showLoadingPopup = true
      this.createSales({ sale_id: 0 }).then(() => {
        this.showLoadingPopup = false
        this.onPayment()
      })
    },
  },
  computed: {
    ...mapGetters([
      'isLoading',
      'getSelectedCountry',
      'getAppLocationCountry',
      'getSelectedCountry',
      'getAppStatus',
      'getCountryNameById',
      'getCheckoutAgreement',
      'getOnHoldPaymentPrivilege',
      'getBackendSetting',
    ]),
    ...mapMasterDataId({
      SMART_LIBRARY_EFORM_FILE_TYPE: {
        tncId: 'TNC',
      },
      SALE_TYPES: {
        formationSalesTypeId: 'FORMATION',
        autoMaintenanceSalesTypeId: 'AUTO_MAINTENANCE',
        repurchase: 'RE_PURCHASE',
        baUpgradeSalesTypeId: 'BA_UPGRADE',
        rentalSalesTypeId: 'RENTAL',
      },
    }),
    ...mapGetters(['getSelectedCountry', 'getAppLocationCountry', 'getEformLinkData']),
    ...mapGetters('enrolment', ['getEnrolCountryId']),
    ...mapGetters('eshop', ['getCartIsRentalSaleOrder', 'getCartSalesTypes']),
    canPay() {
      let agreed = this.additionalAgreements.filter(a => a !== false).length === this.agreementAdditionalMessages.length
      let loading = this.isLoading(['saveTempEnrolment', 'loadingBackendSettings'])

      return agreed && !loading
    },
    displayOnHoldPaymentOptions() {
      return this.showOnHoldPaymentOptions && this.$appSettings.payment.on_hold_payment_options
    },
    ampPreferenceDefault() {
      let defaultSetting = this.getBackendSetting('default_member_amp_preference') || { data: null }

      return defaultSetting.data
    },
  },
  watch: {
    showAmpPreference: {
      handler(to, from) {
        if (to !== from && to === true) {
          this.loadBackendSetting(['default_member_amp_preference']).then(data => {
            let preference = data['default_member_amp_preference'] || { data: null }

            this.ampPreferenceData = preference.data
          })
        }
      },
      immediate: true,
    },
    ampPreferenceData(to, from) {
      this.$emit('ampPreference', JSON.parse(JSON.stringify(to)))
    },
  },
}
</script>
