<i18n>
{
  "en": {
    "DocumentsCard": {
      "stageTitle": "Decision",
      "apply": "Positive decision",
      "reject": "Rejection",
      "type": "Type",
      "mvzDoctableTitle": "Documents added by a specialist",
      "actions": "Actions",
      "templateActions": "Actions (template)",
      "templateCode": "Template code",
      "templateName": "Template name",
      "applicantTableTitle": "applicant",
      "personal": "personal welcome",
      "ResultTableTitle": "Processes",
      "ApplicationPrintTableTitle": "Application print template",
      "name": "Name",
      "code": "code",
      "documentCreate": "New document",
      "documentChose": "Chose document",
      "registryView": "Registry view",
      "noProcessesResult": "No Processes result",
      "confirmationMessage": "Are you sure you want to delete the document?",
      "templateValidationFailed": "Invalid template. Upload aborted",
      "templateNormalizationFailed": "Template normalization error. Upload aborted",
      "goals": "Goals",
      "validationError": "Template validation error",
      "templateTesting": "Template testing",
      "DownloadTemplateTooltip": "Download template",
      "UploadTemplateTooltip": "Upload template",
      "EditTemplateTooltip": "Edit template",
      "DeleteTemplateTooltip": "Delete template",
      "TestTemplateTooltip": "Test template",
      "CreateTemplateTooltip": "Create template",
      "DocumentsSentApplicant": "Documents sent to the applicant",
      "receptionTemplate": "Face to face printable template"
    }
  },
  "ru": {
    "DocumentsCard": {
      "stageTitle": "Решение",
      "apply": "Положительное решение",
      "reject": "Отказ",
      "type": "Тип",
      "applicantTableTitle": "Входящие документы",
      "personal": "Личный прием",
      "mvzDoctableTitle": "Документы, добавляемые специалистом",
      "filename": "Имя файла",
      "actions": "Действия",
      "templateActions": "Действия (шаблон)",
      "templateCode": "Код шаблона",
      "templateName": "Наименование шаблона",
      "ResultTableTitle": "Результирующие документы",
      "ApplicationPrintTableTitle": "Шаблон печати заявления",
      "name": "Наименование документа",
      "code": "Код документа",
      "documentCreate": "Новый документ",
      "documentChose": "Выбрать документ",
      "registryView": "Схема реестра",
      "uploadAttachFile": "Загрузить файл шаблона",
      "noProcessesResult": "Документы не найдены",
      "confirmationMessage": "Удалить документ из описания услуги",
      "templateValidationFailed": "Шаблон не валиден. Загрузка приостановлена",
      "templateNormalizationFailed": "Ошибка нормализации шаблона. Загрузка приостановлена",
      "goals": "Цели",
      "validationError": "Ошибка валидации шаблона",
      "templateTesting": "Проверка шаблона",
      "DownloadTemplateTooltip": "Скачать шаблон",
      "UploadTemplateTooltip": "Загрузить шаблон",
      "EditTemplateTooltip": "Редактировать шаблон",
      "DeleteTemplateTooltip": "Удалить шаблон",
      "TestTemplateTooltip": "Тестировать шаблон",
      "CreateTemplateTooltip": "Создать шаблон",
      "DocumentsSentApplicant": "Документы, отправляемые заявителю",
      "receptionTemplate": "Шаблон печатной формы очного приёма"
    }
  }
}
</i18n>

<template>
  <div class="q-pb-md" v-if="common.active === 'documents' && !loadingCard">
    <q-card class="no-shadow q-gutter-y-md q-mx-md no-border-radius">
      <div
        class="q-gutter-y-md bg-white q-px-lg q-pb-md q-pt-sm q-mt-md rounded-borders"
      >
        <div
          class="flex justify-between q-my-md q-px-md row"
          style="width: 100%"
        >
          <div class="text-h6">Документы</div>
          <div v-if="canEdit">
            <q-btn
              color="secondary"
              icon="pgs-view"
              v-if="state === 'inProgress'"
              @click="createRegistry"
              :label="$t('DocumentsCard.registryView')"
              class="q-mr-md"
            />
            <q-btn
              color="primary"
              icon="search"
              v-if="state === 'inProgress'"
              @click="changelist"
              :label="$t('DocumentsCard.documentChose')"
              class="q-mr-md"
            />
            <q-btn
              color="primary"
              icon="add_box"
              v-if="state === 'inProgress'"
              @click="addDocument"
              :label="$t('DocumentsCard.documentCreate')"
            />
          </div>
        </div>
        <div v-if="isOneOfTheTables">
          <a ref="export" v-show="false" />
          <q-expansion-item default-opened v-if="ResultTable.length">
            <template v-slot:header>
              <q-item-section>
                <div class="text-h6">
                  {{ $t('DocumentsCard.ResultTableTitle') }}
                </div>
              </q-item-section>
            </template>

            <q-table
              :columns="columns"
              :data="ResultTable"
              :pagination.sync="pagination"
            >
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.label }}
                  </q-th>
                  <q-th
                    style="
                      font-size: 16px;
                      font-weight: 600;
                      padding-left: 30px;
                    "
                  >
                    {{ $t('DocumentsCard.goals') }}
                  </q-th>
                  <q-th
                    style="
                      font-size: 16px;
                      font-weight: 600;
                      padding-left: 30px;
                    "
                  >
                    {{ $t('DocumentsCard.actions') }}
                  </q-th>
                  <q-th
                    style="
                      font-size: 16px;
                      font-weight: 600;
                      padding-left: 30px;
                    "
                  >
                    {{ $t('DocumentsCard.templateName') }}
                  </q-th>
                  <q-th
                    style="
                      font-size: 16px;
                      font-weight: 600;
                      padding-left: 30px;
                    "
                  >
                    {{ $t('DocumentsCard.templateActions') }}
                  </q-th>
                </q-tr>
              </template>
              <template v-slot:body="props">
                <q-tr :props="props">
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.value }}
                  </q-td>
                  <q-td>
                    <span
                      v-for="(goal, index) in getGoalsForDocuments(
                        props.row.code
                      )"
                      style="display: inline-block; margin: 5px"
                      :key="`goal-${index}`"
                      :props="props"
                    >
                      <q-badge :color="goalColorMap[goal]" :label="goal" />
                    </span>
                  </q-td>
                  <q-td style="text-align: right">
                    <q-btn
                      v-if="state === 'inProgress' && canEdit"
                      @click="editDocument(props.row)"
                      icon="edit"
                      text-color="primary"
                    >
                      <q-tooltip :delay="500"> Редактировать</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="state === 'inProgress' && canEdit"
                      text-color="negative"
                      @click="toggleDeleteConfim(props.row)"
                      icon="delete"
                      flat
                    >
                      <q-tooltip :delay="500"> Удалить</q-tooltip>
                    </q-btn>
                  </q-td>
                  <q-td style="text-align: right">
                    {{ props.row.templateUrl }}
                  </q-td>
                  <q-td style="text-align: right">
                    <q-btn
                      v-if="
                        get(props.row, 'templateUrl') &&
                        props.row.templateFormat !== 'HTML'
                      "
                      target="_blank"
                      icon="arrow_downward"
                      text-color="primary"
                      :loading="fetchingInProgress[props.row.id]"
                      @click="fetchDocumentAttachment(props.row)"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.DownloadTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>

                    <q-btn
                      v-if="
                        state === 'inProgress' &&
                        props.row.templateFormat !== 'HTML' &&
                        canEdit
                      "
                      icon="attach_file"
                      text-color="primary"
                      @click="addDocumentAttachment(props.row)"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.UploadTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="!props.row.templateUrl && canEdit"
                      icon="add_box"
                      text-color="primary"
                      @click="createTemplate(props.row)"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.CreateTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>

                    <q-btn
                      v-if="
                        !!props.row.templateUrl &&
                        props.row.templateFormat === 'HTML' &&
                        canEdit
                      "
                      icon="edit"
                      text-color="primary"
                      @click="editTemplate(props.row)"
                    >
                      <q-tooltip :delay="500"
                        >{{
                          $t('DocumentsCard.EditTemplateTooltip')
                        }}н</q-tooltip
                      >
                    </q-btn>
                    <q-btn
                      v-if="!!props.row.templateUrl"
                      icon="quiz"
                      text-color="primary"
                      @click="testTemplate(props.row)"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.TestTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="!!props.row.templateUrl && canEdit"
                      icon="delete"
                      text-color="negative"
                      @click="removeTemplate(props.row)"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.DeleteTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>
                  </q-td>
                </q-tr>
              </template>
            </q-table>
          </q-expansion-item>
          <q-expansion-item default-opened v-if="mvzDocTable.length">
            <template v-slot:header>
              <q-item-section>
                <div class="text-h6">
                  {{ $t('DocumentsCard.mvzDoctableTitle') }}
                </div>
              </q-item-section>
            </template>
            <q-table
              :columns="columns"
              :data="mvzDocTable"
              :pagination.sync="pagination"
              hide-bottom
            >
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.label }}
                  </q-th>

                  <q-th
                    style="
                      text-align: right;
                      font-size: 16px;
                      font-weight: 600;
                      padding-left: 30px;
                    "
                  >
                    {{ $t('DocumentsCard.actions') }}
                  </q-th>
                </q-tr>
              </template>
              <template v-slot:body="props">
                <q-tr :props="props">
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.value }}
                  </q-td>
                  <q-td style="text-align: right">
                    <q-btn
                      v-if="state === 'inProgress' && canEdit"
                      @click="editDocument(props.row)"
                      icon="edit"
                      text-color="primary"
                    >
                      <q-tooltip :delay="500"> Редактировать</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="canEdit"
                      text-color="negative"
                      @click="toggleDeleteConfim(props.row)"
                      icon="delete"
                      flat
                    >
                      <q-tooltip :delay="500"> Удалить</q-tooltip>
                    </q-btn>
                  </q-td>
                </q-tr>
              </template>
            </q-table>
          </q-expansion-item>
          <q-expansion-item default-opened v-if="applicantTable.length">
            <template v-slot:header>
              <q-item-section>
                <div class="text-h6">
                  {{ $t('DocumentsCard.applicantTableTitle') }}
                </div>
              </q-item-section>
            </template>
            <q-table
              :columns="columns"
              :data="applicantTable"
              :pagination.sync="pagination"
              hide-bottom
            >
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.label }}
                  </q-th>

                  <q-th
                    style="
                      text-align: right;
                      font-size: 16px;
                      font-weight: 600;
                      padding-left: 30px;
                    "
                  >
                    {{ $t('DocumentsCard.actions') }}
                  </q-th>
                </q-tr>
              </template>
              <template v-slot:body="props">
                <q-tr :props="props">
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.value }}
                  </q-td>
                  <q-td style="text-align: right">
                    <q-btn
                      v-if="state === 'inProgress' && canEdit"
                      @click="editDocument(props.row)"
                      icon="edit"
                      text-color="primary"
                    >
                      <q-tooltip :delay="500"> Редактировать</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="canEdit"
                      text-color="negative"
                      @click="toggleDeleteConfim(props.row)"
                      icon="delete"
                      flat
                    >
                      <q-tooltip :delay="500"> Удалить</q-tooltip>
                    </q-btn>
                  </q-td>
                </q-tr>
              </template>
            </q-table>
          </q-expansion-item>
          <q-expansion-item default-opened v-if="lpTable.length">
            <template v-slot:header>
              <q-item-section>
                <div class="text-h6">
                  {{ $t('DocumentsCard.personal') }}
                </div>
              </q-item-section>
            </template>
            <q-table
              :columns="columns"
              :data="lpTable"
              :pagination.sync="pagination"
              hide-bottom
            >
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.label }}
                  </q-th>

                  <q-th
                    style="
                      text-align: right;
                      font-size: 16px;
                      font-weight: 600;
                      padding-left: 30px;
                    "
                  >
                    {{ $t('DocumentsCard.actions') }}
                  </q-th>
                </q-tr>
              </template>
              <template v-slot:body="props">
                <q-tr :props="props">
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.value }}
                  </q-td>
                  <q-td style="text-align: right">
                    <q-btn
                      v-if="state === 'inProgress' && canEdit"
                      @click="editDocument(props.row)"
                      icon="edit"
                      text-color="primary"
                    >
                      <q-tooltip :delay="500"> Редактировать</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="canEdit"
                      text-color="negative"
                      @click="toggleDeleteConfim(props.row)"
                      icon="delete"
                      flat
                    >
                      <q-tooltip :delay="500"> Удалить</q-tooltip>
                    </q-btn>
                  </q-td>
                </q-tr>
              </template>
            </q-table>
          </q-expansion-item>
          <q-expansion-item default-opened v-if="printTable.length">
            <template v-slot:header>
              <q-item-section>
                <div class="text-h6">
                  {{ $t('DocumentsCard.ApplicationPrintTableTitle') }}
                </div>
              </q-item-section>
            </template>
            <q-table :columns="columns" :data="printTable" hide-bottom>
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.label }}
                  </q-th>

                  <q-th
                    style="
                      text-align: right;
                      font-size: 16px;
                      font-weight: 600;
                      padding-left: 30px;
                    "
                  >
                    {{ $t('DocumentsCard.actions') }}
                  </q-th>
                </q-tr>
              </template>
              <template v-slot:body="props">
                <q-tr :props="props">
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.value }}
                  </q-td>
                  <q-td style="text-align: right">
                    <q-btn
                      v-if="get(props.row, 'templateUrl')"
                      target="_blank"
                      icon="arrow_downward"
                      text-color="primary"
                      :loading="fetchingInProgress[props.row.id]"
                      @click="fetchDocumentAttachment(props.row)"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.DownloadTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>

                    <q-btn
                      v-if="state === 'inProgress'"
                      icon="attach_file"
                      text-color="primary"
                      @click="addDocumentAttachment(props.row)"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.UploadTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>

                    <q-btn
                      v-if="state === 'inProgress'"
                      @click="editDocument(props.row)"
                      icon="edit"
                      text-color="primary"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.EditTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="!!props.row.templateUrl"
                      icon="quiz"
                      text-color="primary"
                      @click="testTemplate(props.row)"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.TestTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="state === 'inProgress'"
                      text-color="negative"
                      @click="toggleDeleteConfim(props.row)"
                      icon="delete"
                      flat
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.DeleteTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>
                  </q-td>
                </q-tr>
              </template>
            </q-table>
          </q-expansion-item>
          <q-expansion-item default-opened v-if="specialistTable.length">
            <template v-slot:header>
              <q-item-section>
                <div class="text-h6">
                  {{ $t('DocumentsCard.DocumentsSentApplicant') }}
                </div>
              </q-item-section>
            </template>
            <q-table
              :columns="columns"
              :data="specialistTable"
              :pagination.sync="pagination"
              hide-bottom
            >
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.label }}
                  </q-th>

                  <q-th
                    style="
                      text-align: right;
                      font-size: 16px;
                      font-weight: 600;
                      padding-left: 30px;
                    "
                  >
                    {{ $t('DocumentsCard.actions') }}
                  </q-th>
                </q-tr>
              </template>
              <template v-slot:body="props">
                <q-tr :props="props">
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.value }}
                  </q-td>
                  <q-td style="text-align: right">
                    <q-btn
                      v-if="state === 'inProgress' && canEdit"
                      @click="editDocument(props.row)"
                      icon="edit"
                      text-color="primary"
                    >
                      <q-tooltip :delay="500"> Редактировать</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="canEdit"
                      text-color="negative"
                      @click="toggleDeleteConfim(props.row)"
                      icon="delete"
                      flat
                    >
                      <q-tooltip :delay="500"> Удалить</q-tooltip>
                    </q-btn>
                  </q-td>
                </q-tr>
              </template>
            </q-table>
          </q-expansion-item>
          <q-expansion-item default-opened v-if="receptionTable.length">
            <template v-slot:header>
              <q-item-section>
                <div class="text-h6">
                  {{ $t('DocumentsCard.receptionTemplate') }}
                </div>
              </q-item-section>
            </template>
            <q-table :columns="columns" :data="receptionTable" hide-bottom>
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.label }}
                  </q-th>

                  <q-th
                    style="
                      text-align: right;
                      font-size: 16px;
                      font-weight: 600;
                      padding-left: 30px;
                    "
                  >
                    {{ $t('DocumentsCard.actions') }}
                  </q-th>
                </q-tr>
              </template>
              <template v-slot:body="props">
                <q-tr :props="props">
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    {{ col.value }}
                  </q-td>
                  <q-td style="text-align: right">
                    <q-btn
                      v-if="get(props.row, 'templateUrl')"
                      target="_blank"
                      icon="arrow_downward"
                      text-color="primary"
                      :loading="fetchingInProgress[props.row.id]"
                      @click="fetchDocumentAttachment(props.row)"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.DownloadTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>

                    <q-btn
                      v-if="state === 'inProgress'"
                      icon="attach_file"
                      text-color="primary"
                      @click="addDocumentAttachment(props.row)"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.UploadTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>

                    <q-btn
                      v-if="state === 'inProgress'"
                      @click="editDocument(props.row)"
                      icon="edit"
                      text-color="primary"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.EditTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="!!props.row.templateUrl"
                      icon="quiz"
                      text-color="primary"
                      @click="testTemplate(props.row)"
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.TestTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="state === 'inProgress'"
                      text-color="negative"
                      @click="toggleDeleteConfim(props.row)"
                      icon="delete"
                      flat
                    >
                      <q-tooltip :delay="500">{{
                        $t('DocumentsCard.DeleteTemplateTooltip')
                      }}</q-tooltip>
                    </q-btn>
                  </q-td>
                </q-tr>
              </template>
            </q-table>
          </q-expansion-item>
        </div>
        <div class="full-width text-center" v-else>
          {{ $t('DocumentsCard.noProcessesResult') }}
        </div>
      </div>
      <q-dialog class="full-width" @hide="clearModel" v-model="openModal">
        <q-card class="no-shadow full-width">
          <q-card-section>
            <div class="text-h6">
              {{ $t('DocumentsCard.uploadAttachFile') }}
            </div>
          </q-card-section>
          <q-card-section>
            <q-file
              filled
              accept=".doc,.docx"
              v-model="attachFile"
              label="Загрузить шаблон"
            />
          </q-card-section>
          <q-card-section>
            <div class="q-gutter-sm">
              <q-checkbox v-model="normalize" label="Нормализовать">
                <q-tooltip :delay="500">
                  Удалить форматирование word внутри тегов mustache
                </q-tooltip>
              </q-checkbox>
            </div>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              @click="updateDocumentAttachment"
              color="primary"
              :loading="attachmentLoading"
              label="Загрузить"
            />

            <q-btn
              color="white"
              text-color="primary"
              outline
              @click="openModal = false"
              label="Отменить"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
      <q-dialog class="full-width" v-model="deleteConfim">
        <q-card class="no-shadow full-width">
          <q-card-section>
            <div class="text-h6">
              {{ $t('DocumentsCard.confirmationMessage') }}
            </div>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn @click="deleteDocument" color="primary" label="Удалить" />

            <q-btn
              color="white"
              text-color="primary"
              outline
              @click="toggleDeleteConfim"
              label="Отменить"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
      <q-dialog class="full-width" v-model="validateError">
        <q-card class="no-shadow full-width">
          <q-card-section>
            <div class="text-h6">
              {{ $t('DocumentsCard.validationError') }}
            </div>
          </q-card-section>
          <q-card-section>
            <div class="error-code">{{ validateErrorMessage }}}</div>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              color="white"
              text-color="primary"
              outline
              @click="validateError = false"
              label="Закрыть"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
      <q-dialog class="full-width" v-model="testTemplateModal">
        <q-card class="no-shadow full-width">
          <q-card-section>
            <div class="text-h6">
              {{ $t('DocumentsCard.templateTesting') }} : {{ testTemplateUrl }}
            </div>
          </q-card-section>
          <q-card-section>
            <v-json-editor
              v-model="testJson"
              :options="{ mode: 'code' }"
              height="400px"
            />
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              @click="printTestDocument"
              color="primary"
              :loading="documentTesting"
              label="Печать"
            />
            <q-btn
              color="white"
              text-color="primary"
              outline
              @click="testTemplateModal = false"
              label="Закрыть"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </q-card>

    <RegistryCreationDialog
      :common="common"
      :model="model"
      @commonModels="commonModels"
      :dialog-data="formModel"
    />
    <ListDialog
      :common="common"
      :model="model"
      @commonModels="commonModels"
      :dialog-data="listModel"
    />
    <DocumentDialog
      :common="common"
      :model="model"
      @commonModels="commonModels"
      :dialog-data="formModel"
    />
  </div>
</template>

<script lang="ts">
// @ts-nocheck
// @ts-ignore
import VJsonEditor from 'v-jsoneditor';
import testDocumentData from './testDocumentData.json';
import { saveFileViaLink } from '@utils/files';
import PrinterService from '@services/printer/index';
import {
  fetchAttachment,
  fetchDocument,
  unlinkService,
  updateAttachment,
  updateDocument,
} from '@services/registry-service';
import { AttachmentApi } from '@openapi/registry-service';
import get from 'lodash/get';
import cloneDeep from 'lodash/cloneDeep';
import { notifyError } from '@utils/notify';
import ListDialog from '@components/cards/services/ListDialog.vue';
import RegistryCreationDialog from '@components/cards/services/RegistryCreationDialog.vue';
import DocumentDialog from '@components/cards/services/DocumentDialog.vue';
import axios from 'axios';
import { PRINT_APPLICATION, RECEPTION_PRINT_APPLICATION } from '@utils/statement-print';

const attachmentApi = new AttachmentApi();

export default {
  name: 'ServiceDocuments',
  components: {
    VJsonEditor,
    ListDialog,
    RegistryCreationDialog,
    DocumentDialog,
  },
  props: ['common', 'model'],
  data() {
    return {
      deleteConfim: false,
      validateError: false,
      validateErrorMessage: '',
      testTemplateModal: false,
      testTemplateUrl: '',
      testDocumentId: null,
      testTemplateFormat: '',
      testJson: testDocumentData,
      normalize: true,
      deleteItem: null,
      formComponent: null,
      formModel: {},
      listModel: {},
      pagination: {
        rowsPerPage: 0,
      },
      attachFile: null,
      attachedFileName: '',
      documentForAttachmentUUID: '',
      attachmentLoading: false,
      documentTesting: false,
      openModal: false,
      schemaName: 'ServiceDocument',
      fetchingInProgress: {},
      documentForAttachment: null,
    };
  },
  methods: {
    get,
    toggleDeleteConfim(item = null) {
      this.deleteConfim = !this.deleteConfim;
      this.deleteItem = item;
    },
    clearModel() {
      this.attachedFileName = '';
      this.attachFile = '';
    },

    fetchForm(template, component) {
      this[component] = this.$GlobalComponentImporter.registerComponent(
        template,
        `cards/services/`
      );
    },

    createRegistry() {
      this.fetchForm('registry_creation_dialog', 'formComponent');
      this.commonModels({
        RegistryCreationDialog: {},
      });
    },

    changelist() {
      this.fetchForm('list_dialog', 'listComponent');
      this.commonModels({
        ListDialog: {
          data: {
            collection: 'documents',
          },
        },
      });
    },
    editDocument(row) {
      this.fetchForm('document_dialog', 'formComponent');
      this.commonModels({
        DocumentDialog: {
          data: row,
        },
      });
    },

    addDocument() {
      this.fetchForm('document_dialog', 'formComponent');
      this.commonModels({
        DocumentDialog: {
          data: 'createMode',
        },
      });
    },
    async deleteDocument() {
      try {
        const { data: result } = await unlinkService({
          id: get(this.basicModel, 'id'),
          documents: [get(this.deleteItem, 'id')],
          modified: get(this.basicModel, 'modified'),
        });
        this.basicModel.documents = this.table.filter(
          (i) => i.id !== this.deleteItem.id
        );
        this.basicModel.modified = result.modified;
        this.$store.dispatch(
          'registryService/services/setCardForJson',
          this.basicModel
        );
      } catch (e) {
        notifyError(e.message.toString());
      } finally {
        this.toggleDeleteConfim();
      }
    },
    commonModels(val) {
      this.$emit('commonModels', val);
    },

    getGoalsForDocuments(code) {
      const document = this.documentsWithGoals.find((i) => i.code === code);
      return get(document, 'goal', []);
    },
    createTemplate(document) {
      updateDocument(this.schemaName, [
        {
          id: document.id,
          modified: document.modified,
          templateFormat: 'HTML',
        },
      ]).then(() => {
        this.$set(document, 'templateFormat', 'HTML');
        this.$router.push(`/print-templates/create/${document.id}`);
      });
    },
    editTemplate(document) {
      this.$router.push(
        `/print-templates/edit/${document.id}/${document.templateUrl}`
      );
    },
    testTemplate(document) {
      this.testTemplateModal = true;
      this.testTemplateUrl = document.templateUrl;
      this.testTemplateFormat =
        document.templateFormat === 'HTML' ? 'HTML' : 'DOCX';
      this.testDocumentId = document.id;
    },
    async printTestDocument() {
      if (!this.testTemplateUrl || !this.testDocumentId) {
        return;
      }
      try {
        this.documentTesting = true;

        const url = await fetchAttachment(
          this.schemaName,
          this.testDocumentId,
          this.testTemplateUrl
        );

        const { data: blob } = await axios.get(url, {
          responseType: 'arraybuffer',
        });
        const file = new File([blob], `${this.testTemplateUrl}`);

        await PrinterService.fetchConvertedFileSync({
          input: this.testTemplateFormat,
          output: 'DOCX',
          template: file,
          parameters: JSON.stringify(this.testJson),
          fileName: this.testTemplateUrl,
          type:
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        }).catch((error) => {
          if (error.hasOwnProperty('body')) {
            this.validateErrorMessage = error.body;
            this.validateError = true;
          }
          throw new Error(this.$t('DocumentsCard.templateValidationFailed'));
        });
      } catch (e) {
        notifyError(e.message.toString());
      } finally {
        this.documentTesting = false;
        this.testTemplateModal = false;
        this.testTemplateUrl = null;
        this.testTemplateFormat = '';
        this.testDocumentId = null;
      }
    },
    removeTemplate(document) {
      this.$q
        .dialog({
          title: 'Удалить шаблон?',
          message: `Удалить шаблон "${document.templateUrl}"`,
          cancel: true,
          persistent: true,
        })
        .onOk(() => {
          attachmentApi
            .deleteDocumentFile(
              document.schema,
              document.id,
              document.templateUrl
            )
            .then(() => fetchDocument(this.schemaName, document.id))
            .then(({ data: result }) =>
              updateDocument(this.schemaName, [
                {
                  id: document.id,
                  templateUrl: '',
                  templateFormat: '',
                  modified: result.modified,
                },
              ])
            )
            .then(({ data: result }) => {
              if (result.success) {
                this.$set(document, 'templateUrl', '');
                this.$set(document, 'templateFormat', '');
              }
            })
            .catch((e) => {
              notifyError(e.message.toString);
            });
        });
    },
    addDocumentAttachment(document) {
      this.documentForAttachment = document;
      this.attachedFileName = document.code;
      this.documentForAttachmentUUID = document.id;
      this.openModal = true;
    },

    async updateDocumentAttachment() {
      if (!this.attachedFileName || !this.attachFile) {
        return;
      }
      try {
        this.attachmentLoading = true;

        const document = this.documentForAttachment;
        const docUUID = this.documentForAttachmentUUID;
        const fileName = `template_${this.attachedFileName}.docx`;
        let file = new File([this.attachFile], fileName);

        if (this.normalize) {
          const blob = await PrinterService.normalizeFile({
            template: file,
            parameters: JSON.stringify({ todo: 'allowEmptyParams' }),
          }).catch(() => {
            throw new Error(
              this.$t('DocumentsCard.templateNormalizationFailed')
            );
          });
          file = new File([blob], fileName);
        }

        await PrinterService.fetchConvertedFileSync({
          input: 'DOCX',
          output: 'DOCX',
          template: file,
          parameters: JSON.stringify({ todo: 'allowEmptyParams' }),
          preventDownload: true,
        }).catch((error) => {
          if (error.hasOwnProperty('body')) {
            this.validateErrorMessage = error.body;
            this.validateError = true;
          }
          throw new Error(this.$t('DocumentsCard.templateValidationFailed'));
        });

        const { data: result } = await updateAttachment(
          this.schemaName,
          docUUID,
          undefined,
          [file]
        );

        if (result.success) {
          updateDocument(this.schemaName, [
            {
              templateUrl: fileName,
              templateFormat: 'DOCX',
              id: docUUID,
              modified: result.modified,
            },
          ]).then(({ data: result }) => {
            if (result.success) {
              this.$set(document, 'templateFormat', 'DOCX');
              this.$set(document, 'templateUrl', fileName);
            }
          });
        }
      } catch (e) {
        notifyError(e.message.toString());
      } finally {
        this.attachmentLoading = false;
        this.openModal = false;
        this.documentForAttachmentUUID = null;
        this.documentForAttachment = null;
        this.attachedFileName = null;
      }
    },

    async fetchDocumentAttachment(document) {
      const fileName = document.templateUrl;

      if (fileName) {
        this.$set(this.fetchingInProgress, document.id, true);

        const url = await fetchAttachment(
          this.schemaName,
          document.id,
          fileName
        ).catch(() => {
          this.$set(this.fetchingInProgress, document.id, false);
        });

        if (url) {
          const { data: blob } = await axios.get(url, {
            responseType: 'blob',
          });
          saveFileViaLink({
            anchor: this.$refs.export,
            blob,
            fileName,
          });
        }

        this.$set(this.fetchingInProgress, document.id, false);
      } else {
        notifyError(
          this.$t('RegistryObjectCard.documentFileUrlIsEmpty').toString()
        );
      }
    },
    getDocumentStages(doc, stages) {
      return doc.map((i) => {
        stages.forEach((element) => {
          if (!element.documents) {
            return;
          }

          const doc = element.documents;

          if (
            doc.reject &&
            doc.reject.find(
              (f) => f === i.code || (f.code && f.code === i.code)
            )
          ) {
            i.stages = 'reject';
          }

          if (
            doc.apply &&
            doc.apply.find((f) => f === i.code || (f.code && f.code === i.code))
          ) {
            i.stages = 'apply';
          }
        });

        return i;
      });
    },
    processes(name) {
      const card = this.$store.getters['registryService/services/servicesCard'];

      const stages = card.stages || [];

      const documents = card.documents || [];

      this.getDocumentStages(documents, stages);

      return (card.documents || []).filter((i) => i.source === name);
    },
    goToModeler() {
      const route = {
        path: '/services/modeler/registries/create',
        query: {
          serviceRegistryID: get(this.basicModel, 'id'),
          serviceLabel: get(this.basicModel, 'shortName'),
          serviceCode: `registry${get(this.basicModel, 'id')}`,
          from: window.location.href,
        },
      };

      this.$router.push(route);
    },
  },
  computed: {
    loadingCard() {
      return (
        this.$store.getters['registryService/services/servicesLoading'] || false
      );
    },
    basicModel() {
      return cloneDeep(
        this.$store.getters['registryService/services/servicesCard']
      );
    },
    columns() {
      const headerStyle = 'font-size: 16px; font-weight: 600';
      return [
        {
          align: 'left',
          field: 'code',
          label: this.$t('DocumentsCard.code'),
          name: 'code',
          sortable: true,
          style: 'white-space: normal',
          headerStyle,
        },
        {
          align: 'left',
          field: 'name',
          label: this.$t('DocumentsCard.name'),
          name: 'name',
          sortable: true,
          style: 'white-space: normal',
          headerStyle,
        },
      ];
    },
    mvzDocTable() {
      return this.processes('MVZ');
    },
    applicantTable() {
      return this.processes('Applicant');
    },
    ResultTable() {
      return this.processes('result');
    },
    lpTable() {
      return this.processes('ЛП');
    },
    specialistTable() {
      return this.processes('Specialist');
    },
    printTable() {
      return this.processes(PRINT_APPLICATION);
    },
    receptionTable() {
      return this.processes(RECEPTION_PRINT_APPLICATION);
    },
    documentsWithGoals() {
      const stages = get(this.basicModel, 'stages', []);
      return (
        stages
          .map((el) => el.documents)
          .filter((el) => el)
          .map((el) => {
            return Object.keys(el).reduce(
              (arr, key) => arr.concat(el[key]),
              []
            );
          })
          .reduce((arr, el) => arr.concat(el), [])
          .filter((el) => el && el.goal) || []
      );
    },
    table() {
      return get(this.basicModel, 'documents', []);
    },
    state() {
      return get(this.basicModel, 'state', 'inProgress');
    },
    goalColorMap() {
      return this.$store.getters['registryService/services/goalColorMap'];
    },
    isOneOfTheTables() {
      return (
        this.ResultTable.length ||
        this.mvzDocTable.length ||
        this.applicantTable.length ||
        this.printTable.length ||
        this.lpTable.length ||
        this.specialistTable.length
      );
    },
    canEdit(): boolean {
      return this.$store.getters['registryService/services/canEdit'];
    },
  },
};
</script>

<style scoped lang="scss">
.error-code {
  font-family: monospace;
}
</style>
