<template>
  <div class="bg-white q-pa-md rounded-borders q-col-gutter-y-sm">
    <div class="row justify-between items-center">
      <div>
        <span class="text-h5">
          {{ $t('interagencies.childInteragencies') }}
        </span>
      </div>

      <div class="q-gutter-x-sm">
        <q-btn
          @click="syncChildren"
          icon="sync"
          unelevated
          :loading="isSyncing"
          :label="$t('interagencies.syncChildrenBtn')"
          color="primary"
        />
        <q-btn
          @click="() => (isCreateModalOpen = true)"
          icon="add"
          unelevated
          :label="$t('interagencies.createNewChildInteragency')"
          color="primary"
        />
        <q-btn
          @click="() => (isSelectModalOpen = true)"
          unelevated
          :label="$t('interagencies.selectChildRequest') + '...'"
          color="primary"
        />
      </div>
    </div>

    <div>
      <base-table
        :columns="columns"
        :data="childList"
        :pagination.sync="pagination"
        :hide-refresh="true"
        :use-search="true"
        v-model="pagination.search"
      />
    </div>

    <q-dialog class="full-width" v-model="isCreateModalOpen">
      <CreateChildInteragency
        @close="isCreateModalOpen = false"
      />
    </q-dialog>
    <q-dialog class="full-width" v-model="isSelectModalOpen">
      <SelectFreeChildInteragency
        :loading="isAddingSelected"
        @close="isSelectModalOpen = false"
        @submit="onSelectChildInteragenciesClick"
      />
    </q-dialog>
  </div>
</template>

<script lang="ts">
import QColumn from '@/types/QColumn';
import { pushRoute } from '@/utils/routes';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import CreateChildInteragency from './create-child-interagency/index.vue';
import SelectFreeChildInteragency from './select-free-child-interagency.vue';
import { Tab } from '../../utils';
import { InteragencyApi } from '@/openapi/registry-service';
import { notifyError, notifySuccess } from '@/utils/notify';
import cloneDeep from 'lodash/cloneDeep';

const interagencyApi = new InteragencyApi();

@Component({
  components: {
    CreateChildInteragency,
    SelectFreeChildInteragency,
  },
})
export default class ChildInteragencyTable extends Vue {
  @Prop() data: any;

  isCreateModalOpen = false;
  isSelectModalOpen = false;
  isAddingSelected = false;
  isSyncing = false;
  childList = [];
  columns: QColumn[] = [
    {
      name: 'id',
      label: this.$t('base.table.id'),
      field: (val: any) => val,
      formatField: 'id',
      align: 'left',
      handler: (id: string, opts?: any) => {
        const parentId = this.$route.params.id;
        pushRoute(
          this.$router,
          {
            name: 'child-interagency-page',
            params: {
              parentId,
              id,
            },
            query: {
              tab: Tab.Request
            }
          },
          opts?.targetBlank
        );
      },
      handlerField: 'id',
    },
    {
      name: 'class',
      label: this.$t('base.table.class'),
      field: 'class',
      align: 'left',
    },
    {
      name: 'requestName',
      label: this.$t('base.table.title'),
      field: 'requestName',
      align: 'left',
    },
    {
      name: 'description',
      label: this.$t('base.table.description'),
      field: 'description',
      align: 'left',
    },
  ];
  pagination = {
    rowsPerPage: 1,
    sortBy: 'modified',
    rowsNumber: 0,
    page: 1,
    search: '',
  };

  @Watch('data', { immediate: true })
  onDataUpdated() {
    this.updateChildList();
  }

  @Watch('pagination.search')
  onSearch(searchText: string) {
    this.childList = this.data.filter((i: any) => {
      for (const prop in i) {
        const value = i[prop]
        if (typeof value === 'string' && value && value.includes(searchText)) {
          return true;
        }
      }
      return false;
    })
  }

  get parentInteragency() {
    return this.$store.getters[
      'registryService/interagencies/getParentInteragency'
    ];
  }

  updateChildList() {
    this.childList = cloneDeep(this.data);
  }

  onSelectChildInteragenciesClick() { }

  async syncChildren() {
    try {
      const { data } = await interagencyApi.updateParentInteragency(this.parentInteragency.id);
      if (data.success) {
        this.$emit('sync');
        notifySuccess('Список дочерних элементов синхронизирован');
      }
    } catch (e) {
      if (e instanceof Error) {
        notifyError(e.message);
      }
    }
  }
}
</script>
