<template>
  <div class="table-container">
    <b-row>
      <b-col v-if="lengthChange" md="4" class="mb-3">
        <b-form inline>
          <label class="mr-2">Show</label>
          <b-form-select v-model="perPage" :options="pageOptions" class="mr-2" @input="onContextChanged" />
          <label>entries per page</label>
        </b-form>
      </b-col>
    </b-row>
    <slot />
    <b-row>
      <b-col md="4" class="mx-auto">
        <b-pagination v-if="paging && totalRows > perPage" v-model="currentPage" :total-rows="totalRows" :per-page="perPage"
                      class="justify-content-center" @input="onContextChanged"
        />
      </b-col>
    </b-row>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Datatable',
  props: {
    lengthChange: {
      type: Boolean,
      default: true
    },
    paging: {
      type: Boolean,
      default: true
    },
    infos: {
      type: Boolean,
      default: true
    },
    searchRoute: {
      type: String,
      default: null
    }
  },
  data () {
    return {
      currentPage: 1,
      perPage: 10,
      totalRows: 0,
      pageOptions: [5, 10, 15, 25, 50],
      searchQuery: null,
      selected: [],
      action: null
    }
  },
  mounted () {
    if (this.actions) {
      this.action = Object.keys(this.actions)[0]
    }
  },
  methods: {
    onContextChanged () {
      this.$emit('context-changed')
    },
    async loadData (sortBy, sortDesc) {
      try {
        const { data } = await axios.get(this.searchRoute, {
          params: {
            page: this.currentPage,
            perPage: this.perPage,
            column: sortBy,
            direction: sortDesc ? 'desc' : 'asc'
          }
        })
        this.totalRows = data.total
        return data.data
      } catch (e) {
        console.error(e)
        return []
      }
    }
  }
}
</script>
