<template>
  <div class="full-width LogAuth">
    <div class="full-width LogAuth-TableHeader LogAuth-Row">
      <div class="LogAuth-TableHeader__Col q-pl-xs">Дата и время события</div>
      <div class="LogAuth-TableHeader__Col q-pl-xs">ФИО</div>
      <div class="LogAuth-TableHeader__Col q-pl-xs">Организация</div>
      <div class="LogAuth-TableHeader__Col q-pl-xs">Операция</div>
      <div class="LogAuth-TableHeader__Col q-pl-xs">Раздел</div>
      <div class="LogAuth-TableHeader__Col q-pl-xs">Описание</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 class="LogAuth-Element__TextCenter">
            {{ formatDate(props.row.eventTime, 'DD-MM-YYYY HH:mm:ss') }}
          </div>
          <div class="LogAuth-Element__TextCenter">
            {{ props.row.userName }}
          </div>
          <div class="LogAuth-Element__TextCenter">
            {{ props.row.vkName }}
          </div>
          <div class="LogAuth-Element__TextCenter">
            {{ eventName(props.row.event) }}
          </div>
          <div class="LogAuth-Element__TextCenter">
            <template v-for="line in readBreadcrumbs(props.row)">
              {{ line }}
            </template>
          </div>
          <div class="LogAuth-Element__TextCenter">
            <span v-if="props.row.description">
              {{ props.row.description }}
            </span>
            <span
              v-for="info in get(props, 'row.extraInfo.previewInfo')"
              :key="info.value || info.label"
            >
              {{ info.label ? `${info.label} - ${info.value}` : info.value }}
            </span>
            <span v-for="entry in extractExtraInfo(props.row.extraInfo)">
              {{ entry.key }} - {{ entry.value }}
            </span>
            <span v-if="recordCount(props.row.extraInfo)">
              {{ recordCount(props.row.extraInfo) }}
            </span>
          </div>
        </div>
        <div class="full-width LogAuth-ExtraInfo" v-show="props.expand">
          <q-list bordered separator>
            <q-expansion-item
              v-if="isShowDetails(props.row.extraInfo)"
              label="Подробные сведения"
            >
              <q-card>
                <q-card-section>
                  <div class="column">
                    <span
                      v-for="info in get(props, 'row.extraInfo.detailedInfo')"
                      :key="info.label"
                    >
                      {{ getInfo(info) }}
                    </span>
                  </div>
                  <q-list
                    v-if="get(props, 'row.extraInfo.list.length')"
                    bordered
                    separator
                  >
                    <q-item
                      v-for="(info, i) in get(props, 'row.extraInfo.list')"
                      class="column"
                      :key="info.idERN || info.fio || `info_${i}`"
                    >
                      <span
                        v-for="entry in extractExtraInfo(info)"
                        :key="entry.key"
                      >
                        {{ entry.key }} - {{ entry.value }}
                      </span>
                    </q-item>
                  </q-list>
                </q-card-section>
              </q-card>
            </q-expansion-item>
            <q-expansion-item label="JSON">
              <q-card>
                <q-card-section>
                  <pre>{{
                    JSON.stringify(props.row, null, 2).slice(2, -1)
                  }}</pre>
                </q-card-section>
              </q-card>
            </q-expansion-item>
          </q-list>
        </div>
      </template>
    </q-table>
  </div>
</template>

<style lang="scss" scoped>
.crumbs {
  > span {
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.LogAuth {
  &-Row {
    display: grid;
    grid-template-columns: 0.6fr 0.8fr 1.5fr 0.4fr 1.5fr 1fr;
  }
  &-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;
    }
  }
  &-Body {
    background: white;
    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 {
      // FIXME это отрабатывает в случае если нет даты для расширения
      //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 {
    > pre {
      margin: 0;
      margin-right: 10px;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    font-size: 12px;

    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, Vue } from 'vue-property-decorator';

import { formatDate } from '@/recruits/utils';
import { get } from 'lodash';

const eventTypes: { [key: string]: string } = {
  navigation: 'Навигация',
  action: 'Действие',
};

interface Info {
  label: string;
  value: string;
  type: string;
}
const priorities: { [key: string]: number } = {
  series: 1,
  number: 2,
  idERN: 3,
  fio: 4,
  target: 5,
  date: 6,
  documentName: 7,
};

@Component({
  methods: { formatDate, get },
})
export default class DataTable extends Vue {
  @Emit('update:pagination')
  paginationHandler(): void {
    //
  }

  @Emit('request')
  requestHandler(): void {
    //
  }

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

  eventName(event: string): string {
    return eventTypes[event] || event;
  }

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

  getInfo(info: Info): string {
    const valueToView =
      info.type === 'date'
        ? formatDate(info.value, 'DD.MM.YYYY HH:mm')
        : info.value;
    return `${info.label} - ${valueToView}`;
  }

  readBreadcrumbs(row: any): Array<string> {
    const result: Array<string> = [];
    if (
      row.extraInfo &&
      Array.isArray(row.extraInfo.breadcrumbs) &&
      row.extraInfo.breadcrumbs.length
    ) {
      row.extraInfo.breadcrumbs.forEach((crumb: string) => {
        result.push(`${crumb}`);
      });
    }
    return [result.join(' 🡪 ')];
  }

  recordCount(extraInfo: any): string {
    const count = extraInfo?.list?.length || 0;
    return count ? `Количество записей - ${count}` : '';
  }

  isShowDetails(extraInfo: any): boolean {
    return extraInfo?.detailedInfo || extraInfo?.list?.length;
  }

  extractExtraInfo(extraInfo: any) {
    function translate(value: any) {
      const dictionary: { [key: string]: string } = {
        idERN: 'ИД ЕРН',
        subpoena: 'повестка',
        id: 'идентификатор',
        fio: 'ФИО',
        number: 'номер',
        series: 'серия',
        type: 'тип сущности',
        recruit: 'гражданин',
        'call-list': 'список на вызов',
        birthDate: 'дата рождения',
        documentType: 'тип документа',
        comment: 'комментарий',
        date: 'дата',
        target: 'цель',
        documentName: 'Наименование документа',
      };
      return dictionary[value] || value;
    }

    function sortEntries(entries: Array<[string, string]>) {
      function getPriority(key: string): number {
        return priorities[key] || 0;
      }
      entries.sort((a, b) => getPriority(a[0]) - getPriority(b[0]));
      return entries;
    }

    return sortEntries(Object.entries(extraInfo))
      .filter(([key]) => Object.keys(priorities).includes(key))
      .map(([key, value]) => ({
        key: translate(key),
        value: translate(value),
      }));
  }

  extraInfo(info: Record<any, any>): Record<string, unknown> {
    const data = {
      userName: '',
      event: '',
      position: '',
      buttonCode: '',
      eventTime: '',
    };
    // 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>
