<template>
  <!-- TODO:  refactor into components -->
  <div>
    <ods-sub-header
      data-id="alerts-subheader"
      cssClass="overrideSubHeader"
    >
      <div style="display: flex; justify-content: space-between; font-weight: 500;">
        <h6>
          {{ $t('dataTables.subheader') }}
        </h6>
        <a href="#">
          <h4 class="rule-settings__title">
            {{ $t('dataTables.alertsConfig') }}
            <div class="rule-settings__icon">
              <ods-icon
                name="setting"
                size="16"
              >
              </ods-icon>
            </div>
          </h4>
        </a>
      </div>
    </ods-sub-header>
    <div class="alerts-container">

      <kpi-filter
        :kpiCounts="kpiCounts"
        :averageTimeResolution="averageTimeResolution"
        @quickFilterAlerts="quickFilterAlerts"
      ></kpi-filter>

      <div class="alerts">
        <div class="filter-container">
          <dynamic-filters
            data-id="table-filters"
            :data="getAlertList"
            :options="columns"
            :type="filterType"
            :valueType="valueType"
            @changeFilter="onChangeFilter"
            class="table-filter"
          />
        </div>
        <div class="table">
          <ods-table
            data-id="alerts-table"
            ref="alertsTable"
            :data="getAlertList"
            height="440"
            size="mini"
            @sort-change="sort"
          >
            <ods-table-column
              prop="status"
              :label="translate('status')"
              sortable="custom"
              v-slot="scope"
            >
              <template v-if="statusMap[scope.row.status]">
                <ods-cascader
                  :options="getOptionsWarning(scope.row)"
                  @change="(event)=> getOptionSelected(event, scope.row)"
                  :value="[scope.row['status']]"
                  :class="addStatusColor(scope.row)"
                />
              </template>
              <template v-else>
                <span
                  :class="addStatusColor(scope.row)"
                  :label="translate(scope.row.status)"
                >
                  {{ translate(scope.row.status+2)}}
                </span>
              </template>

            </ods-table-column>
            <ods-table-column
              prop="creationDate"
              :label="translate('creationDate')"
              v-slot="scope"
              sortable="custom"
            >
              {{ dateFormat(scope.row.creationDate)}}
            </ods-table-column>
            <ods-table-column
              prop="creationDate"
              :label="translate('time')"
              v-slot="scope"
              sortable="custom"
            >
              {{ dateFormat(scope.row.creationDate, 'HH:mm')}}
            </ods-table-column>
            <ods-table-column
              prop="subtype"
              :label="translate('type')"
              sortable="custom"
              v-slot="scope"
            >
              {{ translate(scope.row.subtype) }}
            </ods-table-column>
            <ods-table-column
              prop="detail"
              label="Descripción"
              width="230"
            >
            </ods-table-column>
            <ods-table-column
              prop="affectedAssetType"
              :label="translate('affectedAssetId')"
              sortable="custom"
              v-slot="scope"
            >
              <template v-if="scope.row.affectedAssetType && scope.row.affectedAssetType ==='Vehicle'">
                <ods-icon
                  class="table-row__entity-icon"
                  name="car"
                  size="14"
                >
                </ods-icon>
              </template>
              <template v-else-if="scope.row.affectedAssetType && scope.row.affectedAssetType ==='Person'">
                <ods-icon
                  class="table-row__entity-icon"
                  name="user"
                  size="14"
                ></ods-icon>
              </template>
              <template v-else>
                <ods-icon
                  class="table-row__entity-icon"
                  name="dumpster"
                  size="14"
                ></ods-icon>
              </template>
              <a
                href="#"
                class="table-row__entity-link"
              >
                {{scope.row.affectedAssetType}}
                {{`${scope.row.affectedAssetId}`}}
              </a>

            </ods-table-column>
            <ods-table-column
              prop="creationDate"
              :label="translate('duration')"
              sortable="custom"
            >
            </ods-table-column>
            <ods-table-column
            v-slot="scope"
            class="item"
            >
              <ods-button
                icon="ods-icon-arrow-right"
                circle
                negative
                @click="alertDetail(scope.row.affectedAssetId)"
              >

              </ods-button>
            </ods-table-column>
          </ods-table>
          <ods-pagination
            small
            layout="prev, pager, next"
            @current-change="pageChange"
            :current-page="currentAlertsPage"
            :page-size="size"
            :total="getTotal"
          >
          </ods-pagination>
        </div>

      </div>
    </div>

    <assign-dialog
      @close="dialogAssignmentStatus = false"
      @assignmentFormData="submitAssignamentStatusForm"
      :visible="dialogAssignmentStatus"
      :warningId="dialogAssignmentWarningId"
    ></assign-dialog>
  </div>
</template>

<script>
import Vue from 'vue';
import moment from 'moment';
import {mapActions, mapGetters, mapState} from 'vuex';
import DynamicFilters from '@/components/shared/DynamicFilters.vue';
import {dateFormat} from '@/utils/filters';
import statusMap from '@/constants/warnings-status.js';
import customSimpleDialogConfig from '@/constants/dialog.js';
import AssignDialog from '@/components/assign-dialog/AssignDialog';
import KpiFilter from '@/components/kpi-filter/KpiFilter';
import api from '@/services/api.js';

export default {
  name: 'Alerts',
  components: {
    DynamicFilters,
    AssignDialog,
    KpiFilter,
  },
  data() {
    return {
      statusMap,
      filterType: null,
      valueType: null,
      columns: ['status', 'creationDate', 'type', 'detail', 'affectedAssetId', 'duration'],
      size: 10,
      currentAlertsPage: 1,
      quickFilter: 'all',
      dialogAssignmentStatus: false,
      dialogAssignmentWarningId: '',
      kpiCounts: {},
      averageTimeResolution: '--h--m--s',
    };
  },
  mounted() {
    if (this.$route.params.type) {
      this.valueType = this.$route.params.type;
      this.filterType = 'type';
    }
    this.setPageSize(this.size);
    this.setAlerts();
    this.setCurrentAlertsPage();

    // kpi-filter set props
    this.fetchWarningsPie({field: 'status', ontologyName: 'warning'}).then((statusKpis) => {
      const defaultKpis = ['ASSIGNED', 'INFORMATIVE', 'OPEN', 'RESOLVED'];
      defaultKpis.forEach((item) => {
        const findedKpi = statusKpis.find(kpi => kpi._id === item);
        if (!findedKpi) {
          statusKpis.push({_id: item, count: 0});
        }
      });
      this.kpiCounts = statusKpis;
    });

    this.fetchAvergageKpi();
  },

  computed: {
    ...mapGetters([
      'getAlertList',
      'getTotal',
    ]),
    ...mapState({paginationAlerts: 'paginationAlerts'}),
  },
  methods: {
    ...mapActions([
      'setAlerts',
      'fetchWarningsPie',
      'setPageSize',
      'fetchKpiCalculated',
    ]),
    dateFormat,
    // TODO: ver si esto se exporta a utils o ke
    translate(data) {
      return this.$t(`dataTables.${data}`);
    },

    fetchAvergageKpi() {
      this.fetchKpiCalculated(5).then((kpiValue) => {
        const msec = kpiValue.value || 0;
        const tempTime = moment.duration(msec, 'milliseconds');
        this.averageTimeResolution = `${tempTime.hours()}h ${tempTime.minutes()}m ${tempTime.seconds()}s`;
      });
    },

    alertDetail(id) {
      console.log('HOLA', id);
      this.$router.push({path: `/alerts/${id}`});
    },

    addTagColor(column, scope) {
      if (column !== 'type') {
        return '';
      }
      return scope.type === 'DELAY_IN' ? 'blueTag tag' : 'greenTag tag';
    },
    addStatusColor(scope) {
      const statusColor = {
        open: 'redTag motion-alerts__dropdown',
        resolved: 'greenTag motion-alerts__dropdown',
        assigned: 'assignedTag motion-alerts__dropdown',
        informative: 'informativeTag motion-alerts__dropdown',
      };
      return statusColor[scope.status.toLowerCase()];
    },
    // Peticiones de alertas
    quickFilterAlerts(status) {
      this.setAlertsFn({status});
    },
    sort(obj) {
      this.setAlertsFn({page: 1, filterType: null, valueFilter: null, sort: obj.prop || 'none', order: obj.order});
    },
    pageChange(page) {
      this.setAlertsFn({page}, page);
    },
    onChangeFilter(filterParams) {
      this.setAlertsFn({page: 1, filterType: filterParams.filterType, valueFilter: filterParams.valueFilter});
    },
    setAlertsFn(params, page = 0) {
      this.setCurrentAlertsPage(page);
      this.setAlerts(params).then(() => {
        this.$refs.alertsTable.$el.querySelector('.ods-scrollbar > .ods-table__body-wrapper').scrollTop = 0;
      });
    },
    setCurrentAlertsPage(payload = 1) {
      this.currentAlertsPage = payload;
    },

    async submitAssignamentStatusForm(formData) {
      const body = formData;

      const warningId = formData.warningId;
      delete body.warningId;
      const status = 'ASSIGNED';

      try {
        await api.changeWarningStatus({warningId, status, body});
        setTimeout(() => {
          this.$notify.success({
            title: this.$t('warnings.dialogs.statusAssigned.confirmTitle'),
            message: `${this.$t('warnings.dialogs.statusAssigned.confirmPhrase')} ${formData.user.name} <br>
            <a href="/alerts/${warningId}" class="link-b">${this.$t('warnings.dialogs.detailView')}</a>`,
            dangerouslyUseHTMLString: true,
            position: 'top-right',
            duration: 10000,
          });
          this.setAlertsFn({page: 1});

          // kpi-filter set props
          this.fetchWarningsPie({field: 'status', ontologyName: 'warning'}).then((statusKpis) => {
            const defaultKpis = ['ASSIGNED', 'INFORMATIVE', 'OPEN', 'RESOLVED'];
            defaultKpis.forEach((item) => {
              const findedKpi = statusKpis.find(kpi => kpi._id === item);
              if (!findedKpi) {
                statusKpis.push({_id: item, count: 0});
              }
            });
            this.kpiCounts = statusKpis;
          });
          this.fetchAvergageKpi();
        }, 1000);
      } catch (error) {
        console.log(error);
      }

      this.dialogAssignmentStatus = false;
    },
    getOptionsWarning(warning) {
      const translatedWarningStatus = this.$t(`dataTables.${warning.status}2`);
      const warningOptions = statusMap[warning.status];
      let options = warningOptions.map(item => ({label: this.$t(`dataTables.${item}2`), value: item}));
      options = [...options, {label: translatedWarningStatus, value: warning.status, disabled: true}];
      return options;
    },
    getOptionSelected(selected, warningData) {
      const oldStatus = [warningData.status];
      const newStatus = selected[0];
      Vue.set(selected, 0, oldStatus[0]);

      const optionsDictionary = {
        OPEN: 'openDialogPendingStatus',
        ASSIGNED: 'openDialogAssignedStatus',
        RESOLVED: 'openDialogResolvedStatus',
      };
      this[optionsDictionary[newStatus]](warningData);
    },
    openDialogPendingStatus(warningData) {
      this.$msgbox({
        ...customSimpleDialogConfig,
        title: this.$t('warnings.dialogs.statusPending.title'),
        confirmButtonText: this.$t('warnings.dialogs.statusPending.confirmButtonText'),
        cancelButtonText: this.$t('warnings.dialogs.statusPending.cancelButtonText'),
      }).then(async () => {
        const warningId = warningData.warningId;
        const status = 'OPEN';
        try {
          await api.changeWarningStatus({warningId, status});

          this.$notify.success({
            title: this.$t('warnings.dialogs.statusPending.confirmTitle'),
            message: `${this.$t('warnings.dialogs.statusPending.confirmPhrase')} <br> <a href="/alerts/${warningId}" class="link-b">${this.$t('warnings.dialogs.detailView')}</a>`,
            dangerouslyUseHTMLString: true,
            position: 'top-right',
            duration: 10000,
          });

          this.setAlertsFn({page: 1});
        } catch (error) {
          console.log(error);
        }
      }).catch(() => {
        // console.log('no pending', warningData[status], action)
      });
    },
    openDialogResolvedStatus(warningData) {
      this.$msgbox({
        ...customSimpleDialogConfig,
        title: this.$t('warnings.dialogs.statusResolved.title'),
        confirmButtonText: this.$t('warnings.dialogs.statusResolved.confirmButtonText'),
        cancelButtonText: this.$t('warnings.dialogs.statusResolved.cancelButtonText'),
      })
        .then(async () => {
          const warningId = warningData.warningId;
          const status = 'RESOLVED';
          try {
            await api.changeWarningStatus({warningId, status});
            this.$notify.success({
              title: this.$t('warnings.dialogs.statusResolved.confirmTitle'),
              message: `${this.$t('warnings.dialogs.statusResolved.confirmPhrase')} <br> <a href="/alerts/${warningId}" class="link-b">${this.$t('warnings.dialogs.detailView')}</a>`,
              dangerouslyUseHTMLString: true,
              position: 'top-right',
              duration: 10000,
            });
            this.setAlertsFn({page: 1});
          } catch (error) {
            console.log(error);
          }
        })
        .catch(() => { console.log('no resolved'); });
    },
    openDialogAssignedStatus(warningData) {
      this.dialogAssignmentWarningId = warningData.warningId;
      this.dialogAssignmentStatus = true;
    },
  },
};
</script>

<style lang="scss" scoped>
h2 {
  margin-bottom: 30px;
}
// alerts notifications header
.ods-sub-header {
  padding: 25px 30px;
  h6 {
    font-size: 14px;
    margin: auto 0;
  }
}
.rule-settings__title {
  color: $--color-primary;
  font-size: 10px;
  font-weight: 500;
  line-height: 16px;
  text-align: right;
}

.rule-settings__icon {
  height: 32px;
  width: 32px;
  margin-left: 16px;
  color: $--color-white;
  background-color: $--color-primary;
  box-shadow: 0 2px 5px 0 rgba(46, 108, 153, 0.2);
  border-radius: 50%;
  display: inline-flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}

// main section general styles: includes alerts kpi filters with radio buttons and the data table
.alerts-container {
  display: flex;
  flex-direction: column;
  position: relative;
  top: 85px;
}

// alerts data table container
.alerts {
  padding: 44px 26px 20px;
  background: $--color-white;
  box-shadow: 0 2px 20px 0 rgba(0, 0, 0, 0.05);
  min-width: 1248px;
  margin: 0 auto 24px;
}

.table-filter {
  padding-bottom: 41px;
}
.ods-select {
  width: 200px;
  margin: 20px 0;
}

.filter-container {
  display: flex;
}

.ods-input__suffix-inner {
  display: flex;
}
.ods-input__icon .ods-icon-arrow-down {
  position: relative;
  left: 10px;
}

.motion-alerts__dropdown {
  height: 24px;
  border-radius: 4px;
  padding: 4px;
  text-transform: uppercase;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: $size-xs;
  font-weight: $font-weight-medium;
}

.table-row__entity-link {
  margin-left: 8px;
  text-transform: uppercase;
  color: $--color-primary;
  font-size: $size-ms;
  font-weight: $font-weight-medium;
}
.table-row__entity-icon {
  color: $--color-neutral-1;
  font-weight: $font-weight-bold;
}
</style>

<style lang="scss">
a.link-b {
  color: #2E6C99;
  text-transform: uppercase;
  font-size: 10px;
  font-weight: 500;
}
// radio buttons
.ods-radio__input {
  width: 16px;
  height: 16px;
}
// TODO: this should be modified from a scoped class
.ods-radio--medium.is-bordered .ods-radio__inner {
  height: 16px;
  width: 16px;
  &:after {
    width: 12px;
    height: 12px;
  }
}

// cascader
.motion-alerts__dropdown .ods-cascader__label {
  text-align: center;
  font-size: 9px;
  line-height: 16px;
  padding: 8px 24px 4px 12px;
}
.motion-alerts__dropdown.ods-cascader input.ods-input__inner:read-only {
  background-color: inherit;
  padding: 4px 15px;
}

.motion-alerts__dropdown.ods-cascader .ods-cascader__label {
  color: inherit;
}
// cascader dropdown arrow: TODO: convert it to a scoped one
.motion-alerts__dropdown .ods-input__icon.ods-icon-arrow-down {
  position: relative;
  top: -2px;
  font-size: 24px;
  right: 7px;
  font-weight: 500;
}

.motion-alerts__dropdown.redTag .ods-input__icon.ods-icon-arrow-down {
  color: $--color-danger;
}

.motion-alerts__dropdown.assignedTag .ods-input__icon.ods-icon-arrow-down {
  color: $--color-primary;
}

.motion-alerts__dropdown.greenTag .ods-input__icon.ods-icon-arrow-down {
  color: $--color-success;
}
.motion-alerts__dropdown.informativeTag .ods-input__icon.ods-icon-arrow-down {
  color: $--color-neutral-1;
}
// pagination
.ods-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
// modals
.ods-dialog.-custom-simple-dialog {
  padding: 18px 32px 20px 34px;

  .ods-dialog__title {
    font-size: 16px;
    font-weight: 500;
    line-height: 32px;
  }

  .ods-dialog__headerbtn {
    display: none;
  }
  .ods-dialog__footer {
    padding-top: 13px;

    .ods-button--text:first-child {
      padding-right: 10px;
    }
  }
}

.ods-form-item__label.-not-float {
  float: none;
}
</style>
