<template>
  <q-page padding>
    <h4 class="q-mt-none">{{category.name}}</h4>
    <q-table
      flat
      bordered
        :title="category.name"
        :rows="items"
        :columns="dynamicColumns"
        v-model:pagination="pagination"
        row-key="ref"
        @update:pagination="updatePaginationUrl"
    >

    <template v-slot:top>
      <div class="full-width">
        <q-toggle v-model="showDeleted"
                  label="Voir items supprimés"
                  class="q-mr-md float-right"
        />
        <q-input
          borderless
          clearable
          dense
          icon="search"
          color="secondary"
          v-model="search"
          class="col-6"
          @update:model-value="updateSearchUrl"
          placeholder="Search"
        >
          <template v-slot:prepend>
            <q-icon name="search" color="secondary" />
          </template>
        </q-input>
      </div>
    </template>

      <template v-slot:body="props">
        <q-tr
          :props="props"
          @click="goToDetail(props)"
          :class="{'cursor-pointer': true, 'text-red': props.row.deleted}">
          <q-td v-for="col in props.cols" :key="col.ref">
            <div v-if="col.name === 'available'" class="text-center text-h6">
              <span v-if="col.value" class="text-green">✔</span>
              <span v-else class="text-red">✘</span>
            </div>
            <div v-else-if="col.name === 'working'" class="text-center text-h6">
              <span v-if="col.value" class="text-green">✔</span>
              <span v-else class="text-red">✘</span>
            </div>
            <div v-else-if="col.name === 'deleted'" class=" text-center text-h6">
              <span v-if="col.value" class="text-red">✘</span>
            </div>
            <div v-else-if="col.name === 'state'" class="text-center text-h6">
              <q-chip small :color="stateColor(col.value)" :title="col.value"></q-chip>
            </div>
            <span v-else>
          {{ col.value }}
        </span>
          </q-td>
        </q-tr>
      </template>

    </q-table>
  </q-page>
</template>

<script>
import { debounce } from 'quasar'

export default {
  name: 'StockItems',
  props: ['categoryCode'],
  data () {
    return {
      search: null,
      showDeleted: false,
      pagination: {
        sortBy: null,
        descending: false,
        page: 1,
        rowsPerPage: 15
      },
      columns: [
        { label: 'Référence', align: 'left', field: 'ref', sortable: true, name: 'ref' },
        { label: 'Nom', align: 'left', field: 'name', sortable: true, name: 'name' },
        { label: 'Etat', align: 'center', field: 'state', sortable: true, name: 'state' },
        { label: 'Fonctionnel', align: 'center', field: 'working', sortable: true, name: 'working' },
        { label: 'En stock', align: 'center', field: 'available', sortable: true, name: 'available' },
        { label: 'Propriétaire', align: 'left', field: 'owner', sortable: true, name: 'owner' },
        { label: 'Supprimé', align: 'left', field: 'deleted', sortable: false, name: 'deleted', format: val => val ? '✔' : '' }
      ]
    }
  },
  created () {
    if (!this.search) this.search = this.$route.query.search || null
    let paginationQuery = { ...this.$route.query }
    delete paginationQuery.search
    this.pagination = { ...this.pagination, ...paginationQuery }
    console.log('__Pagination:', this.pagination)
  },
  computed: {
    dynamicColumns () {
      let columns = JSON.parse(JSON.stringify(this.columns))
      if (!this.showDeleted) columns.pop()
      return columns
    },
    category () {
      return this.$store.state.core.firebase.categories.find(item => {
        return parseInt(item.code) === parseInt(this.categoryCode)
      }) || {}
    },
    items () {
      let items = this.$store.state.core.firebase.stock.filter(item => {
        return item.type === this.category.name &&
            (this.search ? (item.ref + (item.name + '').toLowerCase()).search(this.search.toLowerCase()) !== -1 : true) &&
            (this.showDeleted ? true : !item.deleted)
      }).slice().reverse() || []
      if (this.pagination.sortBy) {
        console.log('__Sorting:', this.pagination)
        return [...items].sort((a, b) => {
          const x = this.pagination.descending ? b : a
          const y = this.pagination.descending ? a : b
          return x[this.pagination.sortBy] > y[this.pagination.sortBy]
        })
      }
      return items
    }
  },
  methods: {
    goToDetail (data) {
      this.$router.push(`/item/${data.key}`)
    },
    stateColor (state) {
      let colors = {
        Neuf: 'green-14',
        Excellent: 'green-12',
        Bon: 'lime-13',
        Moyen: 'orange',
        Abimé: 'red',
        Inutilisable: 'black'
      }
      return colors[state]
    },
    updateSearchUrl: debounce(function () {
      this.$router.replace({ path: this.$router.path, query: { ...this.$route.query, search: this.search } })
    }, 300),
    updatePaginationUrl: debounce(function () {
      this.$router.replace({
        path: this.$router.path,
        query: {
          ...this.$route.query,
          ...this.pagination
        }
      })
    }, 300)
  }
}
</script>

<style>
</style>
