<template>
  <div class="full-width JournalSmev">
    <div class="full-width JournalSmev-TableHeader JournalSmev-Row">
      <div class="JournalSmev-TableHeader__Col q-pl-xs">Дата и время</div>
      <div class="JournalSmev-TableHeader__Col q-pl-xs">Наименование ВС</div>
      <div class="JournalSmev-TableHeader__Col q-pl-xs">Класс ВС</div>
      <div class="JournalSmev-TableHeader__Col q-pl-xs">Тип</div>
      <div class="JournalSmev-TableHeader__Col q-pl-xs">ФОИВ</div>
      <div class="JournalSmev-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 JournalSmev-Row JournalSmev-Body"
          @click="props.expand = !props.expand"
        >
          <div class="JournalSmev-Cell">
            {{ formatDate(props.row.createDate, 'DD.MM.YYYY HH:mm:ss.SSS') }}
          </div>
          <div class="JournalSmev-Cell JournalSmev-Cell__Name">{{ props.row.mzName }}</div>
          <div class="JournalSmev-Cell JournalSmev-Cell__Class">{{ props.row.mzClass }}</div>
          <!-- <div>{{ getMzMode(props.row.mzMode) }}</div> -->
          <div class="JournalSmev-Cell">
            {{ getMzDirection(props.row.mzDirection) }}
          </div>
          <div class="JournalSmev-Cell">
            {{ props.row.externalSystem }}
          </div>
          <div class="JournalSmev-file">
            <q-icon
              class="JournalSmev-Icon JournalSmev-Body__CellFile_Icon"
              name="pgs-save"
              @click.stop="downloadXML(props.row.id)"
            >
              <q-tooltip>Скачать</q-tooltip>
            </q-icon>
            <div>
              <div class="JournalSmev-Body__CellFile_Id">
                Файл сообщения СМЭВ.xml
              </div>
            </div>
          </div>
        </div>
        <div class="full-width JournalSmev-ExtraInfo" v-show="props.expand">
          <div v-if="props.row.messageId">
            {{ `messageId ${props.row.messageId}` }}
          </div>
          <div class="JournalSmev-ExtraInfo-Title">Тело сообщения</div>
          <div>{{ props.row.mzBody }}</div>
          <div
            class="JournalSmev-ExtraInfo-Title JournalSmev-ExtraInfo-Title__MarginTop"
            v-if="props.row.files.length"
          >
            Вложения
          </div>
          <div class="JournalSmev-ExtraInfo-Row">
            <div
              v-for="file in props.row.files"
              :key="file.s3url"
              class="JournalSmev-file"
            >
              <q-icon
                class="JournalSmev-Icon JournalSmev-Body__CellFile_Icon"
                name="pgs-save"
                @click.stop="downloadFile(file)"
              >
                <q-tooltip>Скачать</q-tooltip>
              </q-icon>
              <div>
                <div class="JournalSmev-ExtraInfo__CellFile_Id">
                  {{ file.s3Name }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </q-table>
    <q-dialog v-model="apiErrorShow" no-backdrop-dismiss>
      <api-errors :errorObject="errorInResponse" />
    </q-dialog>
  </div>
</template>

<style lang="scss" scoped>
.JournalSmev {
  &-file {
    display: flex;
    gap: 10px;
    align-items: center;
  }
  &-Icon {
    margin-left: 5px;
    font-size: 22px;
    cursor: pointer;
  }
  &__CellFile {
    display: flex;
    align-items: center;
    &_Icon {
      margin-right: 6px;
    }
    &_Id {
      color: rgba(2, 12, 18, 0.58);
      font-size: 10px;
    }
  }
  &-Row {
    display: grid;
    grid-template-columns: 1.5fr 2fr 2fr 1fr 1.5fr 140px;
  }
  &-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;
    cursor: pointer;
    &__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-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);
    }
  }
  &-Cell {
    display: flex;
    justify-content: center;
    flex-direction: column;
    &__Name {
      font-weight: 500;
    }
    &__Class {
      word-break: break-all;
    }
  }
  &-ExtraInfo {
    font-size: 12px;
    padding: 10px 5px;
    background: white;
    border: 1px solid rgba(1, 72, 116, 0.11);
    border-radius: 8px;

    &-Title {
      font-weight: 600;
      font-size: 14px;

      &__MarginTop {
        margin-top: 20px;
      }
    }

    &__CellFile_Id {
      word-break: break-all;
    }

    &-Row {
      display: grid;
      gap: 10px;
      grid-template-columns: 1fr 1fr 1fr;
    }
  }
}
::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 { mzDirections, mzMods } from './utils';
import {
  S3File,
  ErvuMzMonitorServiceApi,
} from '@/recruits/openapi/ervu-service';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { saveBlob } from '@utils/files';

@Component({
  methods: { formatDate },
})
export default class DataTable extends Vue {
  ervuMzMonitorServiceApi = new ErvuMzMonitorServiceApi();

  apiErrorShow = false;
  errorInResponse: unknown = {};

  @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 {}

  getMzMode(mzModeCode: string): string {
    const resultMzMode = mzMods.filter((mzMode) => mzMode.value === mzModeCode);
    return resultMzMode[0]?.label || '-';
  }

  getMzDirection(mzDirectionCode: string): string {
    const resultmzDirection = mzDirections.filter(
      (mzDirection) => mzDirection.value === mzDirectionCode
    );
    return resultmzDirection[0]?.label || '-';
  }

  downloadXML(id: string): void {
    this.ervuMzMonitorServiceApi
      .getMzXmlV1(id)
      .then((response) => {
        const blob: Blob = new Blob([response.data], {
          type: 'text/xml',
        });
        saveBlob({
          blob,
          fileName: 'Файл_сообщения_СМЭВ.xml',
          blobType: 'text/xml',
        });
      })
      .catch((error) => {
        this.errorInResponse = error;
        this.apiErrorShow = true;
      });
  }

  async downloadFile(file: S3File): Promise<void> {
    try {
      const { file: blob } = await S3UrlSignerFilesService.fetchFileFromS3ByUrl(
        {
          url: file.s3url,
        }
      );
      saveBlob({
        blob,
        fileName: file.s3Name,
        blobType: 'text/xml',
      });
    } catch (error) {
      this.errorInResponse = error;
      this.apiErrorShow = true;
    }
  }
}
</script>
