<i18n>
{
  "en": {
    "statements": {
      "PreRejectDialog": {
        "changingCheckResults": "Changing check results",
        "toMakeADecisionToRefuseToProvideAService": "To make a decision to refuse to provide a service, it is necessary to provide justification for changes in the values of control checks.",
        "comment": "Сomment",
        "upload": "Upload",
        "documentsUploadedSuccessfully": "Documents uploaded successfully",
        "errorLoadingDocuments": "Error loading documents",
        "requiredField": "Be sure to file or comment (more than 5 characters)"
      }
    }
  },
  "ru": {
    "statements": {
      "PreRejectDialog": {
        "changingCheckResults": "Изменение результатов проверок",
        "toMakeADecisionToRefuseToProvideAService": "Для принятия решения об отказе в предоставлении услуги необходимо представить обоснования изменений значений контрольных проверок.",
        "comment": "Комментарий",
        "upload": "Загрузить",
        "documentsUploadedSuccessfully": "Документы успешно загружены",
        "errorLoadingDocuments": "Ошибка при загрузке документов",
        "requiredField": "Обязательно файл или комментарий (более 5 симв.)"
      }
    }
  }
}
</i18n>

<template>
  <div>
    <q-btn
      class="q-ml-sm"
      outline
      :disable="disableAllButtons || get(buttonSettings, 'props.disable')"
      :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-form ref="correctionsForm" @submit="handler()">
          <q-card-section class="text-h6">
            {{ $t('statements.PreRejectDialog.changingCheckResults') }}
          </q-card-section>
          <q-card-section class="text-h6">
            <q-banner rounded class="q-mt-md grey-banner q-py-xs">
              <div class="text-grey-9">
                {{
                  $t(
                    'statements.PreRejectDialog.toMakeADecisionToRefuseToProvideAService'
                  )
                }}
              </div>
            </q-banner>
          </q-card-section>
          <q-card-section>
            <div v-for="(correction, i) in corrections" :key="i">
              <div
                class="row"
                :style="`border: 1px solid #757575;${
                  i === 0 ? '' : 'border-top: 0'
                }`"
              >
                <div
                  class="col q-pa-md text-grey-7"
                  style="border-right: 1px solid #757575"
                >
                  {{ get(correction, 'name') }}
                </div>
                <div class="q-pa-md flex items-center">
                  <q-icon
                    name="check_circle_outline"
                    color="positive"
                    size="md"
                  />
                </div>
              </div>
            </div>
          </q-card-section>
          <q-card-section>
            <q-file
              v-model="files"
              :accept="accept"
              :label="$t('statements.PreRejectDialog.upload')"
              multiple
              :rules="[
                (val) =>
                  !!val ||
                  (!!comment && comment.trim().length > 5) ||
                  $t('statements.PreRejectDialog.requiredField'),
              ]"
              clearable
              counter
              filled
            >
              <template #prepend>
                <q-icon name="attach_file" />
              </template>
            </q-file>
            <q-input
              v-model="comment"
              :label="$t('statements.PreRejectDialog.comment')"
              filled
              type="textarea"
              @change="resetValidation"
            />
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              type="submit"
              :loading="loading"
              :label="$t('statements.PreRejectDialog.upload')"
              unelevated
              color="primary"
            >
              <template #loading>
                <q-spinner-gears />
              </template>
            </q-btn>
          </q-card-actions>
          <q-inner-loading :showing="loading">
            <q-spinner-gears color="primary" size="50px" />
          </q-inner-loading>
        </q-form>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import get from 'lodash/get';
import isArray from 'lodash/isArray';
import { notifyError, notifySuccess } from '@utils/notify';

export default {
  props: [
    'common',
    'model',
    'disable-all-buttons',
    'user-task',
    'button-settings',
  ],
  data() {
    return {
      button: {
        props: {
          color: 'red',
          label: 'Отказать',
          loading: false,
        },
        id: '',
      },
      comment: '',
      files: null,
      accept: '.pdf, .doc, .docx, .xls, .xlsx, .txt, image/*',
      loading: false,
      value: false,
    };
  },
  computed: {
    corrections() {
      const groupsVerifications = get(this.model, 'decisionData.groups') || [];
      const corrections = [];

      if (!isArray(groupsVerifications)) {
        return corrections;
      }

      groupsVerifications.forEach((groupItem) => {
        const verifications = get(groupItem, 'verifications');

        if (!isArray(verifications)) {
          return null;
        }
        verifications.forEach((verificationItem) => {
          corrections.push({
            name: get(verificationItem, 'name'),
          });
        });
      });

      return corrections;
    },
  },
  methods: {
    get,
    resetValidation() {
      this.$refs.correctionsForm.resetValidation();
    },
    doAction() {
      this.value = true;
    },
    handler() {
      this.loading = true;
      const corrections = [];

      this.uploadDocuments({
        files: this.files,
        description: this.comment,
      })
        .then((document) => {
          corrections.push(document);

          this.$emit('submit', {
            data: {
              corrections,
            },
            buttonId: 'preReject',
          });
          this.value = false;
          this.loading = false;
        })
        .catch(() => {
          this.value = false;
          this.loading = false;
        });
    },
    uploadDocuments(data) {
      return new Promise((resolve, reject) => {
        const resolveObject = {
          comment: this.comment, // Дублирование для БП
          document: {
            comment: this.comment,
            schema: 'AttachedDocuments',
            type: {
              code: 'criterRedefining',
              name: 'Изменение критерия',
            },
          },
        };

        const uploadFile = ({ opts }) => {
          const file = get(opts, 'files[0]');
          const fileName = get(file, 'name');

          return S3UrlSignerFilesService.uploadFileToS3ByPath({
            file,
            path: `Applications/${get(this.common, 'id')}/file/${fileName}`,
          })
            .then((s3Url) => {
              notifySuccess(
                this.$t(
                  'statements.PreRejectDialog.documentsUploadedSuccessfully'
                )
              );

              resolve({
                ...resolveObject,
                document: {
                  comment: this.comment,
                  file: {
                    name: fileName,
                    url: s3Url,
                  },
                  schema: 'AttachedDocuments',
                  type: {
                    code: 'criterRedefining',
                    name: 'Изменение критерия',
                  },
                },
                fileName,
              });
            })
            .catch((e) => {
              notifyError(
                this.$t('statements.PreRejectDialog.errorLoadingDocuments')
              );
              reject(e);
            })
            .finally(() => {
              this.button.props.loading = false;
            });
        };

        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,
          });
        } else {
          resolve(resolveObject);
        }
      });
    },
    submit({ buttonId, data }) {
      this.$emit('submit', {
        buttonId,
        data,
        force: true,
      });
    },
  },
};
</script>
