<template>
  <q-card class="no-shadow">
    <template v-if="card && card.dictionaries && card.dictionaries.length">
      <q-card-section>
        <div class="text-h6">
          {{ $t('selectDictionary') }}
        </div>
      </q-card-section>
      <q-card-section>
        <q-table
          :columns="directoriesColumns"
          :data="card.dictionaries"
          :pagination.sync="pagination"
          hide-bottom
        >
          <template #header="props">
            <q-tr :props="props">
              <q-th style="font-size: 16px; font-weight: 600">
                {{ $t('action') }}
              </q-th>
              <q-th v-for="col in props.cols" :key="col.name" :props="props">
                {{ col.label }}
              </q-th>
            </q-tr>
          </template>
          <template #body="props">
            <q-tr :props="props">
              <q-td auto-width>
                <q-btn
                  text-color="primary"
                  :label="$t('services.export.select')"
                  @click="selectDictionary(props.row)"
                />
              </q-td>
              <q-td v-for="col in props.cols" :key="col.name" :props="props">
                {{ col.value }}
              </q-td>
              <!-- <q-td v-if="!props.row.nsiDictionaryId" auto-width>
                <q-btn
                  text-color="primary"
                  icon="edit"
                  flat
                  @click="viewDictionary(props.row, 'edit')"
                />

                <q-btn
                  text-color="negative"
                  icon="delete"
                  flat
                  @click="toggleDeleteConfim(props.row)"
                />
              </q-td>
              <q-td auto-width>
                <q-btn
                  text-color="primary"
                  icon="search"
                  flat
                  @click="viewDictionary(props.row, 'view')"
                />
              </q-td> -->
            </q-tr>
          </template>
        </q-table>
      </q-card-section>
      <q-dialog v-model="deleteConfim" class="full-width">
        <q-card class="no-shadow full-width">
          <q-card-section>
            <div class="text-h6">
              {{ $t('confirmationMessage') }}
            </div>
          </q-card-section>

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

            <q-btn
              color="white"
              text-color="primary"
              outline
              label="Отменить"
              @click="toggleDeleteConfim"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </template>
    <template v-else>
      <q-card-section>
        {{ $t('serviceHasNoDictionaries') }}
      </q-card-section>
    </template>
  </q-card>
</template>

<script lang="ts">
import { unlinkService } from '@/services/registry-service';
import { notifyError } from '@/utils/notify';
import cloneDeep from 'lodash/cloneDeep';
import get from 'lodash/get';
import { Component, Vue, Prop } from 'vue-property-decorator';
import { DictionaryApi } from '@openapi/registry-service';

const dictionaryApi = new DictionaryApi();

@Component
export default class DictSelector extends Vue {
  pagination = {
    rowsPerPage: 0,
  };
  deleteConfim = false;
  deleteItem: any = null;

  get directoriesColumns() {
    const headerStyle = 'font-size: 16px; font-weight: 600';
    return [
      {
        align: 'left',
        field: 'id',
        label: this.$t('code'),
        name: 'id',
        sortable: false,
        headerStyle,
      },
      {
        align: 'left',
        field: 'name',
        label: this.$t('name'),
        name: 'name',
        sortable: true,
        style: 'white-space: pre-wrap',
        headerStyle,
      },
    ];
  }

  get card() {
    return cloneDeep(
      this.$store.getters['registryService/services/servicesCard']
    );
  }

  viewDictionary(row: any, mode: any) {
    this.commonModels({
      DictionaryDialog: {
        data: row,
        mode: mode,
      },
    });
  }

  selectDictionary(row: any) {
    this.$emit('select', row);
  }

  commonModels(val: any) {
    this.$emit('commonModels', val);
  }

  toggleDeleteConfim(item = null) {
    if (!item) {
      return;
    }
    this.deleteConfim = !this.deleteConfim;
    this.deleteItem = item;
  }

  async deleteDictionary() {
    if (!this.deleteItem || !this.deleteItem.id) {
      return;
    }
    const dictionaries = [get(this.deleteItem, 'id')];
    try {
      const { data: result } = await unlinkService({
        id: get(this.card, 'id'),
        dictionaries,
        modified: get(this.card, 'modified'),
      } as any);
      const card = cloneDeep(
        this.$store.getters['registryService/services/servicesCard']
      );
      card.dictionaries = this.card.dictionaries.filter(
        (i: any) => i.id !== this.deleteItem.id
      );
      this.card.modified = result?.modified;
      // todo logically - unlinkDictionary here
      await dictionaryApi.deleteDictionary(dictionaries);
      await this.$store.dispatch(
        'registryService/services/setCardForJson',
        card
      );
    } catch (e) {
      if (e instanceof Error) {
        notifyError(e.message);
      }
    } finally {
      this.toggleDeleteConfim();
    }
  }
}
</script>

<style scoped></style>

<i18n>
{
  "en": {
    "type": "Type",
    "code": "Code",
    "goal": "Goal",
    "DirectoriesTitle": "Directories",
    "tableRejectSeviceTitle": "Reject Sevice",
    "tableRejectDocTitle": "eject Document",
    "name": "Name",
    "noProcessesResult": "No Processes directories",
    "confirmationMessage": "Are you sure you want to delete the directory?",
    "rejectDirectoriesTitle": "Reject directories",
    "createReject": "New reject",
    "documentChoose": "Choose directory",
    "upload": "Upload",
    "uploadTooltip": "Upload new dictionary from csv-file",
    "selectDictionary": "Select a dictionary",
    "serviceHasNoDictionaries": "Service has no dictionaries",
    "action": "Action"
  },
  "ru": {
    "type": "Тип",
    "code": "Код",
    "goal": "Цели",
    "DirectoriesTitle": "Справочники",
    "tableRejectSeviceTitle": "Отказы в предоставлении услуги",
    "tableRejectDocTitle": "Отказы в приеме документов",
    "name": "Наименование",
    "noProcessesResult": "Справочники не найдены",
    "create": "Создать",
    "confirmationMessage": "Вы уверены, что хотите удалить справочник?",
    "rejectDirectoriesTitle": "Справочники отказов",
    "createReject": "Новый отказ",
    "documentChoose": "Выбрать",
    "upload": "Загрузить",
    "uploadTooltip": "Загрузка нового справочника из csv-файла",
    "selectDictionary": "Выберите словарь",
    "serviceHasNoDictionaries": "Услуга не содержит ни одного словаря",
    "action": "Действие"
  }
}
</i18n>
