<template>
  <table-listing
    id="restaurants-credits-management-listing"
    :fields="requestFields"
    :filters="requestFilters"
    :use-infinite-scroll="true"
    :headers="headers"
    :rows="scaffoldRow"
    :on-row-click="handleRowClick"
    endpoint="content/users"
  />
</template>

<script>
import { markRaw } from 'vue'

import AvatarUsernameUsers from '@inside-users/displays/AvatarUsernameUsers'

export default {
  name: 'CreditsListing',
  components: {
    AvatarUsernameUsers
  },
  data() {
    return {
      requestFields: [
        'uuid',
        'firstname',
        'lastname',
        'credits',
        'content_type'
      ],
      requestFilters: {
        'status:eq': 1,
        'is_maintenance:eq': 0,
        offset: 0,
        sort: 'lastname:asc'
      }
    }
  },
  computed: {
    headers() {
      return [
        { value: 'User', sortable: true, sortableKey: 'lastname' },
        { value: 'Credits', sortable: true }
      ]
    }
  },
  methods: {
    scaffoldRow(fields) {
      return [
        {
          tag: markRaw(AvatarUsernameUsers),
          data: { user: fields }
        },
        {
          value: `${fields.credits || '0'}€`
        }
      ]
    },
    async handleRowClick(fields) {
      try {
        const res = await this.get('content/dishes_orders', {
          params: {
            fields: JSON.stringify(['number', 'order', 'uuid', 'date', 'cost']),
            filters: JSON.stringify({
              limit: 5,
              'sort:desc': 'date',
              authors: {
                'uuid:eq': fields.uuid
              }
            })
          }
        })
        const { data } = await res.json()

        this.triggerModal(
          'restaurants-credits',
          'static',
          { item: { ...fields, orders: data } },
          { layout: 'right', width: 550, transition: 'fadeInLeft' }
        )
      } catch (err) {
        throw new Error(err)
      }
    }
  }
}
</script>
