<template>
  <div class="full-width LogImport">
    <div class="full-width LogImport-TableHeader LogImport-Row">
      <div class="LogImport-TableHeader__Col q-pl-xs">Начало</div>
      <div class="LogImport-TableHeader__Col q-pl-xs">Окончание</div>
      <div class="LogImport-TableHeader__Col q-pl-xs">Время</div>
      <div class="LogImport-TableHeader__Col q-pl-xs">Статус операции</div>
      <div class="LogImport-TableHeader__Col q-pl-xs">Событие</div>
      <div class="LogImport-TableHeader__Col q-pl-xs">Инициатор</div>
      <div class="LogImport-TableHeader__Col q-pl-xs">Файл</div>
      <div class="LogImport-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 LogImport-Row LogImport-Body"
          @click="handleClick(props)"
          :class="classRow(props.row)"
        >
          <div class="LogImport-Body__Cell">
            {{ formatDate(props.row.dateTimeStart, 'DD-MM-YYYY HH:mm:ss.sss') }}
          </div>
          <div class="LogImport-Body__Cell">
            {{ formatDate(props.row.dateTimeEnd, 'DD-MM-YYYY HH:mm:ss.sss') }}
          </div>
          <div class="LogImport-Body__Cell">
            {{ props.row.duration }}
          </div>
          <div class="LogImport-Body__Cell">
            {{ getStatus(props.row) }}
          </div>
          <div class="LogImport-Body__Cell">{{ props.row.source }}</div>
          <div class="LogImport-Body__Cell LogImport-Body__Cell_VK">
            <div class="LogImport-Body__Cell_FullName">
              {{ props.row.fullName }}
            </div>
            <div class="LogImport-Body__Cell_NameVK">
              {{ props.row.nameVK }}
            </div>
          </div>
          <div class="LogImport-Body__Cell LogImport-Body__CellFile">
            <q-icon
              class="LogImport-Icon LogImport-Body__CellFile_Icon"
              name="pgs-save"
              @click.stop="downloadFile(props.row)"
            >
              <q-tooltip>Скачать</q-tooltip>
            </q-icon>
            <div>
              <div>
                {{ props.row.fileName }}
              </div>
              <div
                v-if="props.row.fileInfo"
                class="LogImport-Body__CellFile_Id"
              >
                {{ props.row.fileInfo.s3Name }}
              </div>
            </div>
          </div>
          <div
            class="LogImport-Body__Cell LogImport-Body__CellCounts"
            v-if="isSuccess(props.row)"
          >
            <div
              class="LogImport-Body__CellCounts_Success"
              :class="{
                'LogImport-Body__CellCounts_Clickable': isImport(props.row),
              }"
              @click.stop="openLogPage('success', props.row.id)"
            >
              <span>Успешно</span>
              <span>{{ props.row.successCount || 0 }}</span>
            </div>
            <div
              class="LogImport-Body__CellCounts_Error"
              :class="{
                'LogImport-Body__CellCounts_Clickable': isImport(props.row),
              }"
              @click.stop="openLogPage('error', props.row.id)"
            >
              <span>С ошибками</span>
              <span>{{ props.row.errorCount || 0 }}</span>
            </div>
          </div>
          <div
            class="LogImport-Body__Cell LogImport-Body__ErrorsInfo"
            v-if="props.row.status === 'FAILED'"
          >
            <div class="LogImport-Body__ErrorsInfo_Message">
              {{ getMessageError(props.row) }}
            </div>
            <div class="LogImport-Body__ErrorsInfo_Code">
              <span>Код:</span>
              <span>{{ getCodeError(props.row) }}</span>
            </div>
          </div>
        </div>
        <q-card v-if="props.expand" class="LogImport-Body__ErrorInfoCard">
          <q-card-section>
            <q-list bordered separator>
              <q-item
                v-for="error in props.row.importErrorInfo"
                class="LogImport-Body__ErrorInfoList"
                :key="error.id"
              >
                <span>{{ error.code }}</span>
                <span>{{ error.message }}</span>
                <span>
                  <template v-for="string in error.description">
                    {{ string }}
                  </template>
                </span>
              </q-item>
            </q-list>
          </q-card-section>
        </q-card>
      </template>
    </q-table>
  </div>
</template>

<style lang="scss" scoped>
.LogImport {
  &-Icon {
    margin-left: 5px;
    font-size: 22px;
    cursor: pointer;
  }
  &-Row {
    display: grid;
    grid-template-columns: 0.3fr 0.3fr 0.35fr 0.4fr 0.55fr 1.2fr 1.2fr 0.9fr;
  }
  &-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 {
    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;

    &__ErrorInfoCard {
      width: 100%;
    }
    &__ErrorInfoList {
      display: flex;
      flex-direction: column;
    }
    &__Cell {
      display: flex;
      align-items: center;
      &_VK {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
      }
      &_FullName {
        font-size: 12px;
        font-weight: 500;
        margin-bottom: 3px;
      }
      &_NameVK {
        font-size: 10px;
      }
    }
    &__CellFile {
      display: flex;
      align-items: center;
      &_Icon {
        margin-right: 6px;
      }
      &_Id {
        color: rgba(2, 12, 18, 0.58);
        font-size: 10px;
      }
    }
    &__CellCounts {
      display: flex;
      justify-content: flex-start;
      &_Success {
        display: flex;
        flex-direction: column;
        align-items: center;
        border: 1px solid #04967d;
        width: 80px;
        color: #04967d;
        padding: 2px 4px;
        font-weight: 600;
        margin-right: 6px;
      }
      &_Error {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 80px;
        border: 1px solid #cf5f14;
        padding: 2px 4px;
        font-weight: 600;
        color: #cf5f14;
      }
      &_Clickable {
        cursor: pointer;
      }
    }
    &__ErrorsInfo {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: center;
      &_Message {
        font-size: 10px;
        font-weight: 500;
      }
      &_Code {
        font-size: 10px;
        & span:last-child {
          margin-left: 5px;
          font-weight: 500;
        }
      }
    }
    &__Success {
      background-color: rgba(227, 254, 250, 1);
    }
    &__Clickable {
      cursor: pointer;
    }
    &__Error {
      background-color: rgba(254, 227, 231, 1);
      cursor: pointer;
    }
    &__InProgress {
      background-color: rgba(253, 243, 237, 1);
    }
    > 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 {
    border: 1px solid rgba(1, 72, 116, 0.11);
    &__Row {
      padding: 4px 0 4px 4px;
      font-size: 12px;
    }
  }
  &-SubTable {
    padding: 5px;
    &__Header {
      color: rgba(2, 12, 18, 0.58);
      overflow: hidden;
      font-family: 'Golos Text', sans-serif;
      font-style: normal;
      font-size: 9px;
      text-transform: uppercase;
    }
    &__Info {
      font-family: 'Golos Text', sans-serif;
      font-size: 12px;
      font-weight: 500;
      & > span {
        margin-right: 10px;
      }
    }
    &__ColHeader {
      padding: 2px 4px;
      &:not(:last-child) {
        border-right: 1px solid rgba(1, 72, 116, 0.11);
      }
    }
    &__ColBody {
      padding: 2px 4px;
      font-family: 'Golos Text', sans-serif;
      font-size: 10px;
      &:not(:last-child) {
        border-right: 1px solid rgba(1, 72, 116, 0.11);
      }
    }
    &__Row {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
    }
  }
  &-Link {
    color: #015e98;
    font-family: 'Golos UI', sans-serif;
    font-size: 14px;
    text-decoration: none;
  }
}
::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 get from 'lodash/get';

import { formatDate } from '@/recruits/utils';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { saveBlob } from '@utils/files';
import {
  ImportJournalRecordV2,
  ImportErrorInfo,
} from '@/recruits/openapi/journal-service';
import isArray from 'lodash/isArray';
import { QTableItemProps } from '@/recruits/interfaces/quasar.interfaces';

const JOURNAL_RECORD_TYPE = {
  FILE: 'file',
  IMPORT: 'import',
};

const JOURNAL_RECORD_STATUS = {
  SUCCESS: 'SUCCESS',
  FAILED: 'FAILED',
};

@Component({
  methods: { formatDate, get },
})
export default class DataTable extends Vue {
  @Emit('update:pagination')
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  paginationHandler(): void {}

  @Emit('request')
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  requestHandler(): void {}

  classRow(row: ImportJournalRecordV2): string {
    switch (row.status) {
      case 'SUCCESS': {
        let classRow = 'LogImport-Body__Success';
        if (row.type === JOURNAL_RECORD_TYPE.IMPORT)
          classRow = `${classRow} LogImport-Body__Clickable`;
        return classRow;
      }
      case 'IN_PROGRESS':
        return 'LogImport-Body__InProgress';
      default:
        return 'LogImport-Body__Error';
    }
  }

  getCodeError(row: ImportJournalRecordV2): string {
    if (row.status === 'FAILED') {
      if (isArray(row.importErrorInfo)) {
        return row.importErrorInfo[0]?.code
          ? row.importErrorInfo[0]?.code
          : 'Неизвестная ошибка';
      } else {
        return 'Неизвестная ошибка';
      }
    } else {
      return this.getStatus(row);
    }
  }

  getMessageError(row: ImportJournalRecordV2): string {
    if (row.status === 'FAILED') {
      if (isArray(row.importErrorInfo)) {
        return row.importErrorInfo[0]?.message || 'Нет кода';
      } else {
        return '';
      }
    } else {
      return this.getStatus(row);
    }
  }

  // открытие подробной страницы
  openLogPage(status: 'success' | 'error', importId: string): void {
    if (importId) {
      switch (status) {
        case 'success':
          this.$router.push({
            name: `log-success`,
            query: { importId },
          });
          break;
        case 'error':
          this.$router.push({
            name: `log-error`,
            query: { importId },
          });
          break;
      }
    }
  }

  // функция получения человекочитаемого статуса
  getStatus(log: ImportJournalRecordV2): string {
    // FIXME с бэка приходит errorImportInfo вместо ImportErrorInfo
    const errorInfo: ImportErrorInfo[] = get(log, 'errorImportInfo', []);
    // const errorInfo: ImportErrorInfo[] = get(log, 'ImportErrorInfo', []);
    switch (log.status) {
      case 'SUCCESS':
        return 'Завершена';
      case 'IN_PROGRESS':
        return 'В процессе обработки';
      default:
        // если есть errorInfo то из него достаем все code ошибок
        // иначе просто выводим сообщение "Не успешно"
        return (
          errorInfo.map((importError) => importError.code).join(', ') ||
          'Не успешно'
        );
    }
  }

  handleClick(props: QTableItemProps<ImportJournalRecordV2>): void {
    if (this.isSuccess(props.row) && this.isImport(props.row)) {
      const id = props.row.id;
      this.$router.push({ name: 'import-details', params: { id } });
    } else if (props.row.status === JOURNAL_RECORD_STATUS.FAILED) {
      props.expand = !props.expand;
    }
  }

  isSuccess(row: ImportJournalRecordV2): boolean {
    return row.status === JOURNAL_RECORD_STATUS.SUCCESS;
  }

  isImport(row: ImportJournalRecordV2): boolean {
    return row.type === JOURNAL_RECORD_TYPE.IMPORT;
  }

  async downloadFile(row: ImportJournalRecordV2): Promise<void> {
    const fileInfo = row.fileInfo;
    try {
      const { file: blob } = await S3UrlSignerFilesService.fetchFileFromS3ByUrl(
        {
          url: fileInfo.s3url,
        }
      );
      saveBlob({
        blob,
        fileName: row.fileName,
        blobType: 'text/xml',
      });
    } catch (e) {
      console.log(e);
    }
  }
}
</script>
