<template>
  <div class="vn-pp row justify-center">
    <toolbar>
      <q-input
        v-model="search"
        debounce="500"
        dark
        dense
        standout>
        <template v-slot:append>
          <q-icon
            v-if="search === ''"
            name="search"/>
          <q-icon
            v-else
            name="clear"
            class="cursor-pointer"
            @click="search = ''"/>
        </template>
      </q-input>
    </toolbar>
    <div>
      <lb-scroll
        ref="scroll"
        :request="request"
        @data="data = arguments[0]">
        <q-card class="vn-w-md">
          <q-list bordered separator>
            <q-item
              v-for="item in data"
              :key="item.id"
              clickable>
              <q-item-section avatar>
                <q-avatar>
                  <img :src="`${$imageBase}/catalog/200x200/${item.image}`">
                </q-avatar>
              </q-item-section>
              <q-item-section>
                <q-item-label>{{item.longName}}</q-item-label>
                <q-item-label caption>#{{item.id}}</q-item-label>
                <q-item-label caption>{{item.image}}</q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-card>
      </lb-scroll>
    </div>
  </div>
</template>

<script>
import Page from 'components/Page'

export default {
  name: 'Items',
  mixins: [Page],
  data () {
    return {
      search: ''
    }
  },
  beforeRouteUpdate (to, from, next) {
    next()
    this.$refs.scroll.reload()
  },
  watch: {
    search (value) {
      let query
      if (value) query = { search: value }
      this.$router.push({ query })
    }
  },
  methods: {
    request () {
      this.search = this.$route.query.search || ''
      if (!this.search) return null

      let where = {}

      if (/^[0-9]+$/.test(this.search)) {
        where.id = this.search
      } else {
        where.longName = { like: `%${this.search}%` }
      }

      return {
        url: 'Items',
        filter: {
          fields: ['id', 'longName', 'image'],
          order: 'name',
          where
        }
      }
    }
  }
}
</script>
