<template>
  <b-container
    :style="{ display: 'flex', 'flex-direction': 'column' }"
    fluid="xxl pt-0 m-0"
    class="logs-section"
  >
    <page-title />
    <div class="logs-head-container">
      <table-cell-count
        :filtered-items-count="filteredRows"
        :total-number-of-cells="allLogs.length"
      ></table-cell-count>
      <search
        :placeholder="$t('pageEventLogs.table.searchLogs')"
        data-test-id="eventLogs-input-searchLogs"
        style="margin: 13px; width: 35%"
        @change-search="onChangeSearchInput"
        @clear-search="onClearSearchInput"
      />
    </div>
    <b-row class="align-items-start">
      <b-col md="12" xl="6">
        <table-date-filter @change="onChangeDateTimeFilter" />
      </b-col>
      <b-col
        md="12"
        xl="6"
        class="d-flex align-items-end justify-content-between mt-3"
      >
        <table-filter :filters="tableFilters" @filter-change="onFilterChange" />
        <popover-with-slot
          id="popover-delete"
          :button-label="$t('pageEventLogs.clear')"
          :popup-label="$t('pageEventLogs.clearLogs_popup')"
          placement="left"
          :action="deleteAllLogs"
        >
          <b-button
            id="popover-delete"
            ref="button"
            variant="link"
            style="color: $red-brand-primary"
            :disabled="allLogs.length === 0"
          >
            <icon-delete /> {{ $t('pageEventLogs.clearLogs') }}
          </b-button>
        </popover-with-slot>
        <b-button
          variant="primary"
          size="md"
          :class="{ disabled: allLogs.length === 0 }"
          :download="exportFileNameByDate()"
          :href="href"
        >
          <icon-download /> {{ $t('global.action.exportAll') }}
        </b-button>
      </b-col>
    </b-row>
    <b-row>
      <b-col id="logs-table-wrapper" class="m-0 p-0">
        <table-toolbar
          ref="toolbar"
          :selected-items-count="selectedRows.length"
          :actions="batchActions"
          @clear-selected="clearSelectedRows($refs.table)"
        >
          <template #toolbar-buttons>
            <b-button
              size="md"
              variant="secondary"
              style="margin-right: 1rem"
              @click="resolveLogs"
            >
              <img
                class="sourse__img"
                src="@/assets/images/event-logs/resolved-button.svg"
              />
              {{ $t('pageEventLogs.resolve') }}
            </b-button>
            <b-button
              size="md"
              variant="primary"
              style="margin-right: 1rem"
              @click="unresolveLogs"
            >
              {{ $t('pageEventLogs.unresolve') }}
            </b-button>
            <table-toolbar-export
              :data="batchExportData"
              style="margin-right: 1rem"
              :file-name="exportFileNameByDate()"
            />
          </template>
        </table-toolbar>
        <b-table
          id="table-event-logs"
          ref="table"
          responsive="md"
          class="logs-table"
          selectable
          no-select-on-click
          sort-icon-left
          hover
          no-sort-reset
          sort-desc
          show-empty
          no-border-collapse
          sort-by="id"
          :sticky-header="true"
          :fields="fields"
          :items="filteredLogs"
          :sort-compare="onSortCompare"
          :empty-text="$t('global.table.emptyMessage')"
          :empty-filtered-text="$t('global.table.emptySearchMessage')"
          :per-page="perPage"
          :current-page="currentPage"
          :filter="searchFilter"
          :busy="isBusy"
          @filtered="onFiltered"
          @row-selected="onRowSelected($event, filteredLogs.length)"
        >
          <!-- Checkbox column -->
          <template #head(checkbox)>
            <b-form-checkbox
              v-model="tableHeaderCheckboxModel"
              data-test-id="eventLogs-checkbox-selectAll"
              :indeterminate="tableHeaderCheckboxIndeterminate"
              @change="onChangeHeaderCheckbox($refs.table)"
            >
              <span class="sr-only">{{ $t('global.table.selectAll') }}</span>
            </b-form-checkbox>
          </template>
          <template #cell(checkbox)="row">
            <b-form-checkbox
              v-model="row.rowSelected"
              :data-test-id="`eventLogs-checkbox-selectRow-${row.index}`"
              @change="toggleSelectRow($refs.table, row.index)"
            >
              <span class="sr-only">{{ $t('global.table.selectItem') }}</span>
            </b-form-checkbox>
          </template>
          <!-- Description column -->
          <template #cell(description)="data">
            <b-row class="semi-bold-16px tretiatry">
              {{ filteredLogs[data.index].name }}
            </b-row>
            <b-row
              class="regular-12px tretiatry pointer"
              @click="toggleRowDetails(data)"
            >
              {{ data.value }}
            </b-row>
          </template>

          <template #row-details="{ item }">
            <b-container
              fluid
              style="border-bottom: 1px solid rgba(26, 62, 91, 0.1)"
            >
              <b-row>
                <b-col class="mt-1">
                  <dl>
                    <!-- Name -->
                    <dt class="semi-bold-12px">
                      {{ $t('pageEventLogs.table.name') }}:
                    </dt>
                    <dd class="regular-12px">{{ dataFormatter(item.name) }}</dd>
                  </dl>
                  <dl>
                    <!-- Description -->
                    <dt class="semi-bold-12px">
                      {{ $t('pageEventLogs.table.description') }}:
                    </dt>
                    <dd class="regular-12px tretiatry">
                      {{ dataFormatter(item.description) }}
                    </dd>
                  </dl>
                  <dl>
                    <!-- Type -->
                    <dt class="semi-bold-12px">
                      {{ $t('pageEventLogs.table.type') }}:
                    </dt>
                    <dd class="regular-12px tretiatry">
                      {{ dataFormatter(item.type) }}
                    </dd>
                  </dl>
                </b-col>
              </b-row>
            </b-container>
          </template>

          <!-- Severity column -->
          <template #cell(severity)="{ value }">
            <span
              :class="`indicators-${value}`"
              class="bold-12px__caps"
              style="text-overflow: ellipsis; white-space: nowrap"
            >
              {{ value }}</span
            >
          </template>
          <!-- Date column -->
          <template #cell(date)="{ value }">
            <img
              src="@/assets/images/event-logs/time.svg"
              class="sourse__img"
            />
            <span v-if="value" class="regular-12px quaternary">
              {{ value | formatDate }}
            </span>
            <span v-if="value" class="regular-12px quaternary">
              в {{ value | formatTimeShort }}
            </span>
          </template>

          <!-- Status column -->
          <template #cell(status)="{ value }">
            <b-row v-if="value === true">
              <img
                class="sourse__img"
                src="@/assets/images/event-logs/resolved.svg"
              />
              <span class="semi-bold-12px__caps resolved">
                {{ $t('pageEventLogs.resolved') }}
              </span>
            </b-row>
            <b-row v-else>
              <img
                class="sourse__img"
                src="@/assets/images/event-logs/not-resolved.svg"
              />
              <span class="semi-bold-12px__caps not-resolved">
                {{ $t('pageEventLogs.unresolved') }}</span
              >
            </b-row>
          </template>
        </b-table>
      </b-col>
    </b-row>
    <!-- Table pagination -->
    <b-row class="logs-pagination-container">
      <b-col sm="6" class="d-flex align-items-center justify-content-start">
        <b-form-group
          class="table-pagination-select"
          :label="$t('global.table.itemsPerPage')"
          label-class="semi-bold-16px mb-0"
          label-for="pagination"
        >
          <b-form-select
            id="pagination"
            v-model="perPage"
            class="select-per-page semi-bold-16px mb-0"
            :options="itemsPerPageOptions"
          />
        </b-form-group>
      </b-col>
      <b-col sm="6" class="d-flex align-items-center justify-content-end">
        <span class="semi-bold-16px"> Страницы </span>
        <b-pagination
          v-model="currentPage"
          first-number
          last-number
          :per-page="perPage"
          :total-rows="getTotalRowCount(filteredRows)"
          aria-controls="table-event-logs"
        />
      </b-col>
    </b-row>
  </b-container>
</template>

<script>
import IconDelete from '@carbon/icons-vue/es/trash-can/20';
import IconDownload from '@carbon/icons-vue/es/download/20';
import { omit } from 'lodash';

import PageTitle from '@/components/Global/PageTitle';
import Search from '@/components/Global/Search';
import TableCellCount from '@/components/Global/TableCellCount';
import TableDateFilter from '@/components/Global/TableDateFilter';
import TableFilter from '@/components/Global/TableFilter';
import TableToolbar from '@/components/Global/TableToolbar';
import TableToolbarExport from '@/components/Global/TableToolbarExport';
import PopoverWithSlot from '@/components/Global/SilaComponents/PopoverWithSlot';

import LoadingBarMixin from '@/components/Mixins/LoadingBarMixin';
import TableFilterMixin from '@/components/Mixins/TableFilterMixin';
import BVPaginationMixin, {
  currentPage,
  perPage,
  itemsPerPageOptions,
} from '@/components/Mixins/BVPaginationMixin';
import BVTableSelectableMixin, {
  selectedRows,
  tableHeaderCheckboxModel,
  tableHeaderCheckboxIndeterminate,
} from '@/components/Mixins/BVTableSelectableMixin';
import BVToastMixin from '@/components/Mixins/BVToastMixin';
import DataFormatterMixin from '@/components/Mixins/DataFormatterMixin';
import TableSortMixin from '@/components/Mixins/TableSortMixin';
import TableRowExpandMixin, {
  expandRowLabel,
} from '@/components/Mixins/TableRowExpandMixin';
import SearchFilterMixin, {
  searchFilter,
} from '@/components/Mixins/SearchFilterMixin';

export default {
  components: {
    IconDelete,
    IconDownload,
    PageTitle,
    Search,
    TableCellCount,
    TableFilter,
    TableToolbar,
    TableToolbarExport,
    TableDateFilter,
    PopoverWithSlot,
  },
  mixins: [
    BVPaginationMixin,
    BVTableSelectableMixin,
    BVToastMixin,
    LoadingBarMixin,
    TableFilterMixin,
    DataFormatterMixin,
    TableSortMixin,
    TableRowExpandMixin,
    SearchFilterMixin,
  ],
  beforeRouteLeave(to, from, next) {
    // Hide loader if the user navigates to another page
    // before request is fulfilled.
    this.hideLoader();
    next();
  },
  data() {
    return {
      isBusy: true,
      sortDesc: true,
      fields: [
        {
          key: 'checkbox',
          sortable: false,
          thClass: ' logs-table__th',
          tdClass: 'logs-table__td',
        },
        {
          key: 'id',
          label: this.$t('pageEventLogs.table.id'),
          sortable: true,
          thClass: 'bold-12px__caps logs-table__th',
          tdClass: 'semi-bold-12px logs-table__td',
        },
        {
          key: 'description',
          label: this.$t('pageEventLogs.table.about_event'),
          thClass: 'bold-12px__caps logs-table__th',
          tdClass: 'logs-table__td',
        },
        {
          key: 'severity',
          label: this.$t('pageEventLogs.table.severity'),
          thClass: 'bold-12px__caps logs-table__th',
          tdClass: 'logs-table__td',
        },
        {
          key: 'source',
          label: this.$t('pageEventLogs.table.source'),
          thClass: 'bold-12px__caps logs-table__th',
          tdClass: 'logs-table__td semi-bold-12px__caps tretiatry ',
        },
        {
          key: 'date',
          label: this.$t('pageEventLogs.table.date'),
          sortable: true,
          thClass: `bold-12px__caps logs-table__th`,
          tdClass: 'logs-table__td',
        },
        {
          key: 'status',
          sortable: true,
          label: this.$t('pageEventLogs.table.status'),
          thClass: 'bold-12px__caps logs-table__th',
          tdClass: 'logs-table__td',
        },
      ],
      tableFilters: [
        {
          key: 'severity',
          label: this.$t('pageEventLogs.table.severity'),
          values: ['OK', 'Warning', 'Critical'],
        },
        {
          key: 'filterByStatus',
          label: this.$t('pageEventLogs.table.status'),
          values: ['Resolved', 'Unresolved'],
        },
      ],
      expandRowLabel,
      activeFilters: [],
      batchActions: [
        {
          value: 'delete',
          label: this.$t('global.action.delete'),
        },
      ],
      currentPage: currentPage,
      filterStartDate: null,
      filterEndDate: null,
      itemsPerPageOptions: itemsPerPageOptions,
      perPage: perPage,
      searchFilter: searchFilter,
      searchTotalFilteredRows: 0,
      selectedRows: selectedRows,
      tableHeaderCheckboxModel: tableHeaderCheckboxModel,
      tableHeaderCheckboxIndeterminate: tableHeaderCheckboxIndeterminate,
    };
  },
  computed: {
    href() {
      return `data:text/json;charset=utf-8,${this.exportAllLogs()}`;
    },
    filteredRows() {
      return this.searchFilter
        ? this.searchTotalFilteredRows
        : this.filteredLogs.length;
    },
    allLogs() {
      return this.$store.getters['eventLog/allEvents'].map((event) => {
        return {
          ...event,
          actions: [
            {
              value: 'export',
              title: this.$t('global.action.export'),
            },
            {
              value: 'delete',
              title: this.$t('global.action.delete'),
            },
          ],
        };
      });
    },
    batchExportData() {
      return this.selectedRows.map((row) => omit(row, 'actions'));
    },
    filteredLogsByDate() {
      return this.getFilteredTableDataByDate(
        this.allLogs,
        this.filterStartDate,
        this.filterEndDate
      );
    },
    filteredLogs() {
      return this.getFilteredTableData(
        this.filteredLogsByDate,
        this.activeFilters
      ).filter((el) => el.description);
    },
  },
  created() {
    this.startLoader();
    this.$store.dispatch('eventLog/getEventLogData').finally(() => {
      this.endLoader();
      this.isBusy = false;
    });
  },
  methods: {
    changelogStatus(row) {
      this.$store
        .dispatch('eventLog/updateEventLogStatus', {
          uri: row.uri,
          status: row.status,
        })
        .then((success) => {
          this.successToast(success);
        })
        .catch(({ message }) => this.errorToast(message));
    },
    deleteAllLogs() {
      this.$store
        .dispatch('eventLog/deleteAllEventLogs', this.allLogs)
        .then((message) => this.successToast(message))
        .catch(({ message }) => this.errorToast(message));
    },
    deleteLogs(uris) {
      this.$store
        .dispatch('eventLog/deleteEventLogs', uris)
        .then((messages) => {
          messages.forEach(({ type, message }) => {
            if (type === 'success') {
              this.successToast(message);
            } else if (type === 'error') {
              this.errorToast(message);
            }
          });
        });
    },
    exportAllLogs() {
      {
        return this.$store.getters['eventLog/allEvents'].map((eventLogs) => {
          const allEventLogsString = JSON.stringify(eventLogs);
          return allEventLogsString;
        });
      }
    },
    onFilterChange({ activeFilters }) {
      this.activeFilters = activeFilters;
    },
    onSortCompare(a, b, key) {
      if (key === 'severity') {
        return this.sortStatus(a, b, key);
      }
    },
    onTableRowAction(action, { uri }) {
      if (action === 'delete') {
        this.$bvModal
          .msgBoxConfirm(this.$tc('pageEventLogs.modal.deleteMessage'), {
            title: this.$tc('pageEventLogs.modal.deleteTitle'),
            okTitle: this.$t('global.action.delete'),
            cancelTitle: this.$t('global.action.cancel'),
          })
          .then((deleteConfirmed) => {
            if (deleteConfirmed) this.deleteLogs([uri]);
          });
      }
    },
    onBatchAction(action) {
      if (action === 'delete') {
        const uris = this.selectedRows.map((row) => row.uri);
        this.$bvModal
          .msgBoxConfirm(
            this.$tc(
              'pageEventLogs.modal.deleteMessage',
              this.selectedRows.length
            ),
            {
              title: this.$tc(
                'pageEventLogs.modal.deleteTitle',
                this.selectedRows.length
              ),
              okTitle: this.$t('global.action.delete'),
              cancelTitle: this.$t('global.action.cancel'),
            }
          )
          .then((deleteConfirmed) => {
            if (deleteConfirmed) {
              if (this.selectedRows.length === this.allLogs.length) {
                this.$store
                  .dispatch(
                    'eventLog/deleteAllEventLogs',
                    this.selectedRows.length
                  )
                  .then(() => {
                    this.successToast(
                      this.$tc('pageEventLogs.toast.successDelete', uris.length)
                    );
                  })
                  .catch(({ message }) => this.errorToast(message));
              } else {
                this.deleteLogs(uris);
              }
            }
          });
      }
    },
    onChangeDateTimeFilter({ fromDate, toDate }) {
      this.filterStartDate = fromDate;
      this.filterEndDate = toDate;
    },
    onFiltered(filteredItems) {
      this.searchTotalFilteredRows = filteredItems.length;
    },
    // Create export file name based on date
    exportFileNameByDate(value) {
      let date = new Date();
      date =
        date.toISOString().slice(0, 10) +
        '_' +
        date.toString().split(':').join('-').split(' ')[4];
      let fileName;
      if (value === 'export') {
        fileName = 'event_log_';
      } else {
        fileName = 'all_event_logs_';
      }
      return fileName + date;
    },
    resolveLogs() {
      this.$store
        .dispatch('eventLog/resolveEventLogs', this.selectedRows)
        .then((messages) => {
          messages.forEach(({ type, message }) => {
            if (type === 'success') {
              this.successToast(message);
            } else if (type === 'error') {
              this.errorToast(message);
            }
          });
        });
    },
    unresolveLogs() {
      this.$store
        .dispatch('eventLog/unresolveEventLogs', this.selectedRows)
        .then((messages) => {
          messages.forEach(({ type, message }) => {
            if (type === 'success') {
              this.successToast(message);
            } else if (type === 'error') {
              this.errorToast(message);
            }
          });
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.semi-bold-14px {
  margin: auto 0;
}
.row {
  margin: 0px;
}

.not-resolved {
  color: $text-quaternary;
}

.form-group,
.b-pagination {
  margin: 0px !important;
}
</style>
