<i18n>
{
  "en": {
    "statements": {
      "CommentDialog": {
        "dialogTitle": "Adding a comment to the status",
        "commentLabel": "Add comment",
        "docLabel":  "Add document",
        "addComment": "Add",
        "cancelComment": "Cancel",
        "resultType": "Document sent to the applicant"
      }
    }
  },
  "ru": {
    "statements": {
      "CommentDialog": {
        "dialogTitle": "Отправить документ и комментарий на ЕПГУ",
        "commentLabel": "Добавить комментарий",
        "docLabel":  "Добавить документ",
        "addComment": "Отправить на портал",
        "cancelComment": "Отменить",
        "resultType": "Документ, отправляемый заявителю"
      }
    }
  }
}
</i18n>

<template>
  <div>
    <q-btn
      class="q-ml-sm"
      padding="6px"
      flat
      :icon="get(buttonSettings, 'props.icon')"
      :label="get(buttonSettings, 'props.label')"
      :color="get(buttonSettings, 'props.color')"
      :disable="disableAllButtons"
      @click="doAction"
    >
      <slot />
    </q-btn>
    <!-- TODO: Доделать дефолтную кнопку с настраеваемым id(props) и label'ом  -->
    <q-dialog v-model="value">
      <q-card class="no-shadow" style="max-width: 80vw; width: 700px">
        <q-card-section class="text-h6">{{
          $t('statements.CommentDialog.dialogTitle')
        }}</q-card-section>
        <q-card-section class="q-gutter-y-md">
          <q-select
            v-model="resultType"
            filled
            :options="documentTypeList"
            :label="$t('statements.CommentDialog.resultType')"
          />
          <q-input
            :label="$t('statements.CommentDialog.commentLabel')"
            v-model="comment"
            filled
            type="textarea"
          />
          <q-file
            :label="$t('statements.CommentDialog.docLabel')"
            @input="s3upload"
            filled
            v-model="document"
          />
        </q-card-section>
        <q-card-section class="full-width flex justify-end">
          <q-btn
            v-for="button in buttons"
            :key="button.id"
            class="q-ml-sm"
            :disable="isAddDisabled && button.id === 'add'"
            :label="button.props.label"
            :color="button.props.color"
            :outline="button.props.outlined"
            :loading="button.props.loading || loading"
            @click="button.handler"
          />
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { Component, Prop, Vue } from 'vue-property-decorator';
import { BaseCardCommon } from '@/interfaces';
import { Model } from '@devsun/eva-models';
import { QSelectOption } from '@models/models-ui';
import get from 'lodash/get';
import { notifyError, notifySuccess } from '@utils/notify';

const SPECIALIST = 'specialist';

@Component({
  methods: {
    get,
  },
})
export default class UserDocsCommentDialog extends Vue {
  @Prop() common: BaseCardCommon;
  @Prop() model: Model.Base;
  @Prop() disableAllButtons: boolean;
  @Prop() userTask: any;
  @Prop() buttonSettings: any;

  buttons = [
    {
      id: 'add',
      props: {
        color: 'primary',
        label: this.$t('statements.CommentDialog.addComment'),
        loading: false,
        outlined: false,
      },
      handler: async (): Promise<void> => {
        this.saveUserComment();
        this.value = false;
      },
    },
  ];

  comment = '';
  document = null;
  resultType: QSelectOption | null = null;

  docUpload = {
    name: '',
    url: '',
  };

  value = false;
  loading = false;

  get serviceCard() {
    return this.$store.getters['registryService/services/servicesCard'];
  }

  get isAddDisabled(): boolean {
    return (
      !this.resultType?.value ||
      !this.resultType?.label ||
      (!this.comment && !(this.docUpload.name && this.docUpload.url))
    );
  }

  get documentTypeList() {
    return (
      this.serviceCard?.documents
        ?.filter(
          (document: any) => document.source.toLowerCase() === SPECIALIST
        )
        .map((document: { name?: string; code?: string }) => {
          return {
            label: document?.name,
            value: document?.code,
          };
        }) || []
    );
  }

  created(): void {
    this.checkUserComments(this.userTask);
  }

  doAction(): void {
    this.value = true;
  }

  async s3upload(inputDoc: File): Promise<void> {
    this.loading = true;
    try {
      this.docUpload.url =
        (await S3UrlSignerFilesService.uploadFileToS3ByPath({
          file: inputDoc,
          path: `Applications/${get(this.common, 'id')}/file/${get(
            inputDoc,
            'name'
          )}`,
        })) || '';
      this.docUpload.name = inputDoc.name;

      notifySuccess(
        this.$t('registries.documentsUploadedSuccessfully') as string
      );
    } catch (e) {
      this.document = null;
      notifyError(this.$t('registries.errorLoadingDocuments') as string);
    } finally {
      this.loading = false;
    }
  }

  saveUserComment(): void {
    this.loading = true;
    try {
      const type = {
        code: this.resultType?.value,
        name: this.resultType?.label,
      };
      const comment = this.comment;
      this.$emit('update', {
        comment,
      });
      this.$emit('submit', {
        buttonId: 'userCommentDoc',
        data: {
          id: '',
          dateRegistered: '',
          type,
          comment,
          file: this.docUpload,
        },
        force: true,
      });
      this.comment = '';
      this.docUpload = { name: '', url: '' };
      this.resultType = null;
      this.document = null;
    } catch (e) {
      console.error(e);
    } finally {
      this.loading = false;
    }
  }

  checkUserComments(userTask: any): void {
    this.comment = get(userTask, 'userTask.outData.comment', '');
    this.$emit('update', {
      comment: this.comment,
    });
  }
}
</script>
