<template>
  <div v-if="common.active === 'connections'" class="q-pb-md">
    <q-card class="no-shadow q-mx-md q-pa-md no-border-radius">
      <q-expansion-item
        v-for="registry in linkedRegistries"
        :key="registry.code"
        expand-separator
        :label="registry.name"
      >
        <q-card>
          <q-card-section>
            <RegistryObjectConnectionTable
              :registry="registry"
              :selected="formModel.linkedRegistriesObjects"
              @update="updateSelected"
            />
          </q-card-section>
        </q-card>
      </q-expansion-item>
    </q-card>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import RegistryObjectConnectionTable from '@components/registries/registry-object/RegistryObjectConnectionTable.vue';
import { RegistryApi } from '@openapi/registry-service';
import isEqual from 'lodash/isEqual';

const registryApi = new RegistryApi();

export default {
  name: 'RegistryConnections',
  components: {
    RegistryObjectConnectionTable,
  },
  props: ['model', 'common'],
  data() {
    return {
      formModel: {},
      loaded: false,
      isFetchRegistries: false,
      registryCode: this.$route.query.reg,
      registryId: this.$route.query.regid,
      linkedRegistries: [],
    };
  },
  computed: {
    registry() {
      const models = this.$store.getters[`utils/cards/models`] || {};
      return models[this.registryCode];
    },
  },
  watch: {
    model(model) {
      if (!isEqual(model, this.formModel)) {
        this.formModel = { ...model };
        this.formModel.linkedRegistriesObjects =
          this.formModel.linkedRegistriesObjects || [];
        this.$nextTick(() => {
          this.loaded = true;
        });
      }
    },
    registry() {
      if (this.linkedRegistries.length === 0 && !this.isFetchRegistries) {
        this.fetchRegistriesData();
      }
    },
  },
  async created() {
    await this.$store.dispatch(
      'registryService/referenceBooks/initReferenceBooks',
      [
        {
          force: true,
          id: 'gpzu_2_application_status',
        },
      ]
    );
  },
  methods: {
    updateSelected(selected) {
      if (!this.loaded) {
        return;
      }

      this.formModel.linkedRegistriesObjects = selected.map((el) =>
        this.removeUnnecessaryLinkFields(el)
      );

      this.$store.commit(`utils/cards/addModel`, {
        model: this.formModel,
        path: 'registry-object',
      });
    },
    async fetchRegistriesData() {
      this.isFetchRegistries = true;
      this.linkedRegistries = [];
      const list = this.registry?.linkedRegistries ?? [];
      for (const id of list) {
        const { data: registry } = await registryApi.getRegistry(id);
        this.linkedRegistries.push(registry);
      }
      this.isFetchRegistries = false;
    },
    removeUnnecessaryLinkFields(link) {
      const { id, finishDate } = link;
      return { id, finishDate };
    },
  },
};
</script>
