<i18n>
{
  "en": {
    "InterdepartmentalCard": {
      "id": "id",
      "clazz": "Class",
      "mapping": "Mapping",
      "requestName": "Name",
      "description": "Description",
      "mock": "mock link",
      "tableTitle": "Interdepartmental",
      "btnChose": "Chose Interdepartmental",
      "testMsg": "testMsg",
      "noProcessesResult": "No Processes result",
      "smevId": "smevId",
      "confirmationMessage": "Are you sure you want to delete the interagency?"
    }
  },
  "ru": {
    "InterdepartmentalCard": {
      "id": "Идентификатор",
      "clazz": "Класс",
      "mapping": "Маппинг",
      "requestName": "Наименование",
      "description": "Описание",
      "mock": "Ссылка на мок",
      "tableTitle": "Межведомственные запросы",
      "btnChose": "Выбрать межвед",
      "testMsg": "Признак testMsg",
      "noProcessesResult": "Межведомственные запросы не найдены",
      "smevId": "Код СМЭВ",
      "confirmationMessage": "Вы уверены, что хотите удалить межведомсвенный запрос?"
    }
  }
}
</i18n>

<template>
  <div class="q-pb-md" v-if="common.active === 'interagencies' && !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 q-mx-md rounded-borders"
      >
        <div class="flex justify-between q-my-md row" style="width: 100%">
          <div class="text-h6">
            {{ $t('InterdepartmentalCard.tableTitle') }}
          </div>
          <q-btn
            v-if="state === 'inProgress' && canEdit"
            color="primary"
            icon="search"
            @click="changelist"
            :label="$t('InterdepartmentalCard.btnChose')"
          />
        </div>
        <q-table
          :columns="columns"
          :data="interagencies"
          hide-bottom
          :pagination="pagination"
          v-if="interagencies.length"
        >
          <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">
                {{ $t('InterdepartmentalCard.mapping') }}
              </q-th>
              <q-th v-if="state === 'inProgress'" />
            </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 auto-width>
                <q-btn
                  size="sm"
                  v-if="get(props.row, 'mapping')"
                  unelevated
                  color="primary"
                  label="Посмотреть"
                >
                  <q-popup-proxy>
                    <q-banner>
                      <div
                        style="margin-bottom: 7px"
                        v-for="(value, name) in props.row.mapping.out"
                        v-bind:key="name"
                      >
                        <strong>{{ name }}:</strong> {{ value }}
                      </div>
                    </q-banner>
                  </q-popup-proxy>
                </q-btn>
              </q-td>
              <!--              todo template-->
              <q-td auto-width>
                <q-btn
                  v-if="get(props.row, 'mapping')"
                  unelevated
                  style="color: rgba(0, 0, 0, 0.54)"
                  icon="attach_file"
                  text-color="primary"
                >
                  <q-popup-proxy>
                    <attachment-editor
                      :attachments="props.row.attachments"
                      :schema="props.row.schema"
                      :id="props.row.id"
                      :canEdit="canEdit"
                      @setAttachments="setAttachments"
                    />
                  </q-popup-proxy>
                  <q-tooltip :delay="500">Вложения</q-tooltip>
                </q-btn>
              </q-td>
              <q-td v-if="state === 'inProgress'" auto-width>
                <q-btn
                  v-if="canEdit"
                  text-color="negative"
                  @click="toggleDeleteConfim(props.row)"
                  icon="delete"
                  flat
                />
              </q-td>
            </q-tr>
          </template>
        </q-table>
        <div class="full-width text-center" v-else>
          {{ $t('InterdepartmentalCard.noProcessesResult') }}
        </div>
      </div>
    </q-card>
    <q-dialog class="full-width" v-model="deleteConfim">
      <q-card class="no-shadow full-width">
        <q-card-section>
          <div class="text-h6">
            {{ $t('InterdepartmentalCard.confirmationMessage') }}
          </div>
        </q-card-section>

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

          <q-btn
            color="white"
            text-color="primary"
            outline
            @click="toggleDeleteConfim"
            label="Отменить"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <ListDialog
      :common="common"
      :model="model"
      @commonModels="commonModels"
      :dialog-data="formModel"
    />
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import { unlinkService } from '@services/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';

export default {
  props: ['common', 'model'],
  components: { ListDialog },
  name: 'interagencies',
  data() {
    return {
      deleteConfim: false,
      deleteItem: null,
      formModel: {},
      pagination: {
        rowsPerPage: 0,
      },
    };
  },
  methods: {
    get,
    setAttachments(data: any[], id: string): void {
      const card = this.card;
      this.$set(
        card.interagencies.find((item) => item.id === id),
        'attachments',
        data
      );
      this.$store.dispatch('registryService/services/setCardForJson', card);
    },
    toggleDeleteConfim(item = null) {
      this.deleteConfim = !this.deleteConfim;
      this.deleteItem = item;
    },
    async deleteInteragency() {
      try {
        const { data: result } = await unlinkService({
          id: get(this.card, 'id'),
          interagencies: [get(this.deleteItem, 'id')],
          modified: get(this.card, 'modified'),
        });
        this.card.interagencies = this.interagencies.filter(
          (i) => i.id !== this.deleteItem.id
        );
        this.card.modified = result.modified;
        this.$store.dispatch(
          'registryService/services/setCardForJson',
          this.card
        );
      } catch (e) {
        notifyError(e.message.toString());
      } finally {
        this.toggleDeleteConfim();
      }
    },

    changelist() {
      this.commonModels({
        ListDialog: {
          data: {
            collection: 'interagencies',
          },
        },
      });
    },
    commonModels(val) {
      this.$emit('commonModels', val);
    },
  },
  computed: {
    loadingCard() {
      return (
        this.$store.getters['registryService/services/servicesLoading'] || false
      );
    },
    state() {
      return get(this.card, 'state', 'inProgress');
    },
    card() {
      return cloneDeep(
        this.$store.getters['registryService/services/servicesCard']
      );
    },
    interagencies() {
      return get(this.card, 'interagencies', []);
    },
    columns() {
      const headerStyle = 'font-size: 16px; font-weight: 600';
      return [
        {
          align: 'left',
          field: 'id',
          label: this.$t('InterdepartmentalCard.id'),
          name: 'id',
          sortable: false,
          headerStyle,
        },
        {
          align: 'left',
          field: 'smevId',
          label: this.$t('InterdepartmentalCard.smevId'),
          name: 'smevId',
          sortable: false,
          headerStyle,
        },
        {
          align: 'left',
          field: 'clazz',
          label: this.$t('InterdepartmentalCard.clazz'),
          name: 'clazz',
          sortable: true,
          style: 'white-space: pre-wrap',
          headerStyle,
        },
        {
          align: 'left',
          field: 'requestName',
          label: this.$t('InterdepartmentalCard.requestName'),
          name: 'requestName',
          style: 'white-space: pre-wrap',
          sortable: true,
          headerStyle,
        },
        {
          align: 'left',
          field: 'description',
          label: this.$t('InterdepartmentalCard.description'),
          name: 'description',
          style: 'white-space: pre-wrap',
          sortable: true,
          headerStyle,
        },
        {
          align: 'left',
          field: 'mock',
          label: this.$t('InterdepartmentalCard.mock'),
          name: 'mock',
          sortable: true,
          style: 'white-space: pre-wrap',
          headerStyle,
        },
        {
          align: 'left',
          field: 'testMsg',
          label: this.$t('InterdepartmentalCard.testMsg'),
          name: 'testMsg',
          sortable: true,
          headerStyle,
        },
      ];
    },
    canEdit(): boolean {
      return this.$store.getters['registryService/services/canEdit'];
    },
  },
};
</script>
