<template>
  <q-card class="q-pa-md w-100">
    <BaseTable
      :title="$t('interagencies.selectInteragenciesForExport')"
      row-key="id"
      selection="multiple"
      :data="data"
      :columns="columns"
      :loading="loading"
      :pagination.sync="pagination"
      :selected="selected"
      :hide-refresh="true"
      :use-search="true"
      @update:selected="onSelected"
      @requestTable="getInteragencies"
      @update="getInteragencies"
      v-model="searchText"
    >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th auto-width />
        <q-th
          v-for="col in props.cols"
          :key="col.name"
          :props="props"
        >
          {{ col.label }}
        </q-th>
      </q-tr>
    </template>

    <template v-slot:body-item-children="props">
        <div v-if="props.row.childrenInteragency">
          <div v-for="child in props.row.childrenInteragency">
            <q-checkbox
              :disable="!selected.some(parentMz => parentMz.id === props.row.id)"
              v-model="selectedChildren[child.id]"
              @input="(v) => onSelectChild(v, child)"
            />
            {{ child.class }}
          </div>
        </div>
    </template>

  </BaseTable>
    <q-card-actions align="right">
      <q-btn
        :disable="!selected.length"
        color="primary"
        @click="onExport"
      >
        {{ $t('interagencies.export') }}
      </q-btn> 
      <q-btn
        :label="$t('base.close')"
        @click="$emit('close')"
      />
    </q-card-actions>
  </q-card>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import { TablePagination } from '@/models/base/TablePagination';
import { Interagency, InteragencyApi } from '@openapi/registry-service';
import { generateParentInteragencySearchQuery } from '../utils';
import { notifyError } from '@/utils/notify';

const interagencyApi = new InteragencyApi();
  
const sortByDefault = 'modified';

interface ParentInteragency extends Interagency {
  childrenInteragency?: Interagency[],
}

@Component
export default class ExportCard extends Vue {
  columns = [
    {
      name: 'clazz',
      label: 'Родительский класс',
      field: 'clazz',
      align: 'left',
      sortable: true,
    },
    {
      name: 'children',
      label: 'Дочерние',
      field: '',
      align: 'left',
    },
  ];
  loading = false;
  pagination = new TablePagination();
  searchText = '';
  data: ParentInteragency[] = [];
  selected: ParentInteragency[] = [];
  selectedChildrenList: ParentInteragency[] = [];
  selectedChildren: any = {};

  @Watch('searchText')
  onInputSearchText() {
    this.getInteragencies();
  }

  onSelectChild(v: boolean, child: ParentInteragency) {
    if (v) {
      this.selectedChildrenList.push(child);
    } else {
      const idx = this.selectedChildrenList.findIndex(s => s.id === child.id);
      this.selectedChildrenList.splice(idx, 1);
    }
  }

  async created() {
    await this.getInteragencies();
  }

  async getInteragencies(val: any = null) {
    if (val?.pagination) {
      this.pagination.descending = val.pagination.descending;
      this.pagination.page = val.pagination.page;
      this.pagination.rowsPerPage = val.pagination.rowsPerPage;
      this.pagination.sortBy =
        val.pagination.sortBy === null
          ? sortByDefault
          : val.pagination.sortBy;
    }
    if (!this.pagination.sortBy) {
      this.pagination.sortBy = sortByDefault;
    }

    this.loading = true;
    const response = await interagencyApi
      .pagingInteragency(
        this.pagination.page,
        this.pagination.rowsPerPage,
        generateParentInteragencySearchQuery(
          ['clazz'],
          this.searchText,
        ),
        '',
        `${this.pagination.descending ? '-' : '+'}${this.pagination.sortBy}`,
        'childrenInteragency'
      )
      .catch((e) => {
        if (e instanceof Error) {
          notifyError(e.message);
        }
      })
      .finally(() => (this.loading = false));
    if (!response || !response.data) {
      return;
    }
    this.data = response.data.records!;
    this.pagination.rowsNumber = response.data.totalRows!;
  }

  onSelected(newSelected: Interagency[]) {
    this.removeSelectedChildren(newSelected);

    this.selected = newSelected;
  }

  removeSelectedChildren(newSelected: Interagency[]) {
    if (newSelected.length < this.selected.length) {
      const removedItem = this.selected.find(i => !newSelected.some(ni => ni.id === i.id))
      if (removedItem?.childrenInteragency?.length) {
        removedItem.childrenInteragency.forEach(child => {
          if (this.selectedChildren[child.id]) {
            this.selectedChildren[child.id] = false;
            const idx = this.selectedChildrenList.findIndex(i => i.id === child.id);
            if (idx >= 0) {
              this.selectedChildrenList.splice(idx, 1);
            }
          }
        })
      }
    }
  }

  async onExport() {
    const data = this.selected.map(p => ({
      parentId: p.id,
      childIds: p.childrenInteragency?.filter(ch => 
        this.selectedChildrenList.some(sch => sch.id === ch.id)
      ).map(ch => ch.id)
    }))

    await this.$store.dispatch('wf/processes/dispatchProcess', {
      processKey: 'BaseExportMZToNexus',
      data: {
        MzList: data,
      },
    });

    this.$emit('close');
  }
}
</script>

<style scoped>
.w-100 {
  max-width: 100vw;
}
</style>