<i18n>
{
    "en": {
        "statements": {
            "UploaderDialog": {
                "addingDocument": "Adding a document",
                "attach": "Attach",
                "documentsUploadedSuccessfully": "Documents uploaded successfully",
                "invalidResultFile": "Invalid file format. The resulting document must be in HTML, PDF, DOCX format",
                "invalidFile": "Invalid file format"
            }
        }
    },
    "ru": {
        "statements": {
            "UploaderDialog": {
                "addingDocument": "Добавление документа",
                "attach": "Прикрепить",
                "documentsUploadedSuccessfully": "Документы успешно загружены",
                "invalidResultFile": "Недопустимый формат файла. Результирующий документ должен быть в формате HTML, PDF, DOCX",
                "invalidFile": "Недопустимый формат файла"
            }
        }
    }
}
</i18n>

<template>
  <div>
    <div
      v-if="$slots.button"
      class="cursor-pointer"
      v-bind="button.props"
      @click="doAction"
    >
      <slot name="button"> </slot>
    </div>

    <q-btn
      v-else
      :disable="disableAllButtons"
      class="q-ml-sm"
      outline
      :label="get(buttonSettings, 'props.label')"
      :color="get(buttonSettings, 'props.color')"
      v-bind="button.props"
      @click="doAction"
    />
    <q-dialog v-model="value" :persistent="loading">
      <q-card class="no-shadow" style="max-width: 80vw; width: 700px">
        <q-card-section class="text-h6">
          {{ $t('statements.UploaderDialog.addingDocument') }}
        </q-card-section>
        <q-card-section>
          <base-uploader
            :description="comment"
            :need-file="false"
            :accept="accept"
            :rules="[
              noEmptyValueWithCustomMessageRule(String(validationMessage)),
            ]"
            @input="(inputFiles) => (files = inputFiles)"
            @upload="uploadDocuments"
          />
        </q-card-section>
        <q-inner-loading :showing="loading">
          <q-spinner-gears color="primary" size="50px" />
        </q-inner-loading>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import { noEmptyValueWithCustomMessageRule } from '@utils/field-validation/basic';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { CardNeedToUpdateType } from '@constants/models/Card';
import get from 'lodash/get';
import { WorkflowServiceApi } from '@openapi/wf';
import { DocumentApi } from '@openapi/document-registry';
import { notifyError, notifySuccess } from '@utils/notify';
import { extractFileName } from '@/utils/files';

const wfApi = new WorkflowServiceApi();
const documentApi = new DocumentApi();

export default {
  props: [
    'row',
    'common',
    'model',
    'disable-all-buttons',
    'user-task',
    'button-settings',
  ],
  data() {
    return {
      loading: false,
      button: {
        props: {
          color: 'primary',
          label: this.$t('statements.UploaderDialog.attach'),
          loading: false,
        },
      },
      documentId: '',
      files: [],
      documentTypeObject: null,
      comment: '',
      value: false,
    };
  },
  computed: {
    accept() {
      if (get(this, 'row.source', '').toLowerCase() === 'result') {
        return '.pdf, .docx, .html';
      }
      return '.ppt, .odt, .pdf, .doc, .docx, .xls, .xlsx, .txt, image/*';
    },
    validationMessage() {
      if (get(this, 'row.source', '').toLowerCase() === 'result') {
        return this.$t('statements.UploaderDialog.invalidResultFile');
      }
      return this.$t('statements.UploaderDialog.invalidFile');
    },
  },
  methods: {
    get,
    doAction() {
      this.value = true;
    },
    checkDocumentSource(document, source) {
      return String(get(document, 'source')).toLowerCase() === source;
    },
    saveDocument(opts, s3Url = undefined) {
      const file = get(opts, 'files[0]');
      const comment = get(opts, 'description');

      const documentObject = Object.assign(
        {},
        {
          id: get(this.row, 'id'),
          modified: get(this.row, 'modified'),
          source: get(this.row, 'source'),
          schema: get(this.row, 'schema'),
          type: {
            code: get(this.row, 'type.code'),
            name: get(this.row, 'type.name'),
          },
          comment,
        }
      );

      if (file) {
        documentObject.file = {
          name: extractFileName(file),
          url: s3Url,
        };
      }
      documentApi
        .updateDocument(documentObject.schema, [documentObject])
        .then(() => {
          if (this.checkDocumentSource(documentObject, 'result')) {
            wfApi.submitForm(get(this.userTask, 'userTask.taskId'), {
              id: 'uploadDocument',
              data: {
                docIds: [documentObject.id],
              },
            });
          }
          this.$store.commit(
            `utils/cards/needToUpdate`,
            CardNeedToUpdateType.MODEL
          );
        });
    },
    uploadDocuments(data, done) {
      this.loading = true;
      const uploadFile = ({ opts }) => {
        const file = get(opts, 'files[0]');
        return S3UrlSignerFilesService.uploadFileToS3ByPath({
          file,
          path: `Applications/${get(this.common, 'id')}/file/${extractFileName(file)}`,
        })
          .then((s3Url) => {
            notifySuccess(
              this.$t('statements.DocumentsCard.documentsUploadedSuccessfully')
            );

            this.saveDocument(opts, s3Url);
          })
          .catch(() => {
            notifyError(
              this.$t('statements.DocumentsCard.errorLoadingDocuments')
            );
            this.loading = false;
          })
          .finally(() => {
            this.button.props.loading = false;
            this.loading = false;
            this.value = false;
            this.files = [];
          });
      };

      const opts = {};
      const files = get(data, 'files');
      const description = (get(data, 'description') || '').trim();

      if (files) {
        opts.files = files;
      }

      if (description) {
        opts.description = description;
      }

      if (Array.isArray(opts.files) && opts.files.length) {
        uploadFile({
          opts,
        }).finally(() => {
          done();
        });
      } else {
        this.saveDocument(opts);
      }
    },
    noEmptyValueWithCustomMessageRule,
  },
};
</script>
