<i18n>
{
  "en": {
    "statements": {
      "CorrectionDialogSingle": {
        "title": "Changing the check result",
        "description": "Justification for changing the proof test value must be provided",
        "save": "Save",
        "upload": "Upload",
        "comment": "Сomment (not necessary)",
        "requiredField": "Required file or comment",
        "buttonTitle": "Provide",
        "manualWithCommentTitle": "Comment on the test result"
      }
    }
  },
  "ru": {
    "statements": {
      "CorrectionDialogSingle": {
        "title": "Изменение результата проверки",
        "description": "Необходимо предоставить обоснование изменения значения контрольной проверки",
        "save": "Сохранить",
        "upload": "Загрузить",
        "comment": "Комментарий (необязательно)",
        "requiredField": "Обязательно файл или комментарий (более 5 символов)",
        "buttonTitle": "Предоставить",
        "manualWithCommentTitle": "Комментарий к результату проверки"
      }
    }
  }
}
</i18n>

<template>
  <div>
    <q-dialog v-model="dialog" :persistent="loading" @hide="clearModel">
      <q-card class="full-width no-shadow" style="max-width: 800px">
        <q-form @submit="handler()">
          <q-card-section>
            <div class="text-h6">
              {{ (correction && correction.withComment) ? 
                $t('statements.CorrectionDialogSingle.manualWithCommentTitle') :
                $t('statements.CorrectionDialogSingle.title') }}
            </div>
            <q-banner rounded class="q-mt-md grey-banner q-py-xs">
              <div class="text-grey-9">
                {{ $t('statements.CorrectionDialogSingle.description') }}
              </div>
            </q-banner>
          </q-card-section>
          <q-card-section>
            <div v-if="correction" 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="icons[correction.status].name"
                    :color="icons[correction.status].color"
                    size="md"
                  />
                </div>
              </div>
              <q-file
                v-model="correction.files"
                :accept="accept"
                :label="$t('statements.CorrectionDialogSingle.upload')"
                multiple
                :rules="fileRules"
                clearable
                counter
                filled
              >
                <template #prepend>
                  <q-icon name="attach_file" />
                </template>
              </q-file>
              <q-input
                v-model="correction.comment"
                :label="$t('statements.CorrectionDialogSingle.comment')"
                filled
                type="textarea"
                :rules="[validCorrectionComment]"
              />
            </div>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn
              type="submit"
              :loading="loading"
              :label="$t('statements.CorrectionDialogSingle.save')"
              :disable="disableCorrection"
              unelevated
              color="primary"
            >
              <template #loading>
                <q-spinner-gears />
              </template>
            </q-btn>
          </q-card-actions>
        </q-form>
        <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 getUUID from 'uuid-by-string';
import { validCorrectionComment } from '@utils/field-validation/comments';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import get from 'lodash/get';
import { notifyError, notifySuccess } from '@utils/notify';

const CORRECTION = 'correction';
const CORRECTION_WITH_COMMENT = 'correctionWithComment';
const ADD_MANUAL_VERIFICATIONS_WITH_COMMENT = 'addManualVerificationsWithComment';

export default {
  name: 'CorrectionDialogSingle',
  props: ['common', 'model', 'user-task'],
  data() {
    return {
      accept: '.pdf, .doc, .docx, .xls, .xlsx, .txt, image/*',
      loading: false,
      dialog: false,
      correction: null,
      icons: {
        ok: {
          value: true,
          color: 'positive',
          name: 'check_circle_outline',
          // tooltip: 'Ответ получен'
        },
        error: {
          value: false,
          color: 'negative',
          name: 'remove_circle_outline',
          // tooltip: 'Ошибка'
        },
        pending: {
          value: null,
          color: 'warning',
          name: 'update',
          // tooltip: 'Ожидание ответа'
        },
      },
    };
  },
  computed: {
    fileRules() {
      return [(val) =>
          !!val ||
          !!(this.correction?.comment?.length > 4) ||
          this.$t('statements.CorrectionDialogSingle.requiredField')
      ];
    },
    disableCorrection() {
      return !(
        (this.correction?.comment && this.correction?.comment.length > 4) ||
        this.correction?.files
      );
    },
  },
  watch: {
    'common.models.correctionDialogSingle.data': {
      handler: function (val) {
        if (val) {
          this.dialog = true;
          this.correction = val;
        }
      },
    },
  },
  methods: {
    get,
    clearModel() {
      this.$emit('commonModels', {
        correctionDialogSingle: {
          data: null,
        },
      });
    },
    handler() {
      this.$store.dispatch('commonComponents/baseChecksTable/setLoading', true);
      this.loading = true;
      const corrections = [];

      this.uploadDocuments({
        files: get(this.correction, 'files'),
        description: get(this.correction, 'comment') || null,
        code: this.correction.code,
        id: this.correction.id,
        value: this.correction.value,
      })
        .then((document) => {
          corrections.push(document);
        })
        .catch(() => {
          this.loading = false;
          this.dialog = false;
        })
        .finally(() => {
          if (!this.correction.withComment) {
            this.correctionBtn(CORRECTION, corrections);
          } else {
            if (this.correction.status !== 'pending') {
              this.correctionBtn(CORRECTION_WITH_COMMENT, corrections);
            } else {
              this.addManualVerificationsWithComment(
                ADD_MANUAL_VERIFICATIONS_WITH_COMMENT, corrections
              );
            }
          }
          this.loading = false;
          this.dialog = false;
        });
    },
    uploadDocuments(data) {
      return new Promise((resolve, reject) => {
        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({
                value: get(data, 'value'),
                id: get(data, 'id'),
                code: get(data, 'code'),
                comment: get(opts, 'description'), // Дублирование для БП
                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);
            });
        };

        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 {
          const returnObject = {
            value: get(data, 'value'),
            id: get(data, 'id'),
            code: get(data, 'code'),
            comment: get(opts, 'description') || null, // Дублирование для БП
            document: null,
          };

          if ((get(opts, 'description') || '').trim()) {
            returnObject.document = {
              comment: get(opts, 'description'),
              schema: 'AttachedDocuments',
              type: {
                code: 'criterRedefining',
                name: 'Изменение критерия',
              },
            };
          }
          resolve(returnObject);
        }
        this.$emit('commonModels', {
          correctionDialogSingle: {
            data: null,
          },
        });
      });
    },
    validCorrectionComment,
    addManualVerificationsWithComment(buttonId, corrections) {
      this.$store.dispatch('commonComponents/baseChecksTable/setPassedChecks', true);
      this.$store.dispatch('commonComponents/baseChecksTable/setLoading', true);
      this.$emit('commonModels', {
        index: {
          submit: {
            buttonId,
            force: true,
            data: {
              manualVerifications: 
                this.correction.prepareData(this.correction.results),
              ...(corrections && { corrections })
            },
          },
        },
      });
      this.correction.updateButtons();
      localStorage.removeItem(this.model.id);
    },
    correctionBtn(buttonId, corrections) {
      this.$emit('commonModels', {
        index: {
          submit: {
            buttonId,
            force: true,
            data: {
              corrections,
            },
          },
        },
      });
    },
  },
};
</script>
