<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"
          :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="action"
        />
        <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, Mixins, PropSync, Prop } from 'vue-property-decorator';
import { FileInfo } from '@/components/common/r-file-loader';
import S3UrlSignerFilesService from '@/recruits/services/s3UrlService/files';
import UploadStatus from '@/components/common/upload-status/index.vue';
import ProcessStarter from '@/mixins/ProcessStarter';

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

@Component({
  components: {
    UploadStatus,
  },
})
export default class UploadQuitance extends Mixins(ProcessStarter) {
  @PropSync('opened', { default: true }) isOpened: boolean;
  @Prop({ default: () => [] }) ids: string[];

  @Prop({ default: 'milBaseUserActionDistribute' }) declare processKey: string;

  files: FileInfo[] = [];
  descName = '';
  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/quitances/${file.file.name}`,
    });
    if (!s3Url) throw new Error('Не удалось загрузить файл');
    return {
      s3Url,
      name: file.file.name,
    };
  }

  async action(): Promise<void> {
    if (this.status) return;
    try {
      this.status = 'pending';
      this.descName = 'Загрузка..';
      const fileInfo = await this.saveDocument(this.files[0]);

      const traceId = await this.startProcess({
        privateFileIds: this.ids,
        actionType: 'privateFileAccept',
        docInfo: {
          s3Url: fileInfo.s3Url,
          s3Name: fileInfo.name,
        },
      });

      this.registerListener((message, removeListener) => {
        if (traceId !== message.traceId) return;
        if (message?.body?.type === 'finish') {
          this.status = 'success';
          this.descName = 'Файл загружен';
          removeListener();
          this.$emit('refresh');
        }
      });
    } catch (e) {
      console.log(e);
      this.status = 'error';
      this.descName = 'Ошибка';
    }
  }

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

  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>
