<template>
  <div v-if="isActive">
    <q-card class="no-shadow q-pb-md q-gutter-y-md q-mx-md">
      <OrganisationsServicesTable :value="services" :loading="loading" />
      <q-btn
        @click="editListOfServices"
        :loading="editListOfServicesLoading"
        class="q-ml-lg q-mt-none"
        color="primary"
      >
        {{ $t('base.edit') }}
      </q-btn>
    </q-card>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Mixins, Watch } from 'vue-property-decorator';
import OrganisationsServicesTable from './Services/Table.vue';
import { BaseCardCommon } from '@/interfaces';
import Loadable from '@mixins/Loadable';
import { Service, DepartmentApi } from '@openapi/registry-service';
import get from 'lodash/get';
import { AxiosResponse } from 'axios';

const departmentApi = new DepartmentApi();

@Component({
  components: {
    OrganisationsServicesTable,
  },
})
export default class DepartmentCardServices extends Mixins(Loadable) {
  @Prop() common: BaseCardCommon;
  @Prop() model: any;
  loading = false;
  private editListOfServicesLoading = false;
  private services: Service[] = [];
  private departmentId = '';

  private get isActive(): boolean {
    return this.common.active === 'services';
  }

  async editListOfServices(): Promise<void> {
    this.editListOfServicesLoading = true;
    const { traceId } = await this.$store.dispatch(
      'wf/processes/dispatchProcess',
      {
        processKey: 'EditDepartmentServicesProcess',
        data: {
          departmentId: get(this.model, 'id'),
        },
      }
    );
    if (traceId) {
      const handler = (e: any) => {
        const data = JSON.parse(get(e, 'data', '{}'));
        if (data.traceId === traceId) {
          this.loading = false;
          this.$websockets.removeListener(handler);
        }
      };
      this.$websockets.addListener(handler);
    }
  }

  private async fetchData(): Promise<void> {
    const { data: department } = await this.withLoading<AxiosResponse>(() =>
      departmentApi.getDepartment(this.departmentId, 'services')
    );
    this.services = department.services;
  }

  @Watch('model', {
    immediate: true,
  })
  async modelWatcher(model: any) {
    this.departmentId = model?.id ?? '';
    await this.fetchData();
  }
}
</script>
