<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="user in data"
              :key="user.id"
              :to="`/access-log/${user.id}`"
              :title="$t('accessLog')"
              clickable>
              <q-item-section>
                <q-item-label>{{user.nickname}}</q-item-label>
                <q-item-label caption>#{{user.id}}</q-item-label>
                <q-item-label caption>{{user.name}}</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: 'Users',
  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 {
        let like = { like: `%${this.search}%` }
        where = {
          or: [
            { name: like },
            { nickname: like }
          ]
        }
      }

      return {
        url: 'Accounts',
        filter: {
          fields: ['id', 'nickname', 'name', 'active'],
          order: 'name',
          where
        }
      }
    }
  }
}
</script>
