mdi-chart-areaspline {{ $route.path | pageTitle }} mdi-refresh
mdi-chart-areaspline {{ $route.path | pageTitle }} mdi-refresh
mdi-chart-areaspline {{ $route.path | pageTitle }} mdi-refresh
<template>
  <div id="monitor-alert" v-resize="onResize" fluid>
    <div class="bigger-text font-weight-bold d-flex align-center">
      <v-icon class="mr-2" color="secondary"> mdi-chart-areaspline </v-icon>
      {{ $route.path | pageTitle }}
      <v-spacer />
      <refresh-set :refresh-item="refreshItem" />
      <v-btn
        fab
        x-small
        outlined
        text
        color="secondary"
        class="ml-1 pa-0"
        @click="refreshBtn"
      >
        <v-icon>mdi-refresh</v-icon>
      </v-btn>
    </div>

    <div class="d-flex align-center flex-wrap my-1">
      <div style="width: 250px">
        <v-text-field
          v-model="search"
          dense
          rounded
          solo
          full-width
          hide-details
          :placeholder="$t('Monitoring.alert.search')"
          align="bottom"
          @keyup.enter="searchAlert = search"
        />
      </div>

      <v-spacer />

      <div
        style="width: 400px"
        class="d-flex rounded-box justify-center align-center mr-2"
      >
        <input
          v-model="stdt"
          type="datetime-local"
          class="pa-0"
          @input="currentDuration = { title: $t('Monitoring.sensor.durationList.pickDate'), date: '0' }"
        />
        <p class="my-1 mx-2">~</p>
        <input
          v-model="eddt"
          type="datetime-local"
          class="pr-4"
          @input="currentDuration = { title: $t('Monitoring.sensor.durationList.pickDate'), date: '0' }"
        />
      </div>

      <div>
        <v-select
          style="width: 160px"
          v-model="currentDuration"
          solo
          rounded
          dense
          hide-details
          :items="durationList"
          item-text="title"
          item-value="date"
          @change="setSearchDate"
        />
      </div>

      <v-btn
        depressed
        color="secondary"
        dense
        class="ml-1"
        x-small
        fab
        @click="getAlertLogES"
      >
        <v-icon>mdi-magnify</v-icon>
      </v-btn>
    </div>

    <v-card class="pt-1">
      <v-data-table
        :headers="headers"
        :items="alertLogs"
        :items-per-page="auItemsPerPage"
        :footer-props="auFooterProps"
        :search.sync="searchAlert"
        :height="mainGridHeight"
        :sort-by.sync="sortBy"
        :sort-desc.sync="sortDesc"
        dense
        fixed-header
      >
        <template v-slot:item.created_at="{ item }">
          {{ item.created_at | logYYYYDateTime }}
        </template>

        <template v-slot:[`body.append`]="props">
          <tr style="height: 1px">
            <td style="height: 1px" :colspan="props.headers.length" />
          </tr>
        </template>
      </v-data-table>
    </v-card>
  </div>
</template>

<script>
import { dateFormat } from '@/utils.js'

import { ACT_SHOW_ERROR_ALERT, ACT_GET_ELASTICSEARCH_DATA } from '@/GlobalVars'
import RefreshSet from '../components/RefreshSet'
export default {
  name: 'Alert',
  components: {
    RefreshSet,
  },

  data () {
    let dayTo = new Date();
    dayTo.setMinutes(dayTo.getMinutes() + 1);
    const delta = 1 * 24 * 60 * 60 * 1000; // 1 day
    const dayFrom = new Date(dayTo - delta - 60000); // dayFrom은 고정 dayTo만 지금보다 1분 더 늦게

    return {
      isAdmin: false,
      sortBy: 'created_at',
      sortDesc: true,
      mainGridHeight: 0,

      idInterval: null,

      searchAlert: '',
      search: '',

      stdt: this.$filters.dateTimeStr(dayFrom),
      eddt: this.$filters.dateTimeStr(dayTo),

      alertLogs: [],
      headers: [
        {
          text: this.$t('Monitoring.alert.header.time'),
          value: 'created_at',
          sortable: true,
          filterable: true,
          width: '15%',
        },
        {
          text: this.$t('Monitoring.alert.header.description'),
          value: 'message',
          filterable: true,
        },
      ],
      auFooterProps: {
        disableItemsPerPage: true,
        showCurrentPage: true,
        showFirstLastPage: true,
      },

      currentDuration: "1d",
      durationList: [
        { title: this.$t('Monitoring.alert.durationList.pickDate'), date: "0" },
        { title: this.$t('Monitoring.alert.durationList.1day'), date: "1d" },
        { title: this.$t('Monitoring.alert.durationList.7day'), date: "7d" },
        { title: this.$t('Monitoring.alert.durationList.30day'), date: "30d" },
      ],
    }
  },
  created () {
    this.getAlertLogES()
    this.onResize()
    this.setIntervalFunc()
  },

  computed: {
    auItemsPerPage () {
      return this.$store.state.main.config.rowInPage
    },

    refreshItem () {
      return this.$store.getters['main/refresh']
    },
  },
  watch: {
    refreshItem: {
      handler () {
        this.setIntervalFunc()
      },
      deep: true,
    },
  },
  beforeDestroy () {
    clearInterval(this.idInterval)
    this.idInterval = null
  },
  methods: {
    setDateRange (message) {
      if (message === 0) {
        this.btnColor = 1
      } else if (message === 7) {
        this.btnColor = 2
      } else {
        this.btnColor = 3
      }
      const day = parseInt(message)
      const fromday = new Date()
      const today = new Date()
      fromday.setDate(today.getDate() - day)

      this.eddt = dateFormat(today)
      this.edtm = '23:59'
      this.oneddt = false
      this.onstdt = false
      this.stdt = dateFormat(fromday)
      this.sttm = '00:00'

      this.onsttm = false
      this.onedtm = false
    },

    setIntervalFunc () {
      const self = this
      if (this.idInterval) {
        clearInterval(this.idInterval)
        this.idInterval = null
      }
      if (this.refreshItem.state) {
        const reftm = this.refreshItem.tm * 1000

        this.idInterval = setInterval(() => {
          self.getAlertLogES()
        }, reftm)
      }
    },

    refreshBtn () {
      this.getAlertLogES()
    },
    onResize () {
      const height = window.innerHeight - 200
      this.mainGridHeight = height
    },
    getAlertLogES(){
      const option = {
        host: "192.168.71.243",
        url: "ncurion-alertlog-*/_search",
        data: {
          size: 1000,
          sort:[
            {
              "@timestamp": {
                "order": "desc",
                "unmapped_type": "boolean"
              }
            }
          ],
          query: {
            bool: {
              must: [
                {
                  query_string: {
                    fields: [
                      "creator",
                      "message",
                    ],
                    query: `*${this.search}*`,
                  },
                },
                {
                  range: {
                    "@timestamp": {
                      gte: this.stdt + ":00.000+09:00",
                      lte: this.eddt + ":00.000+09:00"
                    }
                  }
                }
              ],
            }
          }
        }
      }

      if (!this.search) {
        option.data.query.bool.must = [option.data.query.bool.must[1]];
      }

      this.$store.dispatch(`tool/${ACT_GET_ELASTICSEARCH_DATA}`, {...option,host: "192.168.71.243"})
      .then((res) => {
          this.alertLogs = res.data.hits.hits?.map((el) => el._source);
        })
        .catch((error) => {
          const msg = this.$t('Event.commons.errorMsg.noEventData');
          this.$store.dispatch(`alert/${ACT_SHOW_ERROR_ALERT}`, {
            msg: msg,
            // error: returnQueryErrorMsg(error.errors[0]),
            error: '',
          });
        });
    },

    setSearchDate(duration) {
      let dayFrom;
      let dayTo = new Date();
      dayTo.setMinutes(dayTo.getMinutes() + 1); // dayTo만 지금보다 1분 더 늦게
      switch (duration) {
        case "0":
          return;
        case "1d":
          dayFrom = new Date(dayTo - 1 * 24 * 60 * 60 * 1000);
          break;
        case "7d":
          dayFrom = new Date(dayTo - 7 * 24 * 60 * 60 * 1000);
          break;
        case "30d":
          dayFrom = new Date(dayTo - 30 * 24 * 60 * 60 * 1000);
          break;

        default:
          console.error(`unknown delta time: ${duration}`);
          break;
      }

      this.stdt = this.$filters.dateTimeStr(dayFrom);
      this.eddt = this.$filters.dateTimeStr(dayTo);
    },
  },
}
</script>

<v-btn
  outlined
  text
  small
  color="primary"
  @click.stop="disableGroupUserAlert(el, index)"
  class="mx-1"
  >사용자 알림 {{ userEnable[index] }}</v-btn
>
<v-btn
  outlined
  text
  small
  color="primary"
  @click.stop="disableGroupAdminAlert(el, index)"
  >관리자 알림 {{ adminEnable[index] }}</v-btn
>