<i18n>
{
  "en": {
    "InterdepartmentalCard": {
      "attachments":"attachments",
      "confirmationMessage": "Are you sure you want to delete attachment?",
      "addFile":"Upload template file",
      "addAttachment":"Add attachment",
      "deleteAttachment":"Remove attachment",
      "downloadAttachment":"Download attachment"
    }
  },
  "ru": {
    "InterdepartmentalCard": {
      "confirmationMessage": "Вы уверены, что хотите удалить вложение?",
      "attachments":"Вложения",
      "addFile":"Загрузить файл шаблона",
      "addAttachment":"Добавить вложение",
      "deleteAttachment":"Удалить вложение",
      "downloadAttachment":"Скачать вложение"
    }
  }
}
</i18n>

<template>
  <div>
    <a ref="export" v-show="false" />
    <q-table :data="data" hide-bottom>
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th
            style="font-weight: 600"
            v-for="col in props.cols"
            :key="col.name"
            :props="props"
          >
            {{ $t('InterdepartmentalCard.attachments') }}
          </q-th>
          <q-th>
            <q-btn
              v-if="canAddMoreFiles && canEdit"
              unelevated
              icon="add"
              text-color="primary"
              @click="openModal = true"
            >
              <q-tooltip :delay="500">{{
                $t('InterdepartmentalCard.addAttachment')
              }}</q-tooltip>
            </q-btn>
          </q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.value }}
          </q-td>
          <q-td auto-width>
            <q-btn
              v-if="canEdit"
              unelevated
              text-color="negative"
              icon="delete"
              @click="deleteDoc(props)"
            >
              <q-tooltip :delay="500">{{
                $t('InterdepartmentalCard.deleteAttachment')
              }}</q-tooltip>
            </q-btn>
            <q-btn
              unelevated
              text-color="primary"
              icon="arrow_downward"
              @click="downloadDocumentAttachment(props.row.fileName)"
              :loading="downloadLoading"
            >
              <q-tooltip :delay="500">{{
                $t('InterdepartmentalCard.downloadAttachment')
              }}</q-tooltip>
            </q-btn>
          </q-td>
        </q-tr>
      </template>
    </q-table>
    <q-dialog class="full-width" v-model="openModal">
      <q-card class="full-width">
        <q-card-section>
          <div class="text-h6">{{ $t('InterdepartmentalCard.addFile') }}</div>
        </q-card-section>
        <q-card-section>
          <q-file
            ref="qFile"
            filled
            v-model="attachFile"
            label="Загрузить файл"
            :accept="extensions"
          />
        </q-card-section>
        <q-card-actions align="right">
          <q-btn
            color="primary"
            @click="updateDocumentAttachment"
            :loading="attachmentLoading"
            label="Загрузить"
          />
          <q-btn
            color="white"
            text-color="primary"
            outline
            @click="
              openModal = false;
              attachFile = null;
            "
            label="Отменить"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-dialog class="full-width" v-model="deleteConfim">
      <q-card class="no-shadow full-width">
        <q-card-section>
          <div class="text-h6">
            {{ $t('InterdepartmentalCard.confirmationMessage') }}
          </div>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            @click="deleteDocumentAttachment(fileName)"
            color="primary"
            label="Удалить"
          />

          <q-btn
            color="white"
            text-color="primary"
            outline
            @click="deleteConfim = false"
            label="Отменить"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { AttachmentApi } from '@openapi/registry-service';
import { saveFileViaLink } from '@utils/files';
import { updateAttachment } from '@services/registry-service';
import { notifyError, notifySuccess } from '@utils/notify';

@Component({})
export default class AttachmentEditor extends Vue {
  @Prop() attachments: any;
  @Prop() schema: string;
  @Prop() id: string;
  @Prop({ default: '*' }) extensions: string;
  @Prop({ default: true }) multiple: boolean;
  @Prop({ default: true }) canEdit: boolean;

  openModal = false;
  data: any = [];
  attachFile: any = null;
  attachmentLoading = false;
  deleteConfim = false;
  fileName = '';
  service: AttachmentApi = new AttachmentApi();
  downloadLoading = false;

  $refs!: {
    qFile: any;
    export: any;
  };

  changeObject(attachments: any): void {
    this.data = attachments.map(
      (item: any) =>
        (item = {
          fileName: item.fileName,
        })
    );
  }

  created() {
    if (this.attachments) {
      this.changeObject(this.attachments);
    }
  }

  deleteDoc(props: any): void {
    this.deleteConfim = true;
    this.fileName = props.row.fileName;
  }

  async getAttachments() {
    const attachments = await this.service.getAllFileInfo(this.schema, this.id);
    this.changeObject(attachments.data);
    this.$emit('setAttachments', this.data, this.id);
  }

  get attachFileName() {
    return this.$refs.qFile.selectedString;
  }

  get canAddMoreFiles() {
    return this.multiple || this.attachments.length < 1;
  }

  async updateDocumentAttachment() {
    try {
      const file = new File([this.attachFile], this.attachFileName);
      this.attachmentLoading = true;
      await updateAttachment(this.schema, this.id, undefined, [file]);
      notifySuccess('Файл успешно загружен');
      this.getAttachments();
    } catch (e) {
      notifyError(e.message.toString());
    } finally {
      this.attachmentLoading = false;
      this.openModal = false;
      this.attachFile = null;
    }
  }

  async deleteDocumentAttachment(name: string) {
    try {
      this.attachmentLoading = true;
      await this.service.deleteDocumentFile(this.schema, this.id, name);
      notifySuccess('Файл успешно удален');
      this.getAttachments();
    } catch (e) {
      notifyError(e.message.toString());
    } finally {
      this.deleteConfim = false;
      this.attachmentLoading = false;
    }
  }

  async downloadDocumentAttachment(fileName: string) {
    try {
      this.downloadLoading = true;
      const file = await this.service.getDocumentFile(
        this.schema,
        this.id,
        fileName
      );
      const blob = new Blob([file.data as Blob]);
      saveFileViaLink({
        anchor: this.$refs.export,
        blob,
        fileName,
      });
    } catch (e) {
      notifyError(e.message.toString());
    } finally {
      this.downloadLoading = false;
    }
  }
}
</script>

<style scoped></style>