<template>
  <div v-if="getEwalletStatus === 1" class="ewallet-main-container">
    <div class="ewallet-balance row justify-content-between">
      <section class="ewallet-balance-info">
        <span class="ewallet-balance-label"> {{ $t('EWallet.EWalletBalance') }} </span><br />
        <span class="ewallet-balance-content">
          {{ getEWalletBalance }}
        </span>
      </section>
      <section class="ewallet-balance-process">
        <b-btn
          v-b-modal.fundwithdrawal-modal
          class="ewallet-withrdawal-gradient"
          @click="checkPayment('fundwithdrawal')"
        >
          {{ $t('EWallet.FundWithdrawal') }}
        </b-btn>
        <b-btn v-b-modal.transfer class="ewallet-transfer-gradient" @click="processFund('fundtransfer')">
          {{ $t('EWallet.FundTransfer') }}
        </b-btn>
      </section>
      <bankMpayModal />
    </div>
    <div class="row">
      <b-tabs class="ewallet-table-wrapper" v-model="tabIndex" @input="tabChanged(tabIndex)">
        <b-tab :title="$t('EWallet.TransactionHistory')" :title-link-class="'tab-ewallet-title'">
          <div class="ewallet-transaction-history-table">
            <EWalletDateTimePicker />
            <table class="table table-striped table-hover">
              <thead class="text-light">
                <tr class="bg-secondary">
                  <th class="pl-3">
                    {{ $t('Common.Sales.TransactionDate') }}
                  </th>
                  <th class="ewallet-table-left">
                    {{ $t('Common.Sales.TransactionDetails') }}
                  </th>
                  <th class="ewallet-table-style">
                    {{ $t('EWallet.TransactionHistory.TableHeader.Debit', { currency: currency }) }}
                  </th>
                  <th class="ewallet-table-style">
                    {{ $t('EWallet.TransactionHistory.TableHeader.Credit', { currency: currency }) }}
                  </th>
                  <th class="text-right">
                    {{ $t('EWallet.TransactionHistory.TableHeader.Balance', { currency: currency }) }}
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr
                  class="ewallet-table-row"
                  v-for="(transaction, transactionIndex) in getTransactionHistory"
                  :key="transactionIndex"
                >
                  <td>{{ transaction.transactionDate }}</td>
                  <td class="ewallet-table-left">
                    {{ transaction.transactionDetails }}
                  </td>
                  <td class="text-right">
                    {{ transaction.debit }}
                  </td>
                  <td class="text-right">
                    {{ transaction.credit }}
                  </td>
                  <td class="text-right">
                    {{ transaction.balance }}
                  </td>
                </tr>
              </tbody>
            </table>
            <b-pagination
              align="center"
              :total-rows="getTotalTransactionRows"
              v-model="currentPageHistory"
              @change="handlePaginationChange"
              :per-page="getEwalletPaginationSize"
            />
          </div>
        </b-tab>
        <b-tab :title="$t('EWallet.EWalletRecord')" :title-link-class="'tab-ewallet-title'">
          <div class="ewallet-transaction-history-table pt-3">
            <EWalletDateTimePicker />
            <table class="table table-striped table-hover">
              <thead class="text-light">
                <tr class="bg-secondary">
                  <th class="pl-3">
                    {{ $t('Common.Sales.TransactionDate') }}
                  </th>
                  <th>{{ $t('Common.Sales.TransactionDetails') }}</th>
                  <th>{{ $t('EWallet.EWalletRecord.TableHeader.ToAccount') }}</th>
                  <th class="text-right">
                    {{ $t('EWallet.Amount', { currency: currency }) }}
                  </th>
                  <th>{{ $t('EWallet.EWalletTransferRecord.TableHeader.StatusReference') }}</th>
                  <th />
                </tr>
              </thead>
              <tbody>
                <tr
                  class="ewallet-table-row"
                  v-for="(transaction, transactionIdx) in getEWalletRecord"
                  :key="transactionIdx"
                >
                  <td>{{ transaction.transactionDate }}</td>
                  <td>{{ transaction.transactionDetails }}</td>
                  <td>{{ transaction.toAccount }}</td>
                  <td class="text-right">
                    {{ transaction.amount }}
                  </td>
                  <td>
                    <label
                      :class="{
                        'text-warning': transaction.statusReference === 'In Process',
                        'text-info-green': transaction.statusReference === 'Successful',
                      }"
                    >
                      {{ transaction.statusReference }}
                    </label>
                    <br />
                    {{ transaction.transactionNumber }}
                  </td>
                  <td class="row-blue">
                    <button class="btn btn-secondary" v-if="transaction.recReference === 'EWallet Purchase'" disabled>
                      {{ $t('EWallet.GlobalWords.Reprint') }}
                    </button>
                    <button class="btn btn-primary" v-else @click="handleReprint(transaction)">
                      {{ $t('EWallet.GlobalWords.Reprint') }}
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
            <b-pagination
              align="center"
              :total-rows="getTotalTransactionRows"
              v-model="currentPageRecord"
              @change="handlePaginationChange"
              :per-page="getEwalletPaginationSize"
            />
          </div>
        </b-tab>
      </b-tabs>
    </div>
  </div>
</template>
<script>
import EWalletDateTimePicker from './blocks/EWalletDateTimePicker'
import bankMpayModal from './blocks/BankMPayModal'
import router from '@/router'
import { EWALLET_ACTIVATION, EWALLET_REPRINT_PAGE } from '@/config/url-prefix'
import { mapGetters, mapMutations, mapActions } from 'vuex'
import { EWALLET_PRINT_KEY } from '@/store/utils/localStorageKeys'
import { CurrencyMixin } from '@/app/_global/mixins'
import _ from 'lodash'
/**
 * Dashboard Home
 */
export default {
  name: 'EWallet',
  components: {
    EWalletDateTimePicker,
    bankMpayModal,
  },
  mixins: [CurrencyMixin],
  data() {
    return {
      from: '',
      to: '',
      paymentType: {
        type: 'mBankComponent',
      },
      options: [
        { text: 'BANK', value: 'mBankComponent', selected: true },
        { text: 'MPAY', value: 'mPayComponent' },
      ],
      tabIndex: 0,
      currentPageHistory: 1,
      currentPageRecord: 1,
      printStatus: false,
      reprintObject: null,
    }
  },
  mounted() {
    this.loadEwalletBalance().then(() => {
      if (this.getEwalletStatus === 0) {
        router.push(EWALLET_ACTIVATION)
      }
    })
    this.fetchTransactionHistory({ from_date: null, to_date: null, offset: 0 })
    this.initializeEwalletKey()
    this.resetEwalletState()
    this.fetchEwalletUserCurrency()
    this.SET_EWALLET_SHOW_MODAL(false)
  },
  methods: {
    ...mapActions([
      'processFund',
      'loadEwalletBalance',
      'fetchTransactionHistory',
      'initializeEwalletKey',
      'resetEwalletState',
      'fetchEwalletUserCurrency',
      'setPrintData',
    ]),
    ...mapMutations(['SET_EWALLET_SHOW_MODAL', 'SET_EWALLET_SHOW_MODAL_PROCESS_TYPE', 'SET_EWALLET_TAB_INDEX']),
    handleReprint(historyObject) {
      // Handle reprint
      this.reprintObject = _.cloneDeep(historyObject)
      if (historyObject.paymentInfo !== null) {
        if (typeof historyObject.paymentInfo === 'string') {
          this.reprintObject.paymentInfo = JSON.parse(historyObject.paymentInfo)
        } else {
          this.reprintObject.paymentInfo = historyObject.paymentInfo
        }
        // Process bank info here if any
        if (this.reprintObject.paymentInfo.selected === 1) {
          // bank
          let bankId = null
          let bankData = {
            bankName: '',
            accountName: '',
            accountNumber: '',
          }
          this.reprintObject.paymentInfo.bank_data[0].fields.forEach(item => {
            switch (item.label) {
              case 'Bank Name':
                bankId = item.value
                break
              case 'A/C Holder Name':
                bankData.accountName = item.value
                break
              case 'Bank Account No':
                bankData.accountNumber = item.value
                break
              default:
            }
          })
          if (bankId !== null) {
            bankData.bankName = this.getBankName(bankId)
          }
          this.reprintObject.paymentInfo = {
            selected: 1,
            bankData,
          }
        } else {
          let month = ''
          let year = ''
          // card
          let cardData = {
            cardHolderName: '',
            cardNumber: '',
            cardExpDate: '',
          }
          this.reprintObject.paymentInfo.bank_data[1].fields.forEach(item => {
            switch (item.label) {
              case 'Card Holder Name':
                cardData.cardHolderName = item.value
                break
              case 'Card Number':
                cardData.cardNumber = item.value
                break
              case 'Card Expiry Date':
                if (item.share.index === 5) {
                  month = item.value
                } else {
                  year = item.value
                }
                break
              case 'Card Expiry Year':
                item.options.forEach(yer => {
                  if (yer.value === item.value) {
                    year = yer.label
                  }
                })
                break
              default:
            }
          })
          cardData.cardExpDate = year + ' - ' + month
          this.reprintObject.paymentInfo = {
            selected: 2,
            cardData,
          }
        }
      }
      this.reprintObject.from = this.getIboId + ' ' + this.getUserName
      this.setPrintData({ key: EWALLET_PRINT_KEY, data: this.reprintObject })
      window.open(EWALLET_REPRINT_PAGE, '_blank')
    },
    checkPayment(processType) {
      if (this.getEwalletSelectedPayment === '') {
        this.SET_EWALLET_SHOW_MODAL(true)
        this.SET_EWALLET_SHOW_MODAL_PROCESS_TYPE(processType)
      } else {
        this.processFund(processType)
      }
    },
    tabChanged(tin) {
      this.SET_EWALLET_TAB_INDEX(tin)
      if (tin === 0) {
        this.fetchTransactionHistory({
          from_date: this.getEwalletHistoryDate.from,
          to_date: this.getEwalletHistoryDate.to,
          offset: this.getCurrentHistoryOffset,
        })
      } else {
        this.fetchTransactionHistory({
          from_date: this.getEwalletRecordDate.from,
          to_date: this.getEwalletRecordDate.to,
          offset: this.getCurrentRecordOffset,
        })
      }
    },
    handlePaginationChange(page) {
      let currOffset = this.getEwalletPaginationSize * (page - 1)
      if (this.getEwalletTabIndex === 0) {
        // Transaction History
        this.fetchTransactionHistory({
          from_date: this.getEwalletHistoryDate.from,
          to_date: this.getEwalletHistoryDate.to,
          offset: currOffset,
        })
      } else {
        // Record History
        this.fetchTransactionHistory({
          from_date: this.getEwalletRecordDate.from,
          to_date: this.getEwalletRecordDate.to,
          offset: currOffset,
        })
      }
    },
    cancelActivation() {
      router.go(-1)
    },
  },
  computed: {
    ...mapGetters([
      'getTransactionHistory',
      'getEWalletRecord',
      'getEWalletBalance',
      'getEWalletBankAccountNumber',
      'getEwalletUserCurrency',
      'getEwalletTabIndex',
      'getEwalletPaginationSize',
      'getEwalletHistoryDate',
      'getTotalTransactionRows',
      'getEwalletRecordDate',
      'getCurrentHistoryOffset',
      'getCurrentRecordOffset',
      'getEwalletSelectedPayment',
      'getEwalletStatus',
      'getBankName',
      'getIboId',
      'getUserName',
    ]),
  },
}
</script>
