<i18n>
{
  "en": {
    "statements": {
      "CorrectionDialog": {
        "title": "Changing the checks results",
        "description": "To make a decision to provide a service, it is necessary to provide justifications for changes in the values of control checks",
        "upload": "Upload",
        "comment": "Сomment (not necessary)",
        "requiredField": "Required file or comment",
        "buttonTitle": "Provide"
      }
    }
  },
  "ru": {
    "statements": {
      "CorrectionDialog": {
        "title": "Изменение результатов проверок",
        "description": "Для принятия решения о предоставлении услуги необходимо представить обоснования изменений значений контрольных проверок.",
        "upload": "Загрузить",
        "comment": "Комментарий (необязательно)",
        "requiredField": "Обязательно файл или комментарий (более 5 симв.)",
        "buttonTitle": "Предоставить"
      }
    }
  }
}
</i18n>

<template>
  <div>
    <div
      v-if="$slots.button"
      v-bind="button.props"
      class="cursor-pointer"
      @click="doAction"
    >
      <slot name="button" />
    </div>
    <q-btn
      v-else
      class="q-ml-sm"
      v-bind="button.props"
      :disable="disableAllButtons || buttonDisable"
      :class="{ hidden: !buttonVisible }"
      :label="buttonLabel"
      :color="buttonColor"
      outline
      @click="doAction"
    />
    <q-dialog v-model="value" :persistent="loading">
      <q-card class="full-width no-shadow" style="max-width: 800px">
        <q-form ref="correctionsForm" @submit="handler()">
          <q-card-section>
            <div class="text-h6">
              {{ $t('statements.CorrectionDialog.title') }}
            </div>
            <q-banner rounded class="q-mt-md grey-banner q-py-xs">
              <div class="text-grey-9">
                {{ $t('statements.CorrectionDialog.description') }}
              </div>
            </q-banner>
          </q-card-section>
          <q-card-section>
            <div
              v-for="(correction, i) in corrections"
              :key="i"
              class="q-pb-md"
            >
              <div class="row q-mb-md" style="border: 1px solid #757575">
                <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="remove_circle_outline" color="red" size="md" />
                </div>
              </div>
              <q-file
                v-model="correction.files"
                :accept="accept"
                :label="$t('statements.CorrectionDialog.upload')"
                multiple
                :rules="[
                  (val) =>
                    get(correction, 'type') === 'manual' ||
                    !!val ||
                    (!!correction.comment &&
                      correction.comment.trim().length > 5) ||
                    $t('statements.CorrectionDialog.requiredField'),
                ]"
                clearable
                counter
                filled
              >
                <template #prepend>
                  <q-icon name="attach_file" />
                </template>
              </q-file>
              <q-input
                v-model="correction.comment"
                :label="$t('statements.CorrectionDialog.comment')"
                filled
                type="textarea"
                @change="resetValidation"
              />
            </div>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              type="submit"
              :loading="loading"
              :label="$t('statements.CorrectionDialog.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 getUUID from 'uuid-by-string';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import get from 'lodash/get';
import cloneDeep from 'lodash/cloneDeep';
import { notifyError, notifySuccess } from '@utils/notify';

export default {
  props: [
    'common',
    'button-settings',
    'disable-all-buttons',
    'model',
    'user-task',
  ],
  data() {
    return {
      button: {
        props: {
          color: 'red',
          label: this.$t('statements.CorrectionDialog.buttonTitle'),
          loading: false,
        },
      },
      accept: '.pdf, .doc, .docx, .xls, .xlsx, .txt, image/*',
      loading: false,
      value: false,
      corrections: [],
    };
  },
  computed: {
    checksValidateCondition() {
      return (
        get(this.userTask, 'userTask.outData.checkListIsMandatory') &&
        !this.$store.getters[
          'commonComponents/baseChecksTable/allChecksHaveBeenPassed'
        ] &&
        get(this.model, 'decisionData.manualVerificationExist')
      );
    },
    buttonVisible() {
      return get(
        this.buttonSettings,
        'props.visible',
        get(this.button, 'props.visible')
      );
    },
    buttonLabel() {
      return get(
        this.buttonSettings,
        'props.label',
        get(this.button, 'props.label')
      );
    },
    buttonColor() {
      return get(
        this.buttonSettings,
        'props.color',
        get(this.button, 'props.color')
      );
    },
    buttonDisable() {
      return get(
        this.buttonSettings,
        'props.disable',
        get(this.button, 'props.disable')
      );
    },
    correctionsFromUT() {
      return get(this.model, 'decisionData.failedVerifications') || [];
    },
  },
  methods: {
    get,
    doAction() {
      if (!this.checksValidateCondition) {
        this.value = true;
        this.corrections = cloneDeep(this.correctionsFromUT);
      } else {
        this.$emit('commonModels', {
          checks: {
            needToBeValidated: true,
          },
        });
      }
    },
    handler() {
      this.loading = true;
      let countDocuments = 0;
      const corrections = [];

      for (const [key, correction] of Object.entries(this.corrections)) {
        this.uploadDocuments({
          files: get(correction, 'files'),
          description: get(correction, 'comment') || null,
          key,
          correction,
        })
          .then((document) => {
            corrections.push(document);
            // eslint-disable-next-line no-loop-func
          })
          .finally(() => {
            countDocuments++;

            if (countDocuments === Object.keys(this.corrections).length) {
              this.$emit('submit', {
                data: {
                  corrections,
                },
                buttonId: 'correction',
              });
              this.loading = false;
              this.value = false;
            }
          });
      }
    },
    resetValidation() {
      this.$refs.correctionsForm.resetValidation();
    },
    uploadDocuments(data) {
      return new Promise((resolve, reject) => {
        const opts = {};
        const files = get(data, 'files');
        const description = (get(data, 'description') || '').trim();

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

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

        const returnObject = {
          id: get(data, 'correction.id'),
          code: get(data, 'correction.code'),
          comment: get(opts, 'description'), // Дублирование для БП
          value: true,
        };
        const uploadFile = ({ opts }) => {
          const file = get(opts, 'files[0]');
          const fileName = get(file, 'name');
          const ext = fileName.split('.').pop();
          const UUIDFromFileName = `${getUUID(fileName)}.${ext}`;

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

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

        if (Array.isArray(opts.files) && opts.files.length) {
          uploadFile({
            opts,
          });
        } else {
          if ((get(opts, 'description') || '').trim()) {
            returnObject.document = {
              comment: get(opts, 'description'),
              schema: 'AttachedDocuments',
              type: {
                code: 'criterRedefining',
                name: 'Изменение критерия',
              },
            };
          }

          resolve(returnObject);
        }
      });
    },
  },
};
</script>
