<template>
  <q-form @submit="submit">
    <div class="row q-gutter-y-md">
      <q-input
        class="col-12"
        v-model="title"
        filled
        :label="$t('notifications.name') + ' *'"
        :rules="[rules.required]"
        required
      />
      <BaseAutocompleteSelect
        :model.sync="regionInput"
        :async-getter="getRegions"
        :optional-search="true"
        label-value="fullname"
        :field-label="$t('notifications.region')"
        :rules="[rules.required]"
        :is-multiple="true"
        class="col-12"
        @value="inputRegion"
      />
      <q-select
        v-model="eventId"
        option-label="description"
        option-value="id"
        :options="events"
        class="col-12"
        emit-value
        map-options
        required
        :label="$t('notifications.event') + ' *'"
        :rules="[rules.required]"
        filled
      />
      <q-btn color="primary" :label="$t('notifications.send')" type="submit" />
    </div>
  </q-form>
</template>

<script lang="ts">
import { Component, Prop, Watch } from 'vue-property-decorator';
import InputData from '@/types/wf/InputData';
import Vue from 'vue';
import { Event, EventsApi } from '@openapi/notifier-registry';
import get from 'lodash/get';
import { notifyError } from '@utils/notify';
import { Region, RegionApi, DomainApi } from '@openapi/idm';
import { USER_SCOPES } from '@/constants/entities/Scope';
import { Domain } from 'domain';

const eventsApi = new EventsApi();
const regionApi = new RegionApi();
const domainApi = new DomainApi();

class InputDataProp implements InputData {
  processName = '';
  userTaskId = '';
  events: Array<{
    id: string;
    name: string;
    description: string;
    type: {
      name: string;
    };
    group: string;
    trigger: {
      subject: string;
      conditions: {
        condition: {
          attribute: string;
          equality: string;
          value: string;
        };
      };
    };
  }> = [];
}

@Component({})
export default class NotificationSetupForms extends Vue {
  @Prop() readonly inputData: InputDataProp;
  @Prop() readonly readonly: boolean;
  USER_SCOPES = USER_SCOPES;

  private events: Array<Event> = [];

  private title = '';

  private eventId = '';

  private domains: Array<string> = [];

  regionInput = {
    nextPage: 1,
    pageSize: 20,
    search: '',
    records: [],
    selected: null,
    loading: false,
  };

  private selectedDomains: Array<Region> = [];

  private rules = {
    required: (val: any) => (!!val && val.length) || 'Обязательное поле',
  };

  private get outputData() {
    return {
      title: this.title,
      eventId: this.eventId,
      domainsToAttach: this.domains,
      domainsToDetach: this.domainsToDetach,
    };
  }

  private get domainsToDetach() {
    return this.selectedDomains
      .map((i) => i.id)
      .filter((domain) => !this.domains.find((i) => i === domain));
  }

  private async getRegions() {
    try {
      this.regionInput.loading = true;
      if (this.$AC.haveScope(USER_SCOPES.CLOUD_ADMIN)) {
        const fulltextString = this.regionInput.search
          ? `(fullname=searchprefix="${this.regionInput.search}" or fullname=search="${this.regionInput.search}") or (code=searchprefix="${this.regionInput.search}" or code=search="${this.regionInput.search}")`
          : '';
        const { data: response } = await regionApi.pagingRegions(
          undefined,
          this.regionInput.nextPage,
          this.regionInput.pageSize,
          undefined,
          fulltextString
        );
        return response.records;
      } else if (this.$AC.haveScope(USER_SCOPES.REGION_ADMIN)) {
        const currentUser = this.$store.getters['oidcClient/currentUser'];
        if (currentUser.hasOwnProperty('domain_id')) {
          const { data: response } = await regionApi.getRegion(currentUser.domain_id);
          return [response];
        }
      } else {
        const currentUser = this.$store.getters['oidcClient/currentUser'];
        if (currentUser.hasOwnProperty('domain_id')) {
          const { data: domainData } = await domainApi.getDomain(
            currentUser.domain_id
          );
          const currentRegionId = get(domainData, 'regionId', '');
          if (!currentRegionId) return '';
          const { data: response } = await regionApi.getRegion(currentRegionId);
          return [response];
        }
      }
    } catch (e) {
      notifyError(e.toString());
    } finally {
      this.regionInput.loading = false;
    }
  }

  inputRegion(regions: Region[] = []) {
    this.domains = regions.map((region) => region.id);
  }

  private submit(e: Event): void {
    this.$emit('submit', e, this.outputData);
  }

  @Watch('inputData', { immediate: true })
  private async inputDataUpdate(val: InputDataProp) {
    if (!val) return;
    const events = await eventsApi.searchEvents();
    this.events = events?.data ?? [];
    this.title = get(val, 'title', '');
    this.domains = get(val, 'domains', []);
    this.selectedDomains = get(val, 'domains', []);
    this.eventId = get(val, 'eventId', '');
  }
}
</script>
