<template>
  <div>
    <div v-if="isActualServiceVisible">
      <q-list class="q-mb-lg q-gutter-y-md">
        <q-item-label class="q-pa-none q-mb-md-lg" header>{{
          $t('base.selectedServices')
        }}</q-item-label>
        <q-item
          v-for="service in actualServices"
          :key="actualServices.id"
          class="q-pa-none"
        >
          <q-item-section top>
            <q-item-label lines="1">
              <span>{{ service.fullName }}</span>
            </q-item-label>
          </q-item-section>
          <q-item-section top side>
            <div class="text-grey-8 q-gutter-xs">
              <q-btn
                class="gt-xs"
                size="12px"
                flat
                dense
                round
                icon="delete"
                color="negative"
                @click="deleteActualService(service.id)"
              />
            </div>
          </q-item-section>
        </q-item>
      </q-list>
    </div>
    <q-form @submit="submit">
      <div class="q-gutter-y-md">
        <div class="q-mt-sm col">
          <q-select
            v-model="service"
            :options="organizationServices"
            option-label="fullName"
            emit-value
            map-options
            @input="addServices"
            :disable="isServiceSelectDisable"
            filled
            :label="$t('base.addServices')"
          />
        </div>
        <div>
          <q-btn
            color="primary"
            :label="$t('base.send')"
            type="submit"
            class="q-mt-sm"
          />
        </div>
      </div>
    </q-form>
  </div>
</template>

<script lang="ts">
import { Component, Prop } from 'vue-property-decorator';
import Vue from 'vue';
import { Service } from '@openapi/registry-service';

@Component({})
export default class SelectServicesForOrg extends Vue {
  @Prop() inputData: any;

  private actualServices: Service[] = [];
  private service: Service | null = null;

  get organizationServices() {
    return this.inputData.organizationServices?.filter(
      (orgService: Service) =>
        !this.actualServices.some(
          (actService: Service) => actService?.id === orgService.id
        )
    );
  }

  get servicesIds() {
    return this.actualServices.map((item: any) => item.id);
  }

  get isActualServiceVisible() {
    return this.actualServices?.length;
  }

  get isServiceSelectDisable() {
    return !this.organizationServices?.length;
  }

  private addServices(selected: Service): void {
    this.actualServices.push(selected);
    this.service = null;
  }

  private deleteActualService(id: string): void {
    this.actualServices = this.actualServices.filter(
      (item: any) => item.id !== id
    );
  }

  private submit(e: any): void {
    this.$emit('submit', e, { serviceIds: this.servicesIds, transExit: false });
  }

  created() {
    this.actualServices = this.inputData.departmentServices || [];
  }
}
</script>
