<template>
  <div class="full-width LogAuth">
    <div class="full-width LogAuth-TableHeader LogAuth-Row">
      <div class="LogAuth-TableHeader__Col">Дата и время</div>
      <div class="LogAuth-TableHeader__Col">Событие</div>
      <div class="LogAuth-TableHeader__Col">Тип Логина</div>
      <div class="LogAuth-TableHeader__Col">Статус</div>
      <div class="LogAuth-TableHeader__Col">ФИО</div>
      <div class="LogAuth-TableHeader__Col">Должность</div>
      <div class="LogAuth-TableHeader__Col">Организация</div>
    </div>
    <q-table
      grid
      v-bind="{ ...$props, ...$attrs }"
      @request="requestHandler"
      @update:pagination="paginationHandler"
      row-key="id"
    >
      <template v-slot:item="props">
        <div
          class="full-width LogAuth-Row LogAuth-Body"
          @click="props.expand = !props.expand"
          :class="classRow(props.row.status)"
        >
          <div>
            {{ formatDate(props.row.dateTime, 'DD-MM-YYYY HH:mm:ss.sss') }}
          </div>
          <div class="LogAuth-Element__TextCenter">
            {{ getEvent(props.row.event) }}
          </div>
          <div class="LogAuth-Element__TextCenter">
            {{ loginTypeMap[props.row.loginType] }}
          </div>
          <div class="LogAuth-Element__TextCenter">
            {{ props.row.status === 'SUCCESS' ? 'Успешно' : 'Не успешно' }}
          </div>
          <div class="LogAuth-Element__TextCenter">
            {{ props.row.memberName }}
          </div>
          <div class="LogAuth-Element__TextCenter">
            {{ props.row.memberPosition }}
          </div>
          <div class="LogAuth-Element__TextCenter">
            {{ props.row.departmentName }}
          </div>
        </div>
        <div class="full-width LogAuth-ExtraInfo" v-show="props.expand">
          <!--            <pre>{{ extraInfo(props.row.extraInfo) }}</pre>-->
          <div class="LogAuth-ExtraInfo__Header">Подробная информация</div>
          <div v-if="extraInfo(props.row.extraInfo).error">
            <div class="LogAuth-ExtraInfo__Line">
              <span>Ошибка</span>
              <span>{{ extraInfo(props.row.extraInfo).error }}</span>
            </div>
            <div class="LogAuth-ExtraInfo__Line">
              <span>Логин</span>
              <span>{{ extraInfo(props.row.extraInfo).login }}</span>
            </div>
          </div>
          <div v-if="!extraInfo(props.row.extraInfo).error">
            <div class="LogAuth-ExtraInfo__Line">
              <span>Идентификатор УЗ:</span>
              <span>{{ props.row.extraInfo.userId }}</span>
            </div>
            <div class="LogAuth-ExtraInfo__Line">
              <span>Статус УЗ:</span>
              <span>
                {{ getStatus(props.row.extraInfo.userStatus) }}
              </span>
            </div>
            <div class="LogAuth-ExtraInfo__Line">
              <span>Электронная почта:</span>
              <span>{{ props.row.extraInfo.userEmail }}</span>
            </div>
            <div class="LogAuth-ExtraInfo__Line">
              <span>Роли:</span>
              <span>
                {{ getRolesText(props.row.extraInfo.userRoles) }}
              </span>
            </div>
          </div>
        </div>
      </template>
    </q-table>
  </div>
</template>

<style lang="scss" scoped>
.LogAuth {
  &-Row {
    display: grid;
    grid-template-columns: 0.6fr 0.4fr 0.4fr 0.2fr 0.7fr 1.5fr 1.5fr;
  }
  &-Element {
    &__TextCenter {
      display: flex;
      justify-content: center;
      flex-direction: column;
    }
  }
  &-TableHeader {
    padding: 16px 0 6px 0;
    &__Col {
      color: rgba(2, 12, 18, 0.58);
      overflow: hidden;
      font-family: 'Golos Text', sans-serif;
      font-style: normal;
      font-weight: 600;
      font-size: 10px;
      line-height: 12px;
      letter-spacing: 0.05em;
      text-transform: uppercase;
      padding-left: 4px;
    }
  }
  &-Body {
    max-height: 5em;
    padding: 4px 0 4px 0;
    margin: 2px 0 2px 0;
    border: 1px solid rgba(1, 72, 116, 0.11);
    border-radius: 8px;
    box-shadow: none;
    &__Success {
      background-color: rgba(227, 254, 250, 1);
      &:hover {
        cursor: pointer;
      }
    }
    &__Error {
      background-color: rgba(254, 227, 231, 1);
      &:hover {
        cursor: pointer;
      }
    }
    > div {
      position: relative;
      padding: 0 4px 0 4px;
      overflow: hidden;
      color: rgba(2, 12, 18, 0.9);
      font-family: 'Golos UI', sans-serif;
      font-style: normal;
      font-weight: 400;
      font-size: 12px;
      line-height: 14px;
    }
    &:hover {
      border: 1px solid #1491cf;
      box-shadow: 0 0.6px 1.8px rgba(7, 46, 71, 0.12),
        0 3.2px 8px rgba(7, 46, 71, 0.15);
    }
  }
  &-ExtraInfo {
    padding: 5px;
    border: 1px solid rgba(1, 72, 116, 0.11);
    &__Row {
      padding: 4px 0 4px 4px;
      font-size: 12px;
    }
    &__Header {
      color: rgba(2, 12, 18, 0.58);
      font-family: 'Golos Text', sans-serif;
      font-size: 16px;
      font-style: normal;
      font-weight: 600;
      line-height: 16px;
      margin-bottom: 10px;
    }
    &__Line {
      width: 100%;
      display: grid;
      grid-template-columns: 0.2fr 1fr;
      font-family: 'Golos UI', sans-serif;
      font-size: 12px;
      &:not(:last-child) {
        border-bottom: 1px solid rgba(1, 72, 116, 0.11);
      }
    }
  }
}
::v-deep .q-table__bottom {
  font-family: 'Golos UI', sans-serif;
  font-style: normal;
  font-weight: 400;
  font-size: 14px;
  line-height: 16px;
  color: rgba(2, 12, 18, 0.58);
}
</style>

<script lang="ts">
import { Component, Emit, Prop, Vue } from 'vue-property-decorator';

import { formatDate } from '@/recruits/utils';
import {
  AuthExtraInfoV2,
  AuthJournalRecordV2,
} from '@/recruits/openapi/journal-service';
import { Option } from '@/recruits/models';
import { LOGIN_TYPE_OPTIONS } from '@/recruits/components/log/log-auth/search-filter';

const authEventTypes: Record<string, string> = {
  USER_AUTHENTICATED: 'Авторизация',
  USER_AUTHENTICATION_ERROR: 'Авторизация',
  LOGOUT_SUCCESSFUL: 'Выход из системы',
  LOGOUT_ERROR: 'Выход из системы',
};

@Component({
  methods: { formatDate },
})
export default class DataTable extends Vue {
  @Prop({ default: () => [], type: Array }) data: AuthJournalRecordV2[];

  @Emit('update:pagination')
  paginationHandler() {}

  @Emit('request')
  requestHandler(value: any) {}

  classRow(status: string): string {
    return status === 'SUCCESS'
      ? 'LogAuth-Body__Success'
      : 'LogAuth-Body__Error';
  }

  getEvent(event: string): string {
    return authEventTypes[event] || 'Не известное событие';
  }

  getRolesText(roles: AuthExtraInfoV2['userRoles']): string {
    return roles?.join(', ') || '';
  }

  getStatus(status: string): string {
    return status === 'true' ? 'Активна' : 'Не активна';
  }

  get loginTypeOptions(): Option[] {
    return LOGIN_TYPE_OPTIONS;
  }

  get loginTypeMap(): Record<string, string> {
    return this.loginTypeOptions.reduce(
      (map: Record<string, string>, { value, label }) => {
        map[value] = label;
        return map;
      },
      {}
    );
  }

  extraInfo(info: Record<any, any>): Record<string, unknown> {
    const data = {
      email: '',
      enabled: '',
      gender: '',
      userId: '',
      org: '',
      workMail: '',
      scopes: '',
      error: '',
      login: '',
    };
    if (info.hasOwnProperty('error')) {
      data.error = info?.error || '';
      data.login = info?.login || '';
    } else {
      data.email = info?.userIdentity?.email || 'Не известно';
      data.enabled = info?.userIdentity?.enabled
        ? 'Активна'
        : 'Не активна' || 'Не известно';
      data.gender = info?.userIdentity?.extAttributes?.gender || 'Не известно';
      data.userId =
        info?.userIdentity?.extAttributes?.person_id || 'Не известно';
      data.org = info?.userIdentity?.userAccount?.displayName || 'Не известно';
      data.workMail =
        info?.userIdentity?.userAccount?.extAttributes?.workmail ||
        'Не известно';
      data.scopes = 'Не известно';
      if (info?.allowedScopes && info?.allowedScopes.length) {
        data.scopes = info?.allowedScopes.reduce(
          (scopes: string[], currentScope: Record<string, any>) => {
            scopes.push(currentScope.displayName);
            return scopes;
          },
          []
        );
      }
    }
    return data;
  }
}
</script>
