<i18n>
{
  "en": {
    "StageEdit": {
      "title": "Edit dictionary",
      "createTitle": "Create dictionary",
      "name": "Name",
      "code": "Code",
      "value": "Value",
      "documentsTitle": "Documents",
      "executionPeriodInDays": "Execution period in days",
      "notifyInHours": "Notify in hours",
      "confirmationMessage": "Are you sure you want to delete the object?"

    }
  },
  "ru": {
    "StageEdit": {
      "title": "Редактирование данных этапа",
      "createTitle": "Создание этапа",
      "name": "Имя",
      "code": "Код",
      "value": "Значение",
      "documentsTitle": "Записи",
      "confirmationMessage": "Вы уверены, что хотите удалить объект на всегда?",
      "executionPeriodInDays": "Период предоставления (рабочие дни)",
      "notifyInHours": "Время уведомления (часы)"
    }
  }
}
</i18n>

<template>
  <div>
    <q-dialog v-model="dialogOpen" @hide="clearModel">
      <q-card class="full-width no-shadow" style="max-width: 800px">
        <q-card-section> </q-card-section>

        <BaseTable
          v-model="search"
          :columns="columns"
          :data="dialogData"
          :use-search="true"
          :pagination.sync="pagination"
          title="Выберите объект"
          :selected.sync="selected"
          :loading="loading"
          selection="multiple"
          @update="init"
          @requestTable="init"
        >
          <template v-if="collection === 'dictionaries'" #user-toggle>
            <q-btn-toggle
              v-model="isExternal"
              toggle-color="primary"
              :options="serviceToggle"
            />
          </template>
          <template #body-item-actions="{ row }">
            <span v-if="collection !== 'interagencies'">
              <q-btn
                text-color="primary"
                icon="edit"
                flat
                @click="editDocument(row)"
                :disabled="row.nsiDictionaryId"
              />

              <q-btn
                text-color="negative"
                icon="delete"
                flat
                @click="toggleDeleteConfirm(row)"
                :disabled="row.nsiDictionaryId"
              />
            </span>
          </template>
        </BaseTable>

        <q-card-actions align="right">
          <q-btn label="Выбрать" unelevated color="primary" @click="edit" />

          <q-btn
            label="Закрыть"
            color="white"
            text-color="primary"
            outline
            @click="dialogOpen = false"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-dialog v-model="deleteConfirm" class="full-width">
      <q-card class="no-shadow full-width">
        <q-card-section>
          <div class="text-h6">{{ $t('StageEdit.confirmationMessage') }}</div>
        </q-card-section>

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

          <q-btn
            color="white"
            text-color="primary"
            outline
            label="Отменить"
            @click="toggleDeleteConfirm"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <component
      :is="formComponent"
      :common="common"
      :model="model"
      :dialog-data="formModel"
      @commonModels="dialogModels"
    />
  </div>
</template>
<script lang="ts">
// @ts-nocheck
import {
  DictionaryApi,
  DocumentApi,
  InteragencyApi,
} from '@openapi/registry-service';
import get from 'lodash/get';
import cloneDeep from 'lodash/cloneDeep';
import { BaseCardCommon } from '@/interfaces';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { DictionaryApi as NsiDictionaryApi } from '@openapi/dictionary-registry-nsi/api';
import { notifyError } from '@utils/notify';

const REG_UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
const dictionaryApi = new DictionaryApi();
const documentApi = new DocumentApi();
const interagencyApi = new InteragencyApi();
const nsiDictionaryApi = new NsiDictionaryApi();

const DOCUMENT_SCHEMA = 'ServiceDocument';

@Component({})
export default class ListDialog extends Vue {
  @Prop() common?: BaseCardCommon;
  @Prop() model?: any;

  private dialogData = [];
  private formModel = {};
  private dialogOpen = false;
  private loading = false;
  private search = '';
  private collection = '';
  private deleteConfirm = false;
  private formComponent = null;
  private deleteItem = null;
  private pagination = {
    rowsNumber: 0,
    page: 1,
    rowsPerPage: 10,
  };

  private selected = [];
  private isExternal = false;
  private serviceToggle = [
    { label: 'Внутренние', value: false },
    { label: 'Внешние', value: true },
  ];

  @Watch('search')
  private startInit() {
    this.init();
  }

  @Watch('isExternal')
  private getDictionaries() {
    this.init();
  }

  @Watch('common.models.ListDialog.data', { immediate: true })
  private async dataHandler(val) {
    if (val) {
      this.dialogOpen = true;
      this.collection = val.collection || 'documents';
      await this.init();
    }
  }

  get state() {
    return get(this.card, 'state', 'inProgress');
  }

  get columns() {
    return [
      {
        align: 'left',
        field: (val) => val.code || val.id,
        label: 'Код',
        name: 'code',
        style: 'white-space: normal',
        sortable: true,
      },
      {
        align: 'left',
        field: (val) => val.name || val.description,
        label: 'Наименование',
        name: 'name',
        style: 'white-space: normal',
        sortable: true,
      },
      {
        align: 'left',
        name: 'actions',
        style: 'white-space: normal; width: 150px',
        sortable: true,
      },
    ];
  }

  private edit() {
    const card = cloneDeep(
      this.$store.getters['registryService/services/servicesCard']
    );

    let data = card[this.collection] || [];
    data = data.concat(this.selected);
    card[this.collection] = data;
    this.$store.dispatch('registryService/services/setCardForJson', card);
    this.dialogOpen = false;
  }

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

  private dialogModels(val) {
    this.$emit('commonModels', val);
  }

  private editDocument(row) {
    const dataType =
      this.collection === 'documents' ? 'DocumentDialog' : 'DictionaryDialog';
    const formName =
      this.collection === 'documents' ? 'document_dialog' : 'dictionary_dialog';
    this.fetchForm(formName, 'formComponent');
    this.dialogModels({
      [dataType]: {
        data: row,
        editOnly: true,
      },
    });
  }

  private async init(data) {
    try {
      this.loading = true;
      const linkDictionaryApi = this.isExternal
        ? nsiDictionaryApi
        : dictionaryApi;
      const pagination = data?.pagination ? data.pagination : this.pagination;
      let result;
      let query: string;
      let fullText: string;
      
      if (REG_UUID.test(this.search.trim())) {
        query = `id=like=${this.search}`;
      } else {
        fullText = this.search;
      }

      switch (this.collection) {
        case 'dictionaries': {
          ({ data: result } = await linkDictionaryApi.pagingDictionary(
            pagination.page,
            pagination.rowsPerPage,
            query,
            fullText
              ? `name=search='${fullText}' or code=search='${fullText}' or name=searchprefix='${fullText}' or code=searchprefix='${fullText}'`
              : undefined
          ));
          break;
        }
        case 'interagencies': {
          ({ data: result } = await interagencyApi.pagingInteragency(
            pagination.page,
            pagination.perPage,
            query,
            fullText
              ? `class=search=${fullText} or description=search=${fullText} or class=searchprefix=${fullText} or description=searchprefix=${fullText}`
              : undefined
          ));
          break;
        }
        // https://jira.devsun.ru/browse/PGS-5389
        case 'documents': {
          ({ data: result } = await documentApi.pagingDocuments(
            DOCUMENT_SCHEMA,
            pagination.page,
            pagination.perPage,
            query,
            fullText
              ? `name=search='${fullText}' or code=search=${fullText} or name=searchprefix='${fullText}' or code=searchprefix=${fullText}`
              : undefined
          ));
          break;
        }
      }
      this.pagination.rowsNumber = result.totalRows;
      this.pagination.page = result.page;
      this.pagination.rowsPerPage = result.perPage;
      this.dialogData = result.records || [];
    } catch (e) {
      this.dialogData = [];
      notifyError(e.toString());
    } finally {
      this.loading = false;
    }
  }

  private toggleDeleteConfirm(item = null) {
    this.deleteConfirm = !this.deleteConfirm;
    this.deleteItem = item;
  }

  private async deleteObject() {
    try {
      const item = [get(this.deleteItem, 'id')];
      switch (this.collection) {
        case 'documents':
          await documentApi.deleteDocument(DOCUMENT_SCHEMA, item);
          break;
        case 'dictionaries':
          await dictionaryApi.deleteDictionary(item);
          break;
        case 'interagencies':
          await interagencyApi.deleteInteragency(item);
          break;
      }
      await this.init();
    } catch (e) {
      notifyError(e.message.toString());
    } finally {
      this.toggleDeleteConfirm();
      this.deleteItem = null;
    }
  }

  private clearModel() {
    this.selected = [];
    this.$emit('commonModels', {
      ListDialog: {
        data: null,
      },
    });
  }

  destroyed() {
    this.clearModel();
  }
}
</script>
