<template>
  <div class="eshop">
    <div class="ewallet-fund-step-title">
      {{ $t('EWallet.GlobalWords.Step1') }}
      {{ $t('EWallet.FundTransfer.ApplicationFormStepDescription') }}
    </div>
    <div id="ewallet-fund-body">
      <b-container fluid>
        <div class="fund-first-step-body">
          <b-row>
            <b-col class="ew-lbl">
              <label class="required"> {{ $t('EWallet.Amount') }} </label>:
            </b-col>
            <b-col class="ew-cnt">
              <b-form-input
                size="sm"
                type="text"
                v-model="fundTransferAmount"
                name="Amount"
                v-validate="'required|decimal'"
                :class="{ input: true, 'is-danger': errors.has('Amount') || amountStatus }"
                @focus.native="resetError"
                @keyup.native="checkAmount"
              />
              <span v-show="errors.has('Amount')" class="help is-danger">
                {{ amountError(errors) }}
              </span>
              <span v-show="amountStatus" class="help is-danger">
                {{ amountErrorMsg }}
              </span>
            </b-col>
          </b-row>
          <b-row>
            <b-col class="ew-lbl">
              <label> {{ $t('Common.From') }}: </label>
            </b-col>
            <b-col class="ew-cnt">
              <b-form-input
                size="sm"
                type="text"
                model="fundTransferFrom"
                name="from"
                :value="getIboId + ' - ' + getUserName"
                disabled
              />
            </b-col>
          </b-row>
          <b-row>
            <b-col class="ew-lbl">
              <label class="required"> {{ $t('EWallet.FundTransfer.TOI') }} </label>:
            </b-col>
            <b-col class="ew-cnt">
              <b-input-group>
                <b-form-input
                  size="sm"
                  id="fundtransferTOIId"
                  type="text"
                  v-model="fundTransferTOI"
                  name="IBO"
                  v-validate="'required|numeric'"
                  @input="showCheck"
                  :class="{ input: true, 'is-danger': errors.has('IBO') || checkEwalletStatus }"
                  :placeholder="$t('EWallet.GlobalWords.IBOID')"
                  @focus.native="resetError"
                />
                <icon class="icon-size-3" v-if="isLoading('memberTreeLoading')" name="spinner" pulse />
              </b-input-group>
              <b-popover
                class="popover"
                ref="popoperref"
                target="fundtransferTOIId"
                role="tooltip"
                data-animation="true"
              >
                <ul v-if="getMemberSearchGenealogy.length > 0 && searchStatus" class="list-group">
                  <li
                    class="list-group-item text-dark"
                    v-for="temp in getMemberSearchGenealogy"
                    :key="temp.value"
                    @click="handleListItem(temp)"
                  >
                    {{ temp.label }} <br />
                    {{ temp.name }}
                  </li>
                </ul>
                <ul v-else-if="searchStatus && !showTOI2" class="list-group">
                  <li class="list-group-item text-dark" @click="onBlurSearch">
                    {{ $t('EWallet.GlobalWords.NoMemberFound') }}
                  </li>
                </ul>
              </b-popover>
              <button
                v-if="showCheckButton && !errors.has('IBO')"
                class="btn btn-primary mt-2 float-right"
                @click="verifyMemberNetworkTree"
              >
                {{ $t('Enrolment.Check.Button') }}
              </button>
            </b-col>
          </b-row>
          <b-row class="justify-content-end">
            <b-col class="ew-cnt">
              <b-form-input
                size="sm"
                type="text"
                v-model="fundTransferTOI2"
                name="fundTransferTOI2"
                :placeholder="$t('Common.IboName')"
                disabled
                v-if="showTOI2"
                @focus.native="resetError"
              />
              <span v-show="errors.has('IBO')" class="help is-danger">
                {{ iboError(errors) }}
              </span>
              <span v-show="checkEwalletStatus" class="help is-danger">
                {{ checkEwalletMsg }}
              </span>
            </b-col>
          </b-row>
          <b-row>
            <b-col class="ew-lbl">
              <label size="sm"> {{ $t('EWallet.TransactionForm.RecipientEmail') }}: </label>
            </b-col>
            <b-col class="ew-cnt">
              <b-form-input
                size="sm"
                type="text"
                v-model="fundTransferRecipientEmail"
                name="Recipient Email"
                v-validate="'email|max:56'"
                :placeholder="$t('EWallet.TransactionForm.Placeholder.Optional')"
                :class="{ input: true, 'is-danger': errors.has('Recipient Email') }"
              />
              <span v-show="errors.has('Recipient Email')" class="help is-danger">
                {{ $t('EWallet.GlobalWords.EmailError') }}
              </span>
            </b-col>
          </b-row>
          <b-row>
            <b-col class="ew-lbl">
              <label size="sm"> {{ $t('EWallet.TransactionForm.RecipientReference') }}: </label>
            </b-col>
            <b-col class="ew-cnt">
              <b-form-input
                size="sm"
                type="text"
                v-model="fundTransferRecReference"
                v-validate="'max:76'"
                name="Recipient Reference"
                :placeholder="$t('EWallet.TransactionForm.Placeholder.Optional')"
                :class="{ input: true, 'is-danger': errors.has('Recipient Reference') }"
              />
              <span v-show="errors.has('Recipient Reference')" class="help is-danger">
                {{ errors.first('Recipient Reference') }}
              </span>
            </b-col>
          </b-row>
        </div>
        <b-row class="justify-content-center justify-content-md-end pr-3">
          <b-btn @click="cancelFundStep('')" variant="outline-dark" class="px-4">
            {{ $t('EWallet.GlobalWords.Cancel') }}
          </b-btn>
          <b-btn class="ml-1 px-4" variant="outline-primary" @click="next">
            {{ $t('EWallet.GlobalWords.Continue') }}
          </b-btn>
        </b-row>
      </b-container>
    </div>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import Vue from 'vue'
export default {
  name: 'FundtransferFirstStep',
  $_veeValidate: {
    validator: 'new',
  },
  data() {
    return {
      fundTransferAmount: '',
      fundTransferFrom: '',
      fundTransferTOI: '',
      fundTransferTOI2: '',
      fundTransferRecipientEmail: '',
      fundTransferRecReference: '',
      amountStatus: false,
      amountErrorMsg: '',
      searchStatus: false,
      toUserId: '',
      temporarySearchedText: '',
      showPopOver: false,
      showTOI2: false,
      checkEwalletMsg: '',
      checkEwalletStatus: false,
      showCheckButton: false,
      showVerifiedIcon: false,
      showNotVerifiedIcon: false,
      nextStep: false,
    }
  },
  mounted() {
    this.loadEwalletBalance()
  },
  methods: {
    ...mapActions([
      'setFundStep',
      'cancelFundStep',
      'fundTransferInfo',
      'setInsufficientFundErr',
      'setRangeFundErr',
      'getMemberSearchTreeActionGenealogy',
      'loadEwalletBalance',
      'clearSearchTreeResult',
      'checkEwalletActivation',
      'searchMemberSponsor',
    ]),
    showCheck(value) {
      if (value !== '') {
        this.showCheckButton = true
        this.checkEwalletStatus = false
      } else {
        this.showCheckButton = false
      }
      this.showTOI2 = false
    },
    verifyMemberNetworkTree() {
      let query = {
        old_member_id: this.fundTransferTOI,
      }
      this.searchMemberSponsor(query).then(res => {
        if (res.status) {
          // Check user's ewallet if it's active or not
          this.fundTransferTOI2 = res.msg.name
          this.toUserId = res.msg.user_id
          this.fundTransferRecipientEmail = res.msg.email
          let mData = {
            amount: this.fundTransferAmount,
            from: this.getIboId + '-' + this.getUserName,
            toUserId: res.msg.user_id,
            TOI: this.fundTransferTOI,
            TOI2: this.fundTransferTOI2,
            recipientEmail: this.fundTransferRecipientEmail,
            recRef: this.fundTransferRecReference,
          }
          this.fundTransferInfo(mData)
          this.checkEwalletActivation(mData).then(res => {
            if (res.status) {
              this.showTOI2 = true
              this.showCheckButton = false
              this.checkEwalletStatus = false
              this.nextStep = true
            } else {
              this.nextStep = false
              this.checkEwalletStatus = true
              this.checkEwalletMsg = res.msg || Vue.i18n.translate('Common.Genealogy.MemberSearch.Fail')
            }
          })
        } else {
          this.checkEwalletStatus = true
          this.checkEwalletMsg = Vue.i18n.translate('Common.Genealogy.MemberSearch.Fail')
        }
      })
    },
    onBlurSearch() {
      setTimeout(() => {
        this.$refs.popoperref.$emit('close')
        this.searchStatus = false
      }, 1000)
    },
    resetError() {
      this.setInsufficientFundErr(false)
      this.setRangeFundErr(false)
      this.showPopOver = false
    },
    handleListItem(value) {
      this.temporarySearchedText = value.label
      this.searchStatus = false
      this.toUserId = value.value
      this.fundTransferTOI = value.label
      this.fundTransferTOI2 = value.name
      this.showTOI2 = true
      this.$refs.popoperref.$emit('close')
      this.clearSearchTreeResult()
    },
    searchIBOID(value) {
      if (value !== '' && value !== this.temporarySearchedText) {
        this.showTOI2 = false
        this.checkEwalletStatus = true
        let query = {
          search_text: value,
          verified: 3,
          limit: 10,
        }
        this.getMemberSearchTreeActionGenealogy(query).then(res => {
          if (res) {
            this.searchStatus = true
            this.$refs.popoperref.$emit('open')
            if (this.showTOI2) {
              this.clearSearchTreeResult()
            }
          } else {
            this.searchStatus = false
          }
        })
      } else {
        this.searchStatus = false
      }
    },
    amountError(errorObj) {
      if (errorObj.items.length > 0) {
        if (errorObj.items[0].field === 'Amount') {
          if (errorObj.items[0].rule === 'required') {
            return Vue.i18n.translate('EWallet.GlobalWords.AmountRequiredError')
          } else {
            return Vue.i18n.translate('EWallet.GlobalWords.AmountDecimalError')
          }
        }
      }
    },
    iboError(errorObj) {
      if (errorObj.items.length > 0) {
        let temp = errorObj.items.find(function(obj) {
          return obj.field === 'IBO'
        })
        if (typeof temp !== 'undefined' && temp.hasOwnProperty('rule')) {
          if (temp.rule === 'required') {
            return Vue.i18n.translate('EWallet.GlobalWords.IBORequiredError')
          } else {
            return Vue.i18n.translate('EWallet.GlobalWords.IBOAlphaNumError')
          }
        }
      }
    },
    checkAmount() {
      if (parseFloat(this.fundTransferAmount) < 0.01) {
        this.amountStatus = true
        this.amountErrorMsg = Vue.i18n.translate('EWallet.GlobalWords.RangeFundError')
      } else if (parseFloat(this.fundTransferAmount) > parseFloat(this.getEwalletBalanceInt)) {
        this.amountStatus = true
        this.amountErrorMsg = Vue.i18n.translate('EWallet.Transaction.InsufficientFund')
      } else {
        this.amountStatus = false
        this.amountErrorMsg = ''
      }
    },
    next: function() {
      this.$validator.validateAll().then(valid => {
        if (valid) {
          if (!this.amountStatus) {
            let mData = {
              amount: this.fundTransferAmount,
              from: this.getIboId + '-' + this.getUserName,
              toUserId: this.toUserId,
              TOI: this.fundTransferTOI,
              TOI2: this.fundTransferTOI2,
              recipientEmail: this.fundTransferRecipientEmail,
              recRef: this.fundTransferRecReference,
            }
            this.fundTransferInfo(mData)
            if (!this.nextStep) {
              if (!this.checkEwalletStatus) {
                this.checkEwalletStatus = true
                this.checkEwalletMsg = Vue.i18n.translate('Genealogy.PlacementNetworkTree.CheckIBOID')
              }
            }
            if (this.nextStep && !this.checkEwalletStatus) {
              this.setFundStep('fundSecondStep')
            }
          }
        }
      })
    },
  },
  computed: {
    ...mapGetters([
      'getEWalletFundStep',
      'getIboId',
      'getUserName',
      'getEwalletBalanceInt',
      'getEwalletInsufficientFund',
      'getEwalletRangeFund',
      'getSearchedIboId',
      'getMemberSearchGenealogy',
      'isLoading',
      'getEwalletUserId',
    ]),
  },
}
</script>
