<template>
  <div>
    <div v-if="actualServiceLength">
      <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-item-label class="q-pa-none q-mb-md-lg" header>{{
            $t('base.addServices')
          }}</q-item-label>
          <BaseAutocompleteSelect
            :model.sync="services"
            :async-getter="getService"
            :is-multiple="true"
            field-label="Наименование услуги"
            label-value="shortName"
            @value="handleServicesValues"
            class="q-mt-lg"
          />
        </div>
        <div>
          <q-btn
            color="primary"
            :label="$t('base.add')"
            class="q-mt-sm q-mr-md"
            @click="addServices"
            :disabled="!services.selected.length"
          />
          <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 { ServiceApi } from '@openapi/registry-service';
import { notifyError } from '@utils/notify';

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

  private actualServices = [];

  private services = {
    search: '',
    records: [],
    selected: [],
    loading: false,
  };

  private filter: any = {
    search: '',
    services: '',
    visible: false,
  };

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

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

  private addServices() {
    this.actualServices = [...this.actualServices, ...this.services.selected];
    this.services.selected = [];
  }

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

  private async getService() {
    try {
      this.services.loading = true;
      const fulltextString = this.services.search
        ? `(shortName=searchprefix="${this.services.search}" or shortName=search="${this.services.search}") or (fullName=searchprefix="${this.services.search}" or fullName=search="${this.services.search}")`
        : '';
      const records = await new ServiceApi().searchService('', fulltextString);
      return records.data;
    } catch (e) {
      notifyError(e.message.toString());
    } finally {
      this.services.loading = false;
    }
  }

  private handleServicesValues(val: any): void {
    if (val) {
      this.filter.services = val.id || '';
    } else {
      this.filter.services = '';
    }

    const services = this.filter.services || undefined;

    this.$router.push({ query: { ...this.$route.query, services } });
    this.startSearch();
  }

  private startSearch(): void {
    const query: string[] = [];
    const services = this.filter;
    if (services?.length) {
      query.push(`system.serviceId==${services}`);
    }
  }

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

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

<style lang="scss"></style>
