<template>
  <b-row>
    <b-col md="8" lg="7" xl="5" class="mb-5">
      <b-form-group
        label-for="IboId"
        :label="$t('Common.IboId')"
        :label-class="['required']"
        :state="!(customError.ibo || errors.has('Ibo Id')) && null"
        :invalid-feedback="customError.ibo || errors.first('Ibo Id')"
      >
        <b-input-group @keyup.enter="memberSearchTrigger" class="rounded-1 overflow-hidden">
          <b-form-input
            id="IboId"
            name="Ibo Id"
            type="number"
            v-model="iboSearchText"
            v-validate="'required|numeric'"
            :data-vv-as="$t('Common.IboId')"
            class="border-right-0 rounded-left"
            :state="!(customError.ibo || errors.has('Ibo Id')) && null"
            :disabled="isLoading('memberListLoading') || Boolean(formData.ibo.old_member_id) || fieldLock"
            :data-qa="`${dataQaPrefix}-fundTransfer-iboId-input`"
          />
          <b-input-group-append>
            <b-button
              squared
              class="border-0"
              @click="memberSearchTrigger"
              :variant="formData.ibo.name ? 'light' : 'primary'"
              :disabled="isLoading('memberListLoading') || !iboSearchText"
              :data-qa="
                `${dataQaPrefix}-fundTransfer-${(formData.ibo.name && 'clearMemberSearch') || 'searchMember'}-btn`
              "
            >
              <b-spinner v-if="isLoading('memberListLoading')" small />
              <icon v-else-if="formData.ibo.name" name="remove-icon" />
              <icon v-else name="search" />
            </b-button>
          </b-input-group-append>
        </b-input-group>
      </b-form-group>

      <b-form-group label-for="IboName" :label-class="['required']" :label="$t('Common.IboName')">
        <b-form-input
          id="IboName"
          readonly
          name="Ibo Name"
          class="rounded-1"
          v-validate="'required'"
          :value="formData.ibo.name"
          :data-qa="`${dataQaPrefix}-fundTransfer-iboName-input`"
        />
      </b-form-group>

      <b-form-group
        label-for="Amount"
        :label-class="['required']"
        :label="$t('EWallet.Amount')"
        :invalid-feedback="customError.amount || errors.first('Amount')"
      >
        <b-form-input
          id="Amount"
          type="number"
          name="Amount"
          placeholder="0.00"
          :disabled="fieldLock"
          v-model="formData.amount"
          class="rounded-1 col-6 col-lg-5"
          :data-vv-as="$t('EWallet.Amount')"
          v-validate="'required|between:0.01,999999.99|max:9'"
          :state="!(customError.amount || errors.has('Amount')) && null"
          :data-qa="`${dataQaPrefix}-fundTransfer-amount-input`"
        />
      </b-form-group>

      <b-form-group
        label-for="RecipientEmail"
        :label="$t('EWallet.TransactionForm.RecipientEmail')"
        :invalid-feedback="errors.first('Recipient Email')"
      >
        <b-form-input
          id="RecipientEmail"
          lazy
          type="email"
          class="rounded-1"
          v-validate="'email'"
          :disabled="fieldLock"
          name="Recipient Email"
          v-model="formData.recipientEmail"
          placeholder="emailaddress@elken.com"
          :state="!errors.has('Recipient Email') && null"
          :data-vv-as="$t('EWallet.TransactionForm.RecipientEmail')"
          :data-qa="`${dataQaPrefix}-fundTransfer-recipientEmail-input`"
        />
      </b-form-group>

      <b-form-group
        label-for="RecipientReference"
        :label="$t('EWallet.TransactionForm.RecipientReference')"
        :invalid-feedback="errors.first('Recipient Reference')"
      >
        <!-- Purposely set maxlength = upper limit + 1 to display error -->
        <b-form-textarea
          id="RecipientReference"
          trim
          rows="3"
          no-resize
          maxlength="121"
          class="rounded-1"
          :disabled="fieldLock"
          v-validate="'max:120'"
          name="Recipient Reference"
          v-model="formData.recipientReference"
          :state="!errors.has('Recipient Reference') && null"
          :data-vv-as="$t('EWallet.TransactionForm.RecipientReference')"
          :placeholder="$t('EWallet.TransactionForm.Placeholder.Optional')"
          :data-qa="`${dataQaPrefix}-fundTransfer-recipientReference-input`"
        />
      </b-form-group>
    </b-col>

    <b-col cols="12">
      <slot />
    </b-col>
  </b-row>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { convertToCurrencyAmount } from '@/helpers/currency-formatter'

export default {
  name: 'FundTransferForm',
  $_veeValidate: {
    validator: 'new',
  },
  props: {
    dataQaPrefix: { type: String, required: true },
  },
  data() {
    return {
      fieldLock: false,
      iboSearchText: '',
      formData: {
        ibo: {},
        amount: null,
        recipientEmail: '',
        recipientReference: '',
      },
      customError: {
        ibo: '',
        amount: '',
      },
    }
  },
  watch: {
    iboSearchText() {
      this.customError.ibo = ''
    },
    'formData.amount'() {
      this.customError.amount = ''
    },
  },
  computed: {
    ...mapGetters(['isLoading', 'getMemberCountryId', 'getEWalletDetails']),
  },
  methods: {
    ...mapActions(['loadMemberList']),
    async validateAndSubmit() {
      let self = this
      self.fieldLock = true

      if (!(self.formData.ibo.old_member_id || '').toString() && self.iboSearchText) {
        await self.searchMember()
      }
      return await self.$validator.validate().then(valid => {
        let result = valid

        if (result) {
          /** Note: below currency (decimal point) conversion max support until 13 CHAR long number ONLY
           * as it will cause DECIMAL_POINT_CONVERSION_ERROR by computer
           * e.g. : 9.99999999999 * 100 will equals to 999.9999999990001
           * e.g. : 9.999999999999999 *100 will equals to 999.9999999999998
           * e.g. : 9.9999999999999999 *100 will equals to 1000
           */
          let transactionAmount = Math.floor(self.formData.amount * 100)
          let currentBalance = Math.floor((self.getEWalletDetails.balance || '0') * 100)

          if (transactionAmount <= currentBalance) {
            self.formData.amount = convertToCurrencyAmount(self.formData.amount)
          } else {
            self.customError.amount = self.$t('EWallet.Transaction.InsufficientFund')
            result = false
          }
        } else {
          self.$swal({
            type: 'error',
            title: self.errors.items[0].msg || '',
            timer: '2300',
          })
        }

        self.fieldLock = false
        return result
      })
    },
    async memberSearchTrigger() {
      if (this.formData.ibo.old_member_id) {
        this.clearMemberSearch()
      } else {
        await this.searchMember(false)
      }
    },
    clearMemberSearch() {
      this.iboSearchText = ''
      this.formData.ibo = {}
    },
    async searchMember() {
      if (this.iboSearchText) {
        let payload = {
          limit: 1,
          minimal: true,
          includeSelf: false,
          exactText: this.iboSearchText,
          countryId: this.getMemberCountryId,
        }
        await this.loadMemberList(payload).then(result => {
          result = (result && result[0]) || {}
          if (result.hasOwnProperty('old_member_id')) {
            this.formData.ibo = { ...result }
          } else {
            this.customError.ibo = this.$t('Common.Genealogy.MemberSearch.Fail')
          }
        })
      } else {
        this.customError.ibo = this.$t('Common.Genealogy.MemberSearch.Fail')
      }
    },
    getComponentModelData() {
      let { old_member_id, name, user_id } = this.formData.ibo
      return {
        targetName: name,
        targetUserId: user_id,
        targetIbo: old_member_id,
        amount: this.formData.amount,
        recipientEmail: this.formData.recipientEmail,
        recipientReference: this.formData.recipientReference,
      }
    },
  },
}
</script>
