import * as T from '@/store/utils/types'

import { EWALLET_FUND_WITHDRAWAL, EWALLET_FUND_TRANSFER } from '@/config/url-prefix'
import * as U from '@/store/utils/apiUrls'
import { get, post } from '../../utils/api'
import router from '@/router'
import moment from 'moment'
import { getValue } from '@/helpers/variable-handling'

export const setFundStep = ({ commit }, data) => {
  commit(T.CONFIRM_FUND_STEP, data)
}

export const finishFundStep = ({ commit }, data) => {
  commit(T.FINISH_FUND_STEP, data)
  router.go(-1)
}

export const finishFundWithdrawal = ({ commit }, data) => {
  commit(T.FINISH_FUND_STEP, data)
  router.push({ name: 'EWalletHome' })
}

export const cancelFundStep = ({ commit }, data) => {
  commit(T.SET_EWALLET_MOBILE_VERIFICATION_STATUS, false)
  commit(T.SET_EWALLET_MOBILE_CONFIRMATION_STATUS, { client: false, status: false })
  commit(T.SET_EWALLET_FUND_TRANSFER_STATUS, false)
  if (data === '') {
    router.go(-1)
  } else {
    commit(T.CANCEL_FUND_STEP, data)
  }
}

export const printDocument = () => {
  window.print()
}

export const processFund = ({ commit }, data) => {
  if (data === 'fundwithdrawal') {
    router.push(EWALLET_FUND_WITHDRAWAL)
  } else {
    router.push(EWALLET_FUND_TRANSFER)
  }
}

export const loadEwalletBalance = ({ commit, getters, dispatch }) => {
  return get(U.EWALLET_HOME)
    .then(response => {
      commit(T.SET_EWALLET_INFO, response.data)
      dispatch('loadCountryDynamicContent')
      dispatch('loadMyAccountInfo').then(res => {
        if (res) {
          dispatch('loadBankList')
          if (getters.getMyAccountMemberDetails.banking.payment_data.selected !== '') {
            if (typeof getters.getMyAccountMemberDetails.banking.payment_data.bank_data !== 'undefined') {
              if (getters.getMyAccountMemberDetails.banking.payment_data.selected === 1) {
                commit(T.SET_EWALLET_SELECTED_PAYMENT_TYPE, 'bank')
                commit(
                  T.SET_EWALLET_SELECTED_BANK_INFO,
                  getters.getMyAccountMemberDetails.banking.payment_data.bank_data[0].fields
                )
              } else {
                commit(T.SET_EWALLET_SELECTED_PAYMENT_TYPE, 'mpay')
                commit(
                  T.SET_EWALLET_SELECTED_MPAY_INFO,
                  getters.getMyAccountMemberDetails.banking.payment_data.bank_data[1].fields
                )
              }
            }
          }
        }
      })
    })
    .catch(e => {
      dispatch('logError', { ewallet_loading: e })
    })
}

export const fetchCountryList = ({ commit, dispatch }) => {
  post(U.API_COUNTRIES_LIST_URL, { active: 1, limit: 0 })
    .then(response => {
      let filteredData = response.data.data.map((val, i, arr) => {
        let ret = {
          value: val.call_code,
          text: val.code_iso_2 + ' (+' + val.call_code + ')',
        }
        return ret
      })
      commit(T.SET_MOBILE_COUNTRIES_CODES, filteredData)
    })
    .catch(e => {
      dispatch('logError', { ewallet_loading: e })
    })
}

export const validateMobile = ({ commit, dispatch }, data) => {
  commit(T.SET_MOBILE_COUNTRY_CODE, data)
  commit(T.SET_EWALLET_TEMPORARY_MOBILE_PHONE, data)
  return post(U.EWALLET_MOBILE_VALIDATION, data)
    .then(response => {
      if (response.status === 200) {
        if (data.request_type === 'validate') {
          if (typeof response.data.code === 'undefined') {
            return true
          } else {
            return false
          }
        } else {
          if (response.data.response_code === 0) {
            commit(T.SET_EWALLET_MOBILE_VERIFICATION_STATUS, false)
            return true
          } else if (response.data.code === 'The code is valid') {
            commit(T.SET_EWALLET_MOBILE_VERIFICATION_STATUS, false)
            return true
          } else {
            commit(T.SET_EWALLET_MOBILE_VERIFICATION_STATUS, true)
            commit(T.SET_EWALLET_MOBILE_VERIFICATION_MESSAGE, response.data.response_msg)
            return false
          }
        }
      } else {
        commit(T.SET_EWALLET_MOBILE_VERIFICATION_STATUS, true)
        commit(T.SET_EWALLET_MOBILE_VERIFICATION_MESSAGE, response.data.response_msg)
        return false
      }
    })
    .catch(e => {
      commit(T.SET_EWALLET_MOBILE_VERIFICATION_STATUS, true)
      let errMsg = []
      if (typeof e.response.data.mobile_1_num !== 'undefined') {
        errMsg = errMsg.concat(e.response.data.mobile_1_num)
      }
      if (typeof e.response.data.code !== 'undefined') {
        errMsg = errMsg.concat(e.response.data.code)
      }
      if (typeof e.response.data.mobile_1_country_code_id !== 'undefined') {
        errMsg = errMsg.concat(e.response.data.mobile_1_country_code_id)
      }
      commit(T.SET_EWALLET_MOBILE_VERIFICATION_MESSAGE, errMsg)
      dispatch('logError', { ewallet_activation: e })
    })
}

export const setResendCode = ({ commit }, data) => {
  setTimeout(() => {
    commit(T.SET_EWALLET_RESEND_CODE, data)
  }, 7000)
}

export const setVerificationStatus = ({ commit }, data) => {
  commit(T.SET_EWALLET_MOBILE_VERIFICATION_STATUS, data)
}

export const activateMobile = ({ commit, dispatch }, data) => {
  if (data.security_pin !== data.security_pin_confirmation) {
    commit(T.SET_EWALLET_MOBILE_CONFIRMATION_STATUS, { client: true, status: true })
    return false
  }
  return post(U.EWALLET_MOBILE_ACTIVATION, data)
    .then(response => {
      if (response.status === 200 && response.data.active === 1) {
        commit(T.SET_EWALLET_MOBILE_CONFIRMATION_STATUS, { client: false, status: false })
        commit(T.SET_EWALLET_ACTIVE_STATUS, 1)
        return true
      } else {
        return false
      }
    })
    .catch(e => {
      commit(T.SET_EWALLET_MOBILE_CONFIRMATION_STATUS, { client: false, status: true })
      commit(T.SET_EWALLET_MOBILE_CONFIRMATION_MESSAGE, e.response.data.security_pin.toString())
      dispatch('logError', { ewallet_activation: e })
    })
}

export const fetchTransactionHistory = ({ commit, getters, dispatch }, data) => {
  let mData = {
    paginate: getters.getEwalletPaginationSize,
  }
  if (getters.getEwalletTabIndex === 0) {
    commit(T.SET_EWALLET_CURRENT_HISTORY_OFFSET, data.offset)
  } else {
    commit(T.SET_EWALLET_CURRENT_RECORD_OFFSET, data.offset)
  }
  return post(U.EWALLET_TRANSACTIONS, Object.assign(mData, data))
    .then(response => {
      if (response.status === 200) {
        var transactionHistory = []
        var ewalletRecord = []
        commit(T.SET_EWALLET_TOTAL_TRANSACTION_ROWS, response.data.total)
        response.data.data.forEach(item => {
          let mDebit = ''
          let mCredit = ''
          if (item.amount_type.title === 'Debit') {
            mDebit = getters.getDigitCurrency(item.amount)
            mCredit = ''
            let toAcc = ''
            let toIBO = item.transaction_details.split('-')[1]
            if (item.transaction_details !== 'Fund Withdrawal' && item.transfer_to_user !== null) {
              toAcc = item.transfer_to_user.member.country.code + item.transfer_to_user.old_member_id
              toIBO = toAcc
            }
            let mRecord = {
              transactionNumber: item.transaction_number,
              transactionDate: moment(item.transaction_date).format('YYYY-MM-DD'),
              transactionDetails: item.transaction_details,
              toAccount: toAcc,
              amount: getters.getDigitCurrency(item.amount),
              statusReference: item.transaction_status.title,
              paymentInfo: typeof item.member_payment_info === 'undefined' ? null : item.member_payment_info,
              afterBalance: item.after_balance,
              transactionTime: new Date(item.transaction_date).toLocaleTimeString(),
              transactionStatus: item.transaction_status.title,
              toOtherIbo: toIBO,
              recEmail: item.recipient_email,
              recReference: item.recipient_reference,
            }
            ewalletRecord.push(mRecord)
          } else {
            mDebit = ''
            mCredit = getters.getDigitCurrency(item.amount)
          }
          let mHistory = {
            transactionDate: item.transaction_date,
            transactionDetails: item.transaction_details,
            debit: mDebit,
            credit: mCredit,
            balance: getters.getDigitCurrency(item.after_balance),
          }
          transactionHistory.push(mHistory)
        })
        commit(T.FETCH_EWALLET_TRANSACTION_HISTORY, { history: transactionHistory, record: ewalletRecord })
      } else {
        return false
      }
    })
    .catch(e => {
      dispatch('logError', { ewallet_loading: e })
    })
}

export const fundTransferInfo = ({ commit, dispatch }, data) => {
  commit(T.SET_EWALLET_FUND_TRANSFER_INFO, data)
}

export const createNewFundTransfer = async ({ commit, getters, dispatch }, data) => {
  commit(T.PROCESSING_STARTED, 'createEwalletTransaction')
  let tempData = {
    ewallet_id: getters.getEwalletId,
    currency_id: getters.getEwalletCurrencyId,
    transaction_type_id: getters.getEwalletTransactionTypeId.transfer,
  }
  return post(U.EWALLET_NEW_TRANSACTION, Object.assign(tempData, data))
    .then(response => {
      if (response.status === 200) {
        let transStsInfo = {
          transactionStatus: getters.getEwalletTransactionStatus(response.data.transaction_status_id),
          transactionNumber: response.data.transaction_number,
          transactionDate: moment(response.data.transaction_date).format('YYYY-MM-DD'),
          transactionTime: new Date(response.data.transaction_date).toLocaleTimeString(),
          effectiveDate: moment(response.data.transaction_date).format('YYYY-MM-DD'),
        }
        commit(T.SET_EWALLET_FUND_TRANSFER_STATUS_INFO, transStsInfo)
        commit(T.SET_EWALLET_BALANCE, response.data.after_balance)
        commit(T.PROCESSING_FINISHED, 'createEwalletTransaction')
        return true
      } else {
        commit(T.SET_EWALLET_FUND_TRANSFER_STATUS, true)
        commit(T.PROCESSING_FINISHED, 'createEwalletTransaction')
        return false
      }
    })
    .catch(e => {
      commit(T.SET_EWALLET_FUND_TRANSFER_STATUS, true)
      let errMsg = []
      if (e.response.data.hasOwnProperty('security_pin')) {
        errMsg = errMsg.concat(e.response.data.security_pin)
      }
      if (e.response.data.hasOwnProperty('transfer_to_user_id')) {
        errMsg = errMsg.concat(e.response.data.transfer_to_user_id)
      }
      commit(T.SET_EWALLET_FUND_TRANSFER_MESSAGE, errMsg)
      commit(T.PROCESSING_FINISHED, 'createEwalletTransaction')
      return false
    })
}

export const checkEwalletActivation = ({ commit, getters }, data) => {
  let ret = {
    status: false,
    msg: 'undefine error',
  }
  let tempData = {
    ewallet_id: getters.getEwalletId,
    currency_id: getters.getEwalletCurrencyId,
    transaction_type_id: getters.getEwalletTransactionTypeId.transfer,
    transfer_to_user_id: data.toUserId,
    amount: data.amount,
    recipient_email: data.recipientEmail,
    recipient_reference: data.recRef,
  }
  return post(U.EWALLET_NEW_TRANSACTION, tempData)
    .then(response => {
      if (response.status === 200) {
        ret.status = true
      }
      return ret
    })
    .catch(e => {
      if (typeof e.response.data.transfer_to_user_id !== 'undefined') {
        ret.msg = e.response.data.transfer_to_user_id[0]
      } else {
        ret.status = true
      }
      return ret
    })
}

export const initializeEwalletKey = ({ commit, getters }) => {
  let transTypes = getters.getMasterDataByKey('ewallet_transaction_type')
  let mData = {
    transfer: 0,
    withdraw: 0,
    purchase: 0,
  }
  transTypes.forEach(transType => {
    if (transType.title === 'Transfer') {
      mData.transfer = transType.id
    } else if (transType.title === 'Withdraw') {
      mData.withdraw = transType.id
    } else {
      mData.purchase = transType.id
    }
  })
  commit(T.SET_EWALLET_TRANSACTION_TYPE, mData)
  let transStatus = []
  let transSts = getters.getMasterDataByKey('ewallet_transaction_status')
  transSts.forEach(item => {
    let temp = {
      id: item.id,
      title: item.title,
    }
    transStatus.push(temp)
  })
  commit(T.SET_EWALLET_TRANSACTION_STATUS, transStatus)
}

export const fundWithdrawalInfo = ({ commit }, data) => {
  commit(T.SET_EWALLET_FUND_WITHDRAWAL_INFO, data)
}

export const checkAmountFundWithdrawal = ({ commit, getters }, data) => {
  commit(T.PROCESSING_STARTED, 'amountFundWithdrawalChecking')
  let ret = {
    status: false,
    msg: 'undefine error',
  }
  let tempData = {
    ewallet_id: getters.getEwalletId,
    currency_id: getters.getEwalletCurrencyId,
    transaction_type_id: getters.getEwalletTransactionTypeId.withdraw,
    security_pin: data,
    // transfer_to_user_id: getters.getEwalletUserId,
    amount: getters.getEwalletFundWithdrawalInfo.amount,
    recipient_email: getters.getEwalletFundWithdrawalInfo.recipientEmail,
    recipient_reference: getters.getEwalletFundWithdrawalInfo.recRef,
  }
  return post(U.EWALLET_NEW_TRANSACTION, tempData)
    .then(response => {
      if (response.status === 200) {
        ret.status = true
        commit(T.PROCESSING_FINISHED, 'amountFundWithdrawalChecking')
        return ret
      }
    })
    .catch(e => {
      if (typeof e.response.data.amount !== 'undefined') {
        ret.msg = e.response.data.amount[0]
      } else {
        ret.status = true
      }
      commit(T.PROCESSING_FINISHED, 'amountFundWithdrawalChecking')
      return ret
    })
}

export const createNewFundWithdrawal = async ({ commit, getters, dispatch }, data) => {
  commit(T.PROCESSING_STARTED, 'createEwalletTransaction')
  let tempData = {
    ewallet_id: getters.getEwalletId,
    currency_id: getters.getEwalletCurrencyId,
    transaction_type_id: getters.getEwalletTransactionTypeId.withdraw,
    security_pin: data,
    // transfer_to_user_id: getters.getEwalletUserId,
    amount: getters.getEwalletFundWithdrawalInfo.amount,
    recipient_email: getters.getEwalletFundWithdrawalInfo.recipientEmail,
    recipient_reference: getters.getEwalletFundWithdrawalInfo.recRef,
  }
  return post(U.EWALLET_NEW_TRANSACTION, tempData)
    .then(response => {
      if (response.status === 200) {
        let transStsInfo = {
          transactionStatus: getters.getEwalletTransactionStatus(response.data.transaction_status_id),
          transactionNumber: response.data.transaction_number,
          transactionDate: moment(response.data.transaction_date).format('YYYY-MM-DD'),
          transactionTime: new Date(response.data.transaction_date).toLocaleTimeString(),
          effectiveDate: moment(response.data.transaction_date).format('YYYY-MM-DD'),
        }
        commit(T.SET_EWALLET_FUND_TRANSFER_STATUS_INFO, transStsInfo)
        commit(T.SET_EWALLET_BALANCE, response.data.after_balance)
        commit(T.PROCESSING_FINISHED, 'createEwalletTransaction')
        return true
      } else {
        commit(T.SET_EWALLET_FUND_TRANSFER_STATUS, true)
        commit(T.PROCESSING_FINISHED, 'createEwalletTransaction')
        return false
      }
    })
    .catch(e => {
      commit(T.SET_EWALLET_FUND_TRANSFER_STATUS, true)
      let errMsg = []
      if (e.response.data.hasOwnProperty('security_pin')) {
        errMsg = errMsg.concat(e.response.data.security_pin)
      }
      if (e.response.data.hasOwnProperty('amount')) {
        errMsg = errMsg.concat(e.response.data.amount)
      }
      if (e.response.data.hasOwnProperty('transfer_to_user_id')) {
        errMsg = errMsg.concat(e.response.data.transfer_to_user_id)
      }
      commit(T.SET_EWALLET_FUND_TRANSFER_MESSAGE, errMsg)
      commit(T.PROCESSING_FINISHED, 'createEwalletTransaction')
      return false
    })
}

export const setInsufficientFundErr = ({ commit }, data) => {
  commit(T.SET_EWALLET_INSUFFICIENT_FUND_ERR, data)
}

export const setRangeFundErr = ({ commit }, data) => {
  commit(T.SET_EWALLET_RANGE_FUND_ERR, data)
}

export const initializeBankMpaySetup = async ({ commit, getters, dispatch }, data) => {
  let userdata = await get(U.API_USER_URL).catch(error => {
    dispatch('logError', { ewalletbanksetup: error })
    return error
  })
  let inputData = {
    country_id: userdata.data.member.country_id,
    relations: ['banks'],
  }
  return post(U.API_COUNTRY_RELATION, inputData).then(response => {
    if (response.status === 200) {
      var bankInfo = []
      response.data.banks.map(item => {
        bankInfo.push({ bankId: item.id, bankName: item.name, bankSwiftCode: item.swift_code })
      })
      commit(T.SET_EWALLET_BANK_INFO, bankInfo)
    }
  })
}

export const resetEwalletState = ({ commit }) => {
  commit(T.CANCEL_FUND_STEP, 'fundFirstStep')
}

export const resetSecurityPin = ({ commit, dispatch }, data) => {
  return post(U.EWALLET_FORGOT_SECURITY_PIN, data)
    .then(response => {
      if (response.status === 200) {
        return true
      } else {
        commit(T.SET_FORGOT_SECURITY_PIN_INFO, { status: true, message: 'error' })
        return false
      }
    })
    .catch(error => {
      dispatch('logError', { securityPin: error })
      if (error.response.data.hasOwnProperty('security_pin')) {
        commit(T.SET_FORGOT_SECURITY_PIN_INFO, { status: true, message: error.response.data.security_pin.toString() })
      } else {
        commit(T.SET_FORGOT_SECURITY_PIN_INFO, { status: true, message: error.response.data.error.message })
      }
      return false
    })
}

export const fetchEwalletUserCurrency = ({ commit, getters }) => {
  let country = getters.getCountryById(getters.getMemberDetails.country_id)
  if (country !== null) {
    commit(T.SET_EWALLET_USER_CURRENCY, country.currency.code)
  }
}

export const changeAutoWithdrawalType = ({ commit, getters }, data) => {
  let temp = {
    auto_withdrawal: data,
  }
  return post(U.EWALLET_CHANGE_AUTOWITHDRAWAL_TYPE, temp)
    .then(response => {
      if (response.status === 200) {
        commit(T.SET_EWALLET_AUTOWITHDRAWAL_STATUS, response.data.auto_withdrawal)
        return true
      } else {
        return false
      }
    })
    .catch(e => {
      return false
    })
}

export const validateSecurityPin = ({ commit, dispatch }, data) => {
  let temp = {
    security_pin: data,
  }
  return post(U.EWALLET_VALIDATE_SECURITY_PIN, temp)
    .then(response => {
      return response
    })
    .catch(error => {
      dispatch('logError', { securityPin: error })
      return false
    })
}

export const setEwalletActivation0Step = ({ commit }, data) => {
  commit(T.SET_EWALLET_ACTIVATION0_STEP, data)
}

// NEW ACTIONS IMPLEMENTATION
// =====================================================================================================================
export const requestEWalletVerificationCode = async ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'requestingEWalletValidationCode')
  dispatch('removeError', 'eWalletVerificationCodeRequest')

  payload = {
    mobile_1_country_code_id: payload.countryCode,
    mobile_1_num: payload.phoneNumber,
  }

  return await post(U.EWALLET_MOBILE_VALIDATION, payload)
    .then(res => res.data.response_code === 0)
    .catch(err => {
      let errMsg = Object.values(getValue(err.response, 'data', {})).flat()
      dispatch('logError', { eWalletVerificationCodeRequest: errMsg[0] })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'requestingEWalletValidationCode')
    })
}

export const validateEWalletVerificationCode = async ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'validatingEWalletVerificationCode')
  dispatch('removeError', 'eWalletVerificationCodeValidation')

  payload = {
    mobile_1_country_code_id: payload.countryCode,
    mobile_1_num: payload.phoneNumber,
    code: payload.verificationCode,
    request_type: (payload.activation && 'activate') || 'validate',
  }

  return await post(U.EWALLET_MOBILE_VALIDATION, payload)
    .then(res => {
      let { code, message } = res.data
      return (
        (payload.request_type === 'activate' && code === 'The code is valid') ||
        (payload.request_type === 'validate' && message === 'Mobile Number Validated.')
      )
    })
    .catch(err => {
      let errMsg = Object.values(getValue(err.response, 'data', {})).flat()
      dispatch('logError', { eWalletVerificationCodeValidation: errMsg[0] })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'validatingEWalletVerificationCode')
    })
}

export const setEWalletSecurityPin = async ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'UpdatingEWalletSecurityPin')
  dispatch('removeError', 'setEWalletPin')

  let endPoint = (payload.activation && U.EWALLET_MOBILE_ACTIVATION) || U.EWALLET_FORGOT_SECURITY_PIN
  payload = {
    security_pin: payload.securityPin,
    security_pin_confirmation: payload.reConfirmSecurityPin,
  }

  return await post(endPoint, payload)
    .then(res => res.data.active === 1)
    .catch(err => {
      let errMsg = Object.values(getValue(err.response, 'data', {})).flat()
      dispatch('logError', { setEWalletPin: errMsg[0] })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'UpdatingEWalletSecurityPin')
    })
}

export const loadEWalletDetails = async ({ commit, getters, dispatch }) => {
  commit(T.PROCESSING_STARTED, 'loadingEWalletDetails')
  dispatch('removeError', 'eWalletDetails')

  return await get(U.EWALLET_HOME)
    .then(async res => {
      let data = { ...res.data }
      commit(T.SET_EWALLET_DETAILS, data)
      await dispatch('loadMyAccountInfo').then(res => {
        if (res) {
          // TODO: get bank data here
        }
      })
      return data
    })
    .catch(err => {
      commit(T.SET_EWALLET_DETAILS, {})
      dispatch('logError', { eWalletDetails: err })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingEWalletDetails')
    })
}

export const loadEWalletTransactionRecords = async ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'loadEWalletTransactionRecord')
  dispatch('removeError', 'eWalletTransactionRecord')

  let cancelToken = await dispatch('generateCancelToken', 'eWalletTransactionRecord')
  payload = {
    offset: payload.offset,
    to_date: payload.toTargetDate,
    from_date: payload.fromTargetDate,
    paginate: payload.perPage,
    amount_type: payload.amountType,
  }

  return await post(U.EWALLET_TRANSACTIONS, payload, cancelToken.token)
    .then(res => res.data)
    .catch(err => {
      dispatch('logError', { eWalletTransactionRecord: err })
      return { data: [], total: 0 }
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadEWalletTransactionRecord')
    })
}

export const createEWalletTransaction = async ({ commit, getters, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'creatingEWalletTransaction')
  dispatch('removeError', 'createEWalletTransaction')

  let finalPayload = {
    amount: payload.amount,
    security_pin: payload.securityPin,
    recipient_email: payload.recipientEmail,
    transaction_type_id: payload.transactionTypeId,
    recipient_reference: payload.recipientReference,
    currency_id: getters.getEWalletDetails.default_currency_id,
  }

  if (payload.hasOwnProperty('transferToUserId')) {
    finalPayload['transfer_to_user_id'] = payload.transferToUserId
  }

  return await post(U.EWALLET_NEW_TRANSACTION, finalPayload)
    .then(res => res.data)
    .catch(err => {
      let errMsg = Object.values(getValue(err.response, 'data', {})).flat()
      dispatch('logError', { createEWalletTransaction: errMsg[0] })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'creatingEWalletTransaction')
    })
}

export const cancelFundWithdrawalRequest = async ({ commit, dispatch }, payload) => {
  commit(T.PROCESSING_STARTED, 'submittingCancelFundWithdrawalRequest')
  dispatch('removeError', 'cancelFundWithdrawal')

  payload = { user_ewallet_transaction_id: payload.transactionId }

  return await post(U.EWALLET_CANCEL_FUND_WITHDRAWAL, payload)
    .then(res => res.data && res.data.success)
    .catch(err => {
      let errMsg = Object.values(getValue(err.response, 'data', {})).flat()
      dispatch('logError', { cancelFundWithdrawal: errMsg[0] })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'submittingCancelFundWithdrawalRequest')
    })
}

export const loadEWalletTransactionDetails = async ({ commit, dispatch }, transactionId) => {
  commit(T.PROCESSING_STARTED, 'loadingTransactionDetails')
  dispatch('removeError', 'loadTransactionDetails')

  return await get(U.EWALLET_TRANSACTIONS_DETAILS + transactionId)
    .then(res => res.data)
    .catch(err => {
      dispatch('logError', { loadTransactionDetails: err })
      return false
    })
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingTransactionDetails')
    })
}
