<i18n>
{
  "en": {
    "DigitalReglament": {
      "subServices": "subServices",
      "id": "id",
      "fullName": "fullName",
      "shortName": "shortName",
      "srgu": "srgu",
      "payable": "payable",
      "maxPeriodOfProviding": "maxPeriodOfProviding",
      "maxPeriodOfProvidingComment": "maxPeriodOfProvidingComment",
      "minPeriodOfProviding": "minPeriodOfProviding",
      "minPeriodOfProvidingComment": "minPeriodOfProvidingComment",
      "applicantCategories": "applicantCategories",
      "smevRequests": "smevRequests",
      "documents": "documents",
      "documentsResult": "documentsResult",
      "administrativeProcedures": "administrativeProcedures",
      "profilings": "profilings"
    }
  },
  "ru": {
    "DigitalReglament": {
      "subServices": "Подуслуги",
      "id": "Идентификатор",
      "fullName": "Полное наименование подуслуги",
      "shortName": "Краткое наименование подуслуги",
      "srgu": "Подуслуга СРГУ",
      "payable": "Признак наличия оплаты",
      "maxPeriodOfProviding": "Срок регистрации заявления",
      "maxPeriodOfProvidingComment": "Пояснение к сроку регистрации заявления",
      "minPeriodOfProviding": "Максимальный срок оказания подуслуги",
      "minPeriodOfProvidingComment": "Пояснение к сроку оказания подуслуги",
      "applicantCategories": "Категория заявителя",
      "smevRequests": "Межведомственное взаимодействие",
      "documents": "Документы, необходимые для получения услуги",
      "documentsResult": "Документы, предоставляемые по завершении услуги",
      "administrativeProcedures": "Административные процедуры",
      "profilings": "Профилирование"
    }
  }
}
</i18n>

<template>
  <div
    v-if="common.active === 'digital_regulations' && !loadingCard"
    class="q-pb-md"
  >
    <a ref="download" />
    <q-card class="no-shadow q-gutter-y-md q-mx-md no-border-radius">
      <div
        class="bg-white q-px-lg q-pb-md q-pt-sm q-mt-md q-mx-md rounded-borders"
      >
        <div class="full-width">
          <div
            class="flex justify-between row reverse bg-white q-pa-md rounded-borders"
          >
            <q-btn
              v-if="reglament"
              unelevated
              color="secondary"
              label="Скачать ЦР"
              @click="openFile(void 0)"
            />
          </div>
          <h6>{{ $t('ProcessesCard.tableTitle') }}</h6>
          <q-table
            v-if="processes.length"
            :columns="columns"
            :data="processes"
            hide-bottom
          >
            <template #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">
                  {{ $t('ProcessesCard.actions') }}
                </q-th>
              </q-tr>
            </template>
            <template #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 auto-width>
                  <q-btn
                    icon="arrow_downward"
                    unelevated
                    color="white"
                    text-color="primary"
                    @click="openFile(props.row)"
                  >
                    <q-tooltip :delay="500"> Скачать</q-tooltip>
                  </q-btn>
                </q-td>
              </q-tr>
            </template>
          </q-table>

          <h6>{{ $t('DigitalReglament.profilings') }}</h6>
          <q-table
            v-if="profilings.length"
            :columns="columns"
            :data="profilings"
            hide-bottom
          >
            <template #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">
                  {{ $t('ProcessesCard.actions') }}
                </q-th>
              </q-tr>
            </template>
            <template #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 auto-width>
                  <q-btn
                    icon="arrow_downward"
                    unelevated
                    color="white"
                    text-color="primary"
                    @click="openFile(props.row)"
                  >
                    <q-tooltip :delay="500"> Скачать</q-tooltip>
                  </q-btn>
                </q-td>
              </q-tr>
            </template>
          </q-table>

          <div v-if="subServices" class="q-gutter-y-md q-pt-lg">
            <h6>{{ $t('DigitalReglament.subServices') }}</h6>

            <q-list
              v-for="(service, i) in subServices"
              :key="`service-${i}`"
              bordered
            >
              <q-expansion-item expand-separator class="bg-grey-2">
                <template #header>
                  <q-item-section>
                    <b>{{ $t(service.fullName) }}</b>
                  </q-item-section>
                </template>

                <q-card class="bg-grey-2">
                  <q-card-section>
                    <base-label-value
                      v-for="(attr, j) in attrList"
                      :key="`attr-${j}`"
                      class="q-pa-xs q-gutter-x-md"
                    >
                      <template #label>
                        {{ $t(`DigitalReglament.${attr}`) }}
                      </template>

                      <template #value>
                        {{ get(service, `${attr}`) }}
                      </template>
                    </base-label-value>

                    <base-label-value
                      v-if="service.documents"
                      class="q-pa-xs q-gutter-x-md"
                    >
                      <template #label>
                        {{ $t('DigitalReglament.documents') }}
                      </template>

                      <template #value>
                        <div
                          v-for="(item, k) in inputDocuments(service.documents)"
                          :key="`documents-${k}`"
                          class="q-pb-xs"
                        >
                          {{ item.value }}
                          <div>({{ item.id }})</div>
                        </div>
                      </template>
                    </base-label-value>

                    <base-label-value
                      v-if="service.documents"
                      class="q-pa-xs q-gutter-x-md"
                    >
                      <template #label>
                        {{ $t('DigitalReglament.documentsResult') }}
                      </template>

                      <template #value>
                        <div
                          v-for="(item, k) in resultDocuments(
                            service.documents
                          )"
                          :key="`documentsResult-${k}`"
                          class="q-pb-xs"
                        >
                          {{ item.value }}
                          <div>({{ item.id }})</div>
                        </div>
                      </template>
                    </base-label-value>

                    <base-label-value
                      v-if="service.administrativeProcedures"
                      class="q-pa-xs q-gutter-x-md"
                    >
                      <template #label>
                        {{ $t('DigitalReglament.administrativeProcedures') }}
                      </template>

                      <template #value>
                        <div
                          v-for="(item, k) in service.administrativeProcedures"
                          :key="`documentsProcedures-${k}`"
                          class="q-pb-xs"
                        >
                          {{ item.value }}
                        </div>
                      </template>
                    </base-label-value>

                    <base-label-value
                      v-if="
                        service.interdepartmentalRequest &&
                        service.interdepartmentalRequest.smevRequests
                      "
                      class="q-pa-xs q-gutter-x-md"
                    >
                      <template #label>
                        {{ $t('DigitalReglament.smevRequests') }}
                      </template>

                      <template #value>
                        <div
                          v-for="(item, k) in service.interdepartmentalRequest
                            .smevRequests"
                          :key="`smevRequests-${k}`"
                          class="q-pb-xs"
                        >
                          {{ item.value }}
                          <div>
                            ({{ item.smevOwner }}, {{ item.smevId }},
                            {{ item.smevVersion }})
                          </div>
                        </div>
                      </template>
                    </base-label-value>
                  </q-card-section>
                </q-card>
              </q-expansion-item>
            </q-list>
          </div>

          <div v-if="!reglament">{{ $t('DigitalReglament.noResult') }}</div>
        </div>
      </div>
    </q-card>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import { saveFileViaLink } from '@utils/files';
import { fetchAttachment } from '@services/registry-service';
import { DigitalReglamentApi } from '@openapi/registry-service';
import get from 'lodash/get';
import { notifyError } from '@utils/notify';

const digitalReglamentApi = new DigitalReglamentApi();

export default {
  name: 'FormModel',
  props: ['common', 'model'],
  data() {
    return {
      processes: [],
      profilings: [],
      attrList: [
        'id',
        'fullName',
        'payable',
        'maxPeriodOfProviding',
        'minPeriodOfProviding',
      ],
    };
  },
  computed: {
    loadingCard() {
      return (
        this.$store.getters['registryService/services/servicesLoading'] || false
      );
    },
    columns() {
      const headerStyle = 'font-size: 16px; font-weight: 600';
      return [
        {
          align: 'left',
          field: 'id',
          label: 'Идентификатор',
          name: 'id',
          sortable: true,
          headerStyle,
        },
        {
          align: 'left',
          field: 'name',
          label: 'Наименование',
          name: 'name',
          sortable: true,
          headerStyle,
        },
      ];
    },
    reglament() {
      const card = this.$store.getters['registryService/services/servicesCard'];
      const reglament = get(card, 'reglament');
      if (reglament && reglament.original && reglament.original.subServices) {
        reglament.original.subServices.forEach((item) => {
          if (item.administrativeProcedures) {
            this.sortValues(item.administrativeProcedures);
          }
          if (item.documents) {
            this.sortValues(item.documents);
          }
          if (
            item.interdepartmentalRequest &&
            item.interdepartmentalRequest.smevRequests
          ) {
            this.sortValues(item.interdepartmentalRequest.smevRequests);
          }
        });
      }
      return reglament;
    },
    subServices() {
      return get(this, 'reglament.original.subServices');
    },
  },
  watch: {
    reglament: function (reglament) {
      if (!reglament) return;
      this.initProcesses(reglament);
    },
  },
  methods: {
    get,
    resultDocuments(documents) {
      return documents.filter((document) => document.isResultDoc === 'true');
    },
    inputDocuments(documents) {
      return documents.filter((document) => document.isResultDoc === 'false');
    },
    sortValues(items) {
      return items.sort((a, b) => a.value.localeCompare(b.value));
    },
    async initProcesses(reglament) {
      const { data: result } = await digitalReglamentApi.getDigitalReglament(
        reglament.id,
        'processes'
      );
      this.processes = (result.processes || []).filter(
        (item) => item.type === 'adm'
      );
      this.profilings = (result.processes || []).filter(
        (item) => item.type === 'profiling'
      );
    },
    async openFile(row) {
      try {
        if (!get(this.reglament, 'id')) return;
        const schemaName = row ? 'DigitalReglamentProcess' : 'DigitalReglament';
        const fileName = get(row, 'code') || 'origin';
        const uuid = get(row, 'id') || get(this.reglament, 'id');
        const downloadName = get(row, 'code') || 'origin';
        const extension = row ? 'bpmn' : 'xml';
        const hrefData = 'data:application/bpmn20-xml;charset=UTF-8,';
        const xml = await fetchAttachment(schemaName, uuid, fileName, false);
        saveFileViaLink({
          anchor: this.$refs.download,
          hrefData: hrefData + encodeURIComponent(xml),
          fileName: `${downloadName}.${extension}`,
        });
      } catch (error) {
        notifyError(error.message.toString());
      }
    },
  },
};
</script>
