<i18n>
{
  "en": {
    "statements": {
      "DocumentsCard": {
        "preview": "Preview",
        "dateOfChange": "Date of change",
        "documentType": "Type",
        "description": "Description"
      },
      "DocumentDialog": {
        "addingDocument": "Adding a document",
        "documentTypeLabel": "Document type"
      }
    }
  },
  "ru": {
    "statements": {
      "DocumentsCard": {
        "preview": "Предпросмотр",
        "dateOfChange": "Дата изменения",
        "documentType": "Тип",
        "description": "Описание"
      },
      "DocumentDialog": {
        "addingDocument": "Добавление документа",
        "documentTypeLabel": "Тип документа"
      }
    }
  }
}
</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"
    />
    <!-- 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.DocumentsCard.preview') }}
        </q-card-section>
        <q-card-section class="q-gutter-y-md">
          <table class="text-primary">
            <tr>
              <td>
                <q-item>
                  <q-item-section>
                    <q-item-label class="text-grey-9">
                      {{ $t('statements.DocumentsCard.documentType') }}
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </td>
              <td>
                <q-item>
                  <q-item-section>
                    <q-item-label>
                      {{ get(preview, 'data.typeName') }}
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </td>
            </tr>
            <tr>
              <td>
                <q-item>
                  <q-item-section>
                    <q-item-label class="text-grey-9">
                      {{ $t('statements.DocumentsCard.dateOfChange') }}
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </td>
              <td>
                <q-item>
                  <q-item-section>
                    <q-item-label>
                      {{ get(preview, 'data.modifiedDate') }}
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </td>
            </tr>
            <tr v-show="get(preview, 'data.description')">
              <td>
                <q-item>
                  <q-item-section>
                    <q-item-label class="text-grey-9">
                      {{ $t('statements.DocumentsCard.description') }}
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </td>
              <td>
                <q-item>
                  <q-item-section>
                    <q-item-label>
                      {{ get(preview, 'data.description') }}
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </td>
            </tr>
          </table>
        </q-card-section>
        <q-card-section class="full-width q-gutter-y-md">
          <component
            :is="uploadFormComponent"
            v-if="uploadFormComponent"
            :type-object="preview.documentTypeObject"
            :form="preview.form"
            :hide-nulls="true"
            :sub="sub"
            mode="preview"
          />
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import { convertDateFromTimestamp } from '@utils/format-date';
import { DateFormat } from '@constants/utils/format-date';
import get from 'lodash/get';

export default {
  props: [
    'row',
    'common',
    'model',
    'disable-all-buttons',
    'user-task',
    'button-settings',
  ],
  data() {
    return {
      button: {
        props: {
          color: 'primary',
          label: 'Просмотр',
          loading: false,
        },
      },
      documentTypeOptions: [],
      uploadFormComponent: undefined,
      preview: {
        documentTypeObject: null,
        form: {},
        data: {
          typeName: '',
          source: '',
          modifiedDate: '',
          description: '',
        },
      },
      sub: [],
      value: false,
    };
  },
  computed: {
    serviceMeta() {
      return this.$store.getters['registryService/services/servicesCard'];
    },
  },
  methods: {
    get,
    doAction() {
      this.initDocumentType().then(() => {
        this.fetchForm('ReviewDocumentsHiddenForm');
        const row = this.row || {};

        this.preview.data.typeName = get(row, 'type.name', '');
        this.preview.data.source = get(row, 'source', '');
        this.preview.data.description = get(row, 'comment', '');
        this.preview.data.modifiedDate = '';
        const modifiedTimestamp = row.modified;

        if (modifiedTimestamp) {
          this.preview.data.modifiedDate = convertDateFromTimestamp(
            modifiedTimestamp,
            DateFormat.date
          );
        }

        const doc = this.model.documents.find((el) => {
          return el.id === row.id;
        });

        const sub = [];
        if (doc) {
          if (doc.source === 'Result')
            sub.push(get(this.model, 'statement.goal'));
          this.preview.documentTypeObject =
            this.documentTypeOptions.find(
              (document) => document.type === doc.type.code
            ) || null;
          const form = this.getDocumentUploadFormFields(doc);
          this.updateUploadFormModel(form, 'preview');
        }
        this.sub = sub;
      });

      this.value = true;
    },
    getDocumentUploadFormFields(doc) {
      const cleanDoc = ({
        type,
        hidden,
        id,
        modified,
        schema,
        source,
        ...rest
      }) => {
        return rest;
      };

      return cleanDoc(doc);
    },
    updateUploadFormModel(model, formKey) {
      Object.keys(model).forEach((key) => {
        this[formKey].form[key] = model[key];
      });
    },
    initDocumentType() {
      return new Promise((resolve, reject) => {
        const comparator = this.$store.getters['i18N/localeComparator'];
        const docs = this.serviceMeta?.documents;
        if (docs) {
          this.documentTypeOptions = docs
            .map((document) => ({
              label: document.name,
              type: document.code,
              data: document,
            }))
            .sort((a, b) => comparator(a.label, b.label));

          resolve(this.documentTypeOptions);
        } else {
          reject();
        }
      });
    },
    fetchForm(previewDocumentsFormKey) {
      if (this.uploadFormComponent) {
        return;
      }

      this.uploadFormComponent = this.$GlobalComponentImporter.registerComponent(
        previewDocumentsFormKey,
        'forms/'
      );
    },
  },
};
</script>
