<template>
  <b-card>
    <div class="d-flex justify-content-center align-items-center vh-50" v-if="loadingData">
      <icon class="icon-size-4" name="spinner" pulse />
    </div>
    <div v-else>
      <b-container v-if="inputSecurityPINPageVisible">
        <b-row class="my-2">
          <b-col xl="3">
            <label class="required">
              {{ $t('Common.Security.SecurityPin') }}
            </label>
          </b-col>
          <b-col sm="5">
            <b-form-input
              v-validate="'required'"
              name="Security PIN"
              v-model="securityPIN"
              :class="{ input: true, 'is-danger': errors.has('Security PIN') }"
              type="password"
            />
            <span v-show="errors.has('Security PIN')" class="help is-danger">
              {{ errors.first('Security PIN') }}
            </span>
            <b-alert variant="danger" v-if="getErrors('pin')" show>
              {{ $t('Login.LoginForm.ErrorLoginMessage') }}
            </b-alert>
          </b-col>
        </b-row>
        <b-row class="my-2">
          <b-col xl="3" />
          <b-col sm="5">
            <b-link v-b-modal.confirm_reset_pin>
              {{ $t('Eshop.Order.Payment.Method.EWallet.ForgetPIN') }}
            </b-link>
          </b-col>
        </b-row>
        <b-row class="my-2">
          <b-col xl="3" />
          <b-col sm="5">
            <b-btn v-b-toggle.payment-ewallet class="btn-cancel">
              {{ $t('Eshop.Order.GlobalWords.Cancel') }}
            </b-btn>
            <b-btn @click="gotoInputAmountPage" class="btn-next">
              {{ $t('Eshop.Order.GlobalWords.Next') }}
            </b-btn>
          </b-col>
        </b-row>
      </b-container>
      <b-container v-if="inputAmountPageVisible">
        <b-row class="my-2">
          <b-col xl="3">
            <label> {{ $t('Eshop.Order.Payment.Method.EWallet.EWalletBalance') }}</label>
          </b-col>
          <b-col sm="5">
            <b-form-input name="balance" :value="eWalletBalance.toFixed(2)" disabled type="text" />
          </b-col>
        </b-row>
        <b-row class="my-2">
          <b-col xl="3">
            <label class="required">
              {{ $t('Eshop.Order.Payment.Method.EWallet.AmountToPay') }}
            </label>
          </b-col>
          <b-col sm="5">
            <b-form-input
              v-validate="'required|decimal:2|max_value:1000'"
              name="Amount Pay"
              v-model="amountPay"
              :class="{ input: true, 'is-danger': errors.has('Amount Pay') }"
              type="text"
            />
            <span v-show="errors.has('Amount Pay')" class="help is-danger">
              {{ errors.first('Amount Pay') }}
            </span>
          </b-col>
        </b-row>
        <b-row class="my-2">
          <b-col xl="3" />
          <b-col sm="5">
            <b-btn v-b-toggle.payment-ewallet class="btn-cancel">
              {{ $t('Eshop.Order.GlobalWords.Cancel') }}
            </b-btn>
            <b-btn @click="gotoFinalAmountPage" class="btn-confirm">
              {{ $t('Eshop.Order.GlobalWords.Confirm') }}
            </b-btn>
          </b-col>
        </b-row>
      </b-container>
      <b-container v-if="finalAmountPageVisible">
        <b-row class="my-2">
          <b-col xl="3">
            <label> {{ $t('Eshop.Order.Payment.Method.EWallet.AmountPaid') }}</label>
          </b-col>
          <b-col sm="5">
            <b-form-input name="balance" v-model="amountPaid" disabled type="text" />
          </b-col>
        </b-row>
        <b-row class="my-2">
          <b-col xl="3" />
          <b-col sm="5">
            <b-btn @click="resetEwalletPayment" class="btn-cancel">
              {{ $t('Eshop.Order.GlobalWords.Cancel') }}
            </b-btn>
            <b-btn v-if="!needMorePayment" v-b-modal.confirm_payment_ewallet class="btn-next">
              {{ $t('Eshop.Order.GlobalWords.Confirm') }}
            </b-btn>
          </b-col>
        </b-row>
        <span v-if="needMorePayment" class="red-message">
          {{ $t('Eshop.Order.GlobalWords.SelectNextPayment') }}
        </span>
      </b-container>
      <b-modal id="confirm_payment_ewallet" class="eshop-model" centered @ok="commitEwalletPayment">
        <div>{{ $t('Eshop.Order.GlobalWords.ConfirmPaymentFromEwallet') }}</div>
      </b-modal>
      <payment-e-wallet-reset-pin :e-wallet-mobile-number="eWalletMobileNumber" />
    </div>
  </b-card>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import paymentEWalletResetPin from './PaymentEWalletResetPin'
export default {
  name: 'PaymentEWallet',
  components: {
    paymentEWalletResetPin,
  },
  props: {
    cancelAction: {
      type: Function,
      required: true,
    },
    confirmAction: {
      type: Function,
      required: true,
    },
    payableAmount: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      inputSecurityPINPageVisible: true,
      inputAmountPageVisible: false,
      finalAmountPageVisible: false,
      needMorePayment: false,
      securityPIN: '',
      amountPay: 0,
      amountPaid: 0,
      eWalletBalance: 0,
      eWalletMobileNumber: '',
      loadingData: true,
    }
  },
  created() {
    this.$validator.extend('verify_pin', {
      getMessage: field => `This is not a valid pin.`,
      validate: value =>
        new Promise(resolve => {
          // @todo should be from backend
          const validPins = ['123', '111', '123456']

          setTimeout(() => {
            resolve({
              valid: value && validPins.indexOf(value.toUpperCase()) !== -1,
            })
          }, 500)
        }),
    })
    this.$validator.attach({
      name: 'Security PIN',
      rules: 'required|verify_pin',
    })
  },
  mounted() {
    this.loadEwalletBalance().then(response => {
      this.eWalletBalance = parseFloat(this.getEwalletBalanceInt)
      this.eWalletMobileNumber = this.getMobileNumber
      this.validateAmountPay()
      this.loadingData = false
    })
  },
  methods: {
    ...mapActions(['loadEwalletBalance']),
    openResetPin: function() {
      this.$refs.reset_pin_modal.show()
    },
    showNextResetPage: function() {
      this.$refs.new_pin_modal.show()
    },
    resetEwalletPayment: function() {
      this.inputSecurityPINPageVisible = true
      this.inputAmountPageVisible = false
      this.finalAmountPageVisible = false
      this.validateAmountPay
      this.securityPIN = ''
    },
    gotoInputAmountPage: function() {
      this.$validator.validate('Security PIN', this.securityPIN).then(valid => {
        if (valid) {
          this.inputSecurityPINPageVisible = false
          this.inputAmountPageVisible = true
        }
      })
    },
    gotoFinalAmountPage: function() {
      this.$validator.validate('Amount Pay', this.amountPay).then(valid => {
        if (valid) {
          if (parseFloat(this.amountPay) > this.eWalletBalance) {
            // TODO: not allow to proceed, stay in current page // maybe show message
          } else {
            this.inputSecurityPINPageVisible = false
            this.inputAmountPageVisible = false
            this.finalAmountPageVisible = true
            this.amountPaid = this.amountPay
            this.validateAmountPay
          }
        }
      })
    },
    commitEwalletPayment: function() {
      this.confirmAction({
        securityPIN: this.securityPIN,
        amount: this.amountPaid,
      })
    },
    validateAmountPay: function() {
      if (this.amountPay === 0) {
        if (this.payableAmount < this.eWalletBalance) {
          this.amountPay = this.payableAmount.toFixed(2)
        } else {
          this.amountPay = this.eWalletBalance.toFixed(2)
        }
      } else {
        this.amountPay = parseFloat(this.amountPay).toFixed(2)
        this.amountPaid = parseFloat(this.amountPay).toFixed(2)
      }
      this.needMorePayment = this.amountPaid < this.payableAmount
      return true
    },
  },
  computed: {
    ...mapGetters('eshop', ['getOrderStep', 'getRoundAdjustAmount']),
    ...mapGetters(['getErrors', 'getEwalletBalanceInt', 'getMobileNumber']),
  },
}
</script>
