<template>
  <div class="message-explorer">
    <div class="q-pa-md">
      <q-table
          :data="data"
          :columns="columns"
          row-key="id"
          :pagination.sync="pagination"
          :loading="loading"
          @request="getMessages"
          binary-state-sort
      >
        <template v-slot:top-left>
          <div class="q-table__title">
            Mesaje expediate{{totalMatching != null ? ' (' + totalMatching + ')' : ''}}
          </div>
          <q-btn
              dense
              icon-right="archive"
              label="Exportă în format CSV"
              no-caps
              @click="exportMessagesToCSV"
              v-if="totalMatching != null && totalMatching > 0"
          ></q-btn>
        </template>
        <template v-slot:top-right>
          <q-btn icon="event" rounded>
            {{ dateRange.from }} - {{ dateRange.to }}
            <q-popup-proxy @before-show="updateSelectedRange" transition-show="scale" transition-hide="scale">
              <q-date v-model="selectedRange" mask="YYYY-MM-DD" :navigation-max-year-month="moment().format('YYYY/MM')" range>
                <div class="row items-center justify-end q-gutter-sm">
                  <q-btn label="Cancel" color="primary" flat v-close-popup></q-btn>
                  <q-btn label="OK" color="primary" flat @click="saveSelectedRange" v-close-popup></q-btn>
                </div>
              </q-date>
            </q-popup-proxy>
          </q-btn>
        </template>
        <template v-slot:body-cell-to="props">
          <q-td :props="props">
            <a :href="`http://www.portabilitate.ro/ro-no-${props.row.to.replace('+40', '0')}#ctl00_cphBody_panelDetails`" target="_blank">{{props.row.to}}</a>
          </q-td>
        </template>
      </q-table>
    </div>
  </div>
</template>


<script>
module.exports = {
  name: "MessageExplorer",
  data() {
    return {
      dateRange: {
        from: moment().add(-1, 'M').format("YYYY-MM-DD"),
        to: moment().format("YYYY-MM-DD")
      },
      selectedRange: null,
      loading: false,
      pagination: {
        sortBy: 'id',
        descending: true,
        page: 1,
        rowsPerPage: 50,
        rowsNumber: 50
      },
      columns: [
        {name: "id", label: "ID mesaj", field: "id", sortable: true},
        {name: "fromICCID", label: "Expeditor", field: "fromICCID", sortable: true},
        {name: "to", label: "Destinatar", field: "to", sortable: true},
        {name: "content", label: "Mesaj", field: "content", sortable: true, style: "max-width: 375px; min-width: 375px; white-space: normal;"},
        {name: "creationDate", label: "Dată creere", field: "creationDate", style: "max-width: 50px; white-space: normal;", sortable: true, format: (val, row) => val != null ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "" },
        /*{name: "allocationDate", label: "Dată alocare", field: "allocationDate", sortable: true},*/
        {name: "sentDate", label: "Dată expediere", field: "sentDate", style: "max-width: 30px; white-space: normal;",sortable: true, format: (val, row) => val != null ? moment(val).format("YYYY-MM-D HH:mm:ss") : "" },
        {name: "deliveredDate", label: "Dată livrare", field: "deliveredDate", style: "max-width: 30px; white-space: normal;",sortable: true, format: (val, row) => val != null ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "" },
        {name: "sendingStatus", label: "Expediere", field: "sendingStatus", sortable: true, style: "max-width: 30px; white-space: normal;", format: (val, row) => val == 0 ? "" : val == 1 ? "OK" : "Problema: " + val},
        {name: "deliveryStatus", label: "Livrare", field: "deliveryStatus", sortable: true, style: "max-width: 30px; white-space: normal;", format: (val, row) => val == -1 ? "Nesolicitat" : val == 0 ? (row.deliveredDate ? "Eșuat" : "") : val == 1 ? "OK" : "Problema: " + val}
      ],
      data: [],
      totalMatching: null
    };
  },
  props: {
  },
  computed: {
  },
  watch: {
    dateRange: {
      handler() {
        var fromTimestamp = moment(this.dateRange.from).valueOf();
        var toTimestamp = moment(this.dateRange.to).add(1, 'days').valueOf();
        this.loading = true;
        this.totalMatching = null;
        axios.get(`/api/v1/sms/messages/${fromTimestamp}/${toTimestamp}/totals`)
            .then(response => {
              this.totalMatching = response.data;
            })
            .catch(error => {
              var errorMessage;
              try {
                errorMessage = error.response ? JSON.stringify(error.response.data) : error.request ? JSON.stringify(error.request) : error.message;
              } catch (e) {
                errorMessage = error.message;
              }
              this.$q.dialog({
                title: "O eroare s-a produs în timpul interogării numărului total de mesaje",
                message: errorMessage
              });
              this.loading = false;
            });
      },
      immediate: true
    },
    totalMatching: {
      handler() {
        if (this.totalMatching != null) {
          this.getMessages({pagination: this.pagination});
        } else {
          this.data = [];
        }
      }
    }
  },
  methods: {
    getMessageCallParameters(props) {
      var { page, rowsPerPage } = props.pagination;
      var fetchCount = rowsPerPage === 0 ? this.totalMatching : rowsPerPage;
      var startRow = (page - 1) * rowsPerPage;
      var fromTimestamp = moment(this.dateRange.from).valueOf();
      var toTimestamp = moment(this.dateRange.to).add(1, 'days').valueOf();
      return {
        ...props.pagination,
        fetchCount: fetchCount,
        rowsNumber: this.totalMatching,
        startRow: startRow,
        fromTimestamp: fromTimestamp,
        toTimestamp: toTimestamp
      };
    },
    getMessages(props) {
      var { page, rowsPerPage, sortBy, descending, fetchCount, rowsNumber, startRow, fromTimestamp, toTimestamp } = this.getMessageCallParameters(props);
      this.loading = true;
      axios
          .get(`/api/v1/sms/messages/${fromTimestamp}/${toTimestamp}/sort/${sortBy}/${descending}/${startRow}/${fetchCount}`)
          .then(response => {
          var data = [];
          response.data.forEach((row, index) => {
            data.push(row);
          });
          this.data = data;
          this.pagination.page = page;
          this.pagination.rowsPerPage = rowsPerPage;
          this.pagination.sortBy = sortBy;
          this.pagination.descending = descending;
          this.pagination.rowsNumber = rowsNumber;
          this.loading = false;
        })
        .catch(error => {
          var errorMessage;
          try {
            errorMessage = error.response ? JSON.stringify(error.response.data) : error.request ? JSON.stringify(error.request) : error.message;
          } catch (e) {
            errorMessage = error.message;
          }
          this.$q.dialog({
            title: "O eroare s-a produs în timpul descărcării mesajelor",
            message: errorMessage
          });
          this.loading = false;
        });

    },
    updateSelectedRange() {
      this.selectedRange = Object.assign({}, this.dateRange);
    },
    saveSelectedRange() {
      this.dateRange = Object.assign({}, this.selectedRange);
    },
    exportMessagesToCSV() {
      var { page, rowsPerPage, sortBy, descending, fetchCount, startRow, fromTimestamp, toTimestamp } = this.getMessageCallParameters({pagination: this.pagination});

      document.location.href = `/api/v1/sms/messages/${fromTimestamp}/${toTimestamp}/sort/${sortBy}/${descending}/${0}/${Math.pow(2, 31) - 1}/csv`;
    },
    moment(timestamp) {
      return moment(timestamp);
    }
  }
}

</script>

<style scoped>
</style>

<style>
  .row {
    margin: 0 !important;
  }

  .q-date__content .col {
    padding: 0 !important;
  }
</style>