<template>
  <v-container>
    <div v-if="this.formState.ready">
      <v-col cols="12" mt-1 mb-2 v-if="formState.errorBoxMessage">
        <v-alert
          ref="errorbox"
          v-show="formState.errorBoxMessage"
          color="error"
          icon="fa-exclamation-circle "
          transition="scale-transition"
          class="multi-line"
          outlined
          >{{ formState.errorBoxMessage }}</v-alert
        >
      </v-col>
      <v-col cols="12">
        <div class="elevation-5" v-if="this.formState.ready">
          <v-toolbar flat>
            <v-toolbar-title>
              <v-icon large color="primary">fa-splotch</v-icon>
              <span class="hidden-sm-and-down">{{ lt("WidgetList") }}</span>
            </v-toolbar-title>
            <v-spacer></v-spacer>
            <v-btn v-if="this.rights.change" icon @click="newItem()">
              <v-icon>fa-plus-circle</v-icon>
            </v-btn>
            <v-btn icon @click="filterMe()">
              <v-icon>fa-filter</v-icon>
            </v-btn>
            <v-btn icon @click="getDataFromApi()">
              <v-icon>fa-sync</v-icon>
            </v-btn>
            <v-btn icon>
              <v-icon>fa-ellipsis-v</v-icon>
            </v-btn>
          </v-toolbar>
          <v-data-table
            v-model="selected"
            :headers="headers"
            :items="Items"
            item-key="id"
            :options.sync="localFormSettings.pagination"
            :server-items-length="totalItems"
            :loading="loading"
            show-select
            class="elevation-1"
            :footer-props="{
              itemsPerPageOptions: rowsPerPageItems,
              itemsPerPageText: lt('RowsPerPage')
            }"
          >
            <template slot="item" slot-scope="props">
              <tr>
                <td>
                  <v-checkbox
                    v-model="props.selected"
                    primary
                    hide-details
                  ></v-checkbox>
                </td>
                <td class="text-xs-left" @click="editItem(props.item)">
                  {{ props.item.name }}
                </td>
                <td class="text-xs-left" @click="editItem(props.item)">
                  {{ props.item.serial }}
                </td>
                <td class="text-xs-left" @click="editItem(props.item)">
                  {{ props.item.dollarAmount | currency }}
                </td>
                <td class="text-xs-left" @click="editItem(props.item)">
                  {{ props.item.active | boolastext }}
                </td>
                <td class="text-xs-left" @click="editItem(props.item)">
                  {{ props.item.roles }}
                </td>
                <td class="text-xs-left" @click="editItem(props.item)">
                  {{ props.item.startDate | shortdatelocalized }}
                </td>
                <td class="text-xs-left" @click="editItem(props.item)">
                  {{ props.item.endDate | shortdatelocalized }}
                </td>
              </tr>
            </template>
          </v-data-table>
        </div>
      </v-col>
    </div>
  </v-container>
</template>

<script>
/*  Xeslint-disable */
const FORM_KEY = "inventorywidgetlist";

export default {
  beforeCreate() {
    var that = this;

    window.$gz.locale
      .fetch([
        "Widget",
        "WidgetList",
        "WidgetName",
        "WidgetSerial",
        "WidgetDollarAmount",
        "Active",
        "WidgetRoles",
        "WidgetStartDate",
        "WidgetEndDate",
        "WidgetNotes",
        "RowsPerPage"
      ])
      .then(() => {
        window.$gz._.forEach(that.headers, function setHeaderLocalizedText(
          header
        ) {
          header.text = window.$gz.locale.get(header.text);
        });
      })
      .then(() => {
        //don't have access to local data object until here
        that.rights = window.$gz.role.getRights(window.$gz.type.Widget);
        var formSettings = window.$gz.form.getFormSettings(FORM_KEY);
        /**
 * {
          temp: { page: that.localFormSettings.pagination.page },
          saved: {
            rowsPerPage: that.localFormSettings.pagination.rowsPerPage,
            sortBy: that.localFormSettings.pagination.sortBy,
            descending: that.localFormSettings.pagination.descending
          }
        }
//NEW VUETIFY 2.x options object
source code is looking for these props
this.options.sortBy
this.options.sortDesc[sortIndex]
this.options.multiSort

Actual in inspector browser code:
{"page":2,"itemsPerPage":99,"sortBy":["serial"],"sortDesc":[true],"groupBy":[],"groupDesc":[],"mustSort":false,"multiSort":false,"rowsPerPage":5,"descending":false}


 */
        //set default values for form settings if they are not present yet
        if (!formSettings.saved || !formSettings.saved.itemsPerPage) {
          that.localFormSettings = {
            pagination: {}
          };
        } else {
          that.localFormSettings.pagination = {
            itemsPerPage: formSettings.saved.itemsPerPage,
            sortBy: [formSettings.saved.sortBy],
            descending: formSettings.saved.descending
          };
          if (formSettings.temp && formSettings.temp.page) {
            that.localFormSettings.pagination.page = formSettings.temp.page;
          }
        }

        that.formState.ready = true;
      })
      .catch(err => {
        that.formState.ready = true; //show the form anyway so we know what's what
        window.$gz.errorHandler.handleFormError(err);
      });
  },
  data() {
    return {
      formState: {
        ready: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject(),
      totalItems: 0,
      Items: [],
      loading: true,
      localFormSettings: {
        pagination: {}
      },
      selected: [],
      rowsPerPageItems: [5, 10, 25, 99],
      rowsPerPageText: "blah per blah",
      headers: [
        {
          text: "WidgetName",
          value: "name"
        },
        { text: "WidgetSerial", value: "serial" },
        {
          text: "WidgetDollarAmount",
          value: "dollarAmount"
        },
        { text: "Active", value: "active" },
        { text: "WidgetRoles", value: "roles" },
        { text: "WidgetStartDate", value: "startDate" },
        { text: "WidgetEndDate", value: "endDate" }
      ]
    };
  },
  watch: {
    "localFormSettings.pagination": {
      handler() {
        this.getDataFromApi();
      },
      deep: true
    }
  },
  methods: {
    lt(ltKey) {
      return window.$gz.locale.get(ltKey);
    },
    newItem() {
      this.$router.push({
        name: "inventory-widget-edit",
        params: { id: 0 }
      });
    },
    filterMe() {
      window.$gz.eventBus.$emit(
        "notify-info",
        "inventoryWidgetList::filterMe -> STUB (selected items count=" +
          this.selected.length +
          ")"
      );
      //console.log(this.selected);
    },
    getDataFromApi() {
      //debugger;
      var that = this;
      var listOptions = {
        offset: 0,
        limit: 5,
        sort: "name",
        asc: true
      };

      if (
        this.localFormSettings.pagination.itemsPerPage &&
        this.localFormSettings.pagination.itemsPerPage > 0
      ) {
        listOptions.offset =
          (this.localFormSettings.pagination.page - 1) *
          this.localFormSettings.pagination.itemsPerPage;
        listOptions.limit = this.localFormSettings.pagination.itemsPerPage;
      }
      listOptions.sort = this.localFormSettings.pagination.sortBy;
      listOptions.asc = !this.localFormSettings.pagination.descending;

      //set the list settings in the store since we were successful at retrieval
      if (
        that.localFormSettings &&
        that.localFormSettings.pagination &&
        that.localFormSettings.pagination.itemsPerPage
      ) {
        window.$gz.form.setFormSettings(FORM_KEY, {
          temp: { page: that.localFormSettings.pagination.page },
          saved: {
            itemsPerPage: that.localFormSettings.pagination.itemsPerPage,
            sortBy: that.localFormSettings.pagination.sortBy,
            descending: that.localFormSettings.pagination.descending
          }
        });
      }

      this.loading = true;
      var listUrl =
        "Widget/ListWidgets?" + window.$gz.api.buildQuery(listOptions);
      window.$gz.api.get(listUrl).then(res => {
        that.loading = false;
        that.Items = res.data;
        that.totalItems = res.paging.count;
      });
    },
    editItem(item) {
      this.$router.push({
        name: "inventory-widget-edit",
        params: { id: item.id }
      });
    }
  }
};
</script>
