<template>
  <q-dialog
    v-model="isOpened"
    position="right"
    full-height
    maximized
    persistent
  >
    <q-card class="dialog-content full-width full-height">
      <header>Импортировать коды загрузки ЛД</header>
      <main v-if="!status">
        <r-file-loader
          supported-file=".json"
          v-model="files"
          @change="addFile"
        />
      </main>
      <main v-else class="flex items-center justify-center">
        <upload-status
          :status="status"
          :label="descName"
          :file-name="description"
          :reverse-labels-order="true"
          :label-size="16"
        />
      </main>
      <footer>
        <r-btn
          v-if="!status"
          outline
          label="Отмена"
          icon="pgs-close"
          color="primary"
          @click="close"
        />
        <div />
        <r-btn
          v-if="!status"
          action
          label="Импортировать"
          :disable="!files.length"
          icon-right="pgs-shevron-right-off"
          @click="importCodes"
        />
        <r-btn
          v-else
          action
          label="Продолжить"
          :disable="status === 'pending'"
          icon-right="pgs-shevron-right-off"
          @click="close"
        />
      </footer>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { Component, PropSync } from 'vue-property-decorator';
import Vue from 'vue';
import { FileInfo } from '@/components/common/r-file-loader';
import S3UrlSignerFilesService from '@/recruits/services/s3UrlService/files';
import { PersonRegistryApi } from '@/recruits/openapi/person-registry';
import UploadStatus from '@/components/common/upload-status/index.vue';

interface DocumentInfo {
  s3Url: string;
  name: string;
  sigUrl?: string;
  sigName?: string;
}

@Component({
  components: {
    UploadStatus,
  },
})
export default class ImportCodes extends Vue {
  @PropSync('opened', { default: true }) isOpened: boolean;

  private personRegistryApi = new PersonRegistryApi();
  files: FileInfo[] = [];
  descName = '';
  description = '';
  status = '';

  addFile(files: FileInfo[]): void {
    this.files = files;
  }

  async saveDocument(file: FileInfo): Promise<DocumentInfo> {
    if (!file.file) throw new Error('');
    const s3Url = await S3UrlSignerFilesService.uploadFileToS3ByPath({
      bucket: 'ervu-attachment',
      file: file.file,
      path: `PersonalFiles/codes-to-import/file/${file.file.name}`,
    });
    if (!s3Url) throw new Error('Не удалось загрузить файл');
    return {
      s3Url,
      name: file.file.name,
    };
  }

  async importCodes(): Promise<void> {
    if (this.status) return;
    try {
      this.status = 'pending';
      this.descName = 'Загрузка..';
      this.description = 'Файл загружается';
      const fileInfo = await this.saveDocument(this.files[0]);
      const { data } = await this.personRegistryApi.importLDCodesV1({
        s3Url: fileInfo.s3Url,
        fileName: fileInfo.name,
      });
      console.log('importCodes', data);
      this.status = data.statusLoad === 'success' ? 'success' : 'error';
      this.descName = data.descName;
      this.description = data.description ?? '';
    } catch (e) {
      console.log(e);
      this.status = 'error';
      this.descName = 'Ошибка';
      this.description = 'Не удалось загрузить файл';
    }
  }

  resetStatus(): void {
    this.status = '';
    this.descName = '';
    this.description = '';
  }

  close(): void {
    this.resetStatus();
    this.isOpened = false;
  }
}
</script>

<style lang="scss" scoped>
.dialog-content {
  display: grid;
  width: 600px !important;
  height: 100%;
  display: grid;
  gap: 12px;
  grid-template-rows: min-content 1fr min-content;
  background: white;
  z-index: 10;
}

header {
  padding: 8px;
  font-family: 'Golos Text';
  font-style: normal;
  font-weight: 500;
  font-size: 20px;
  line-height: 24px;
  letter-spacing: -0.015em;
  color: rgba(2, 12, 18, 0.9);
}

main {
  overflow: auto;
  padding: 8px;
}

footer {
  display: flex;
  justify-content: space-between;
  background: rgba(15, 32, 160, 0.08);
  position: sticky;
  bottom: 0;
  padding: 8px;
}
</style>
