<template>
  <div class="all-reservations-listing">
    <Banner :back="backLink" page="all-reservations" />

    <TemplateContainer>
      <filters-container
        :id="filterId"
        :filters="filters"
        @onFiltersChange="filterChange"
      />

      <table-listing
        :id="listingId"
        :fields="requestFields"
        :filters="requestFilters"
        :headers="headers"
        :rows="scaffoldRows"
        :filter-id="filterId"
        :on-row-click="openModal"
        :selectable="false"
        :mass-actions="massActions"
        endpoint="reservations/list/index"
      />
    </TemplateContainer>
  </div>
</template>

<script>
import moment from 'moment'
import checkRolesMixin from '../../mixins/check-roles-mixin'

import Banner from '@inside-commons/components/lib/Banner'
import TemplateContainer from '@inside-commons/components/lib/TemplateContainer'

import { http } from '@inside-library/helpers/Http'

export default {
  name: 'ReservationsListingPage',
  $_i18nRootPath: 'customs.RESERVATIONS.LISTING',
  components: { Banner, TemplateContainer },
  mixins: [checkRolesMixin],
  data() {
    return {
      dateFilterValue:
        this.getCheckedData(this.$route, ['query', 'date']) ||
        this.getCheckedData(this.$route, ['query', 'day']),
      filterId: 'reservations-listing-filters',
      listingId: 'reservations-listing'
    }
  },
  computed: {
    defaultDateFilterValue() {
      if (this.isAlive(this.$route, ['query', 'date'])) {
        return new Date(
          this.getCheckedData(this.$route, ['query', 'date']) * 1000
        )
      }

      return new Date()
    },
    filters() {
      return [
        {
          modelName: 'day',
          type: 'day',
          defaultValue: this.defaultDateFilterValue,
          filterOn: 'date',
          equality: '',
          clearButton: false,
          label: this.$_tr('filters.day')
        },
        {
          modelName: 'room',
          type: 'selectbox',
          fetch: true,
          reference: 'rooms',
          callback: value => ({ room_uuid: value }),
          fields: ['uuid', 'title'],
          objectLabelKey: 'title',
          objectValueKey: 'uuid',
          filters: { sort: 'title:asc' },
          label: this.$_tr('filters.room')
        }
      ]
    },
    headers() {
      return [
        { value: this.$_tr('headers.title'), sortable: true, key: 'title' },
        { value: this.$_tr('headers.author') },
        { value: this.$_tr('headers.day') },
        { value: this.$_tr('headers.startTime') },
        { value: this.$_tr('headers.endTime') },
        { value: this.$_tr('headers.room') }
      ]
    },
    massActions() {
      return this.$_checkRoles([
        'super_administrator',
        'catering_services_team'
      ])
        ? [
            {
              id: 'exportReservations',
              icon: 'export',
              callback: async (fields, vm) => {
                try {
                  await http.post(
                    'reservations/export',
                    {},
                    {
                      onSuccess: () => {
                        vm.$_triggerToast({
                          type: 'success',
                          text: vm.$_tr('exportAllReservations.success'),
                          duration: 4000
                        })
                      },
                      onError: () => {
                        vm.$_triggerToast({
                          type: 'error',
                          text: vm.$_tr('exportAllReservations.error'),
                          duration: 3000
                        })
                      }
                    }
                  )
                } catch (err) {
                  throw new Error(err)
                }
              }
            }
          ]
        : []
    },
    requestFields() {
      return [
        'uuid',
        'title',
        'start_date',
        'end_date',
        { rooms: { fields: ['title'] } },
        'admin',
        'content_type'
      ]
    },
    requestFilters() {
      return { sort: 'start_date:asc', limit: 15, paginate: 1 }
    },
    backLink() {
      return {
        title: this.$_tr('back'),
        href: {
          name: 'RoomReservationPage',
          query: { date: this.unixDate(this.dateFilterValue) }
        }
      }
    }
  },
  methods: {
    filterChange(filters) {
      const date = this.getCheckedData(filters, [0, 'value', 0])

      this.dateFilterValue = date
    },
    unixDate(date) {
      return moment(date).format('X')
    },
    scaffoldRows(fields) {
      return [
        { value: fields.title },
        { value: this.$_username(fields.authors) },
        {
          tag: 'date-ui',
          data: { date: this.unixDate(this.dateFilterValue) }
        },
        { tag: 'date-ui', data: { date: fields.start_date, format: 'LT' } },
        { tag: 'date-ui', data: { date: fields.end_date, format: 'LT' } },
        { value: fields.rooms.title }
      ]
    },
    openModal(item) {
      this.triggerModal(
        'reservation',
        'fetch',
        {
          item,
          content: 'rooms_reservations',
          filters: {
            date: this.dateFilterValue,
            uuid: item.uuid
          }
        },
        {
          layout: 'right',
          width: '650px',
          transition: 'fadeInLeft',
          listingId: this.listingId,
          date: this.dateFilterValue
        }
      )
    }
  }
}
</script>

<style lang="scss">
.all-reservations-listing {
  .listing-item {
    .cell {
      .status {
        &.todo {
          color: var(--color-warn);
        }

        &.ready {
          color: var(--color-valid);
        }
      }
    }
  }

  .filter-item-container {
    max-width: 300px;

    &.input-day {
      flex: 0;
    }
  }
}
</style>
