<template>
  <div class="full-width">
    <q-card>
      <q-table
        v-if="rows"
        :title="title"
        :columns="columns"
        :data="rows"
        row-key="name"
        hide-bottom
      >
        <template #body="props">
          <q-tr :props="props">
            <q-td :key="props.cols[0].name" :props="props">
              {{ props.cols[0].value }}
            </q-td>

            <q-td :key="props.cols[1].name" :props="props">
              <add-file-button
                :title="$t('services.emulation.upload')"
                :disable="disable"
                @added="file => onAdded(file, props.rowIndex)"
                @removed="$emit('removed', props.row.code)"
              />
              <q-inner-loading :showing="loading" />
            </q-td>
          </q-tr>
        </template>
      </q-table>
    </q-card>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import { Row } from "../types";
import { consoleNotifyError, requestNotifyError } from "../utils";
import S3UrlSignerFilesService from "@services/s3urlsigner/files";
import AddFileButton from '../components/add-file-button.vue';
import { notifySuccess } from "@/utils/notify";
import cloneDeep from 'lodash/cloneDeep'

export default Vue.extend({
  components: {
    AddFileButton
  },
  props: {
    documents: Array as () => any[],
    title: String,
    disable: Boolean
  },
  data() {
    return {
      rows: [] as Row[],
      columns: [
        {
          name: 'name',
          label: 'Наименование',
          field: 'name',
          align: 'left',
        },
        {
          name: 'file',
          label: 'Файл',
          field: 'file',
          align: 'center',
        }
      ],
      loading: false
    };
  },
  watch: {
    documents() {
      this.setRows();
    },
  },
  mounted() {
    this.setRows();
  },
  methods: {
    setRows() {
      if (this.documents.length) {
        this.rows = cloneDeep(this.documents);
      } else {
        this.rows = [];
      }
    },
    async onAdded(file: File, index: number) {
      this.loading = true;
      const fileUrlObj = await this.uploadFileToS3(file)
        .catch(error => requestNotifyError(error))
        .finally(() => this.loading = false);
      if (!fileUrlObj) {
        consoleNotifyError('Не смог загрузить файл в S3');
        return;
      }
      notifySuccess('Файл успешно загружен');

      const documentObj = { ...fileUrlObj, documentCode: this.rows[index].code };
      console.log(documentObj);
      this.$emit('upload', documentObj);
    },
    onRejected(rejectedEntries: any) {
      consoleNotifyError(
        `${rejectedEntries.length} ${this.$t('services.emulation.error.filesDidNotPass')}`
      );
		},
    async uploadFileToS3(file: File): Promise<any>  {
      const fileName = file.name;
      const path = `Applications/EmulationDocuments/file/${fileName}`;
      const url = await S3UrlSignerFilesService.uploadFileToS3ByPath({
        file,
        path
      });
      if (!url) {
        return;
      }
      return {
        fileName,
        fileUrl: url
      }
    }
  }
});
</script>

