<template>
  <select-base
    :options="options"
    :loading="loading"
    :disable="disable || disabled"
    v-bind="$attrs"
    use-input="10"
    option-value="id"
    option-label="fullname"
    v-on="$listeners"
  />
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { DomainApi, DomainForStats } from '@openapi/idm';
import { Document } from '@openapi/registry-service';
import map from 'lodash/map';
import SelectBase from './select-base.vue';
import { USER_SCOPES } from '@/constants/entities/Scope';
import sortBy from 'lodash/sortBy';
import { notifyError } from '@utils/notify';

const domainApi = new DomainApi();

@Component({
  inheritAttrs: false,
  components: {
    SelectBase,
  },
})
export default class SelectOrganizations extends Vue {
  @Prop({ required: true }) regions: string[];
  @Prop({ type: Boolean }) disable: boolean;

  protected options: DomainForStats[] | [] = [];
  protected loading = false;
  protected disabled = true;

  protected last = 0;

  @Watch('regions', { immediate: true, deep: true })
  protected async regionsUpdate(regions: any[] | 'all'): Promise<void> {
    if (!regions?.length) {
      this.$emit('input', []);
    }

    if (regions !== 'all') {
      if (!regions || !regions.length) {
        this.options = [];
        this.disabled = true;

        return;
      }
      if (typeof regions[0] !== 'string') {
        regions = map(regions, 'id');
      }
    }

    this.disabled = false;
    this.loading = true;
    const last = ++this.last;

    let organizations = regions !== 'all' 
      ? await (
        domainApi.pagingDomainsForStats(regions)
          .then((res) => {
            const organizations = res.data as unknown as DomainForStats[];
            return organizations.flatMap(org => org.organizations).filter(el => el)
          })
        ).catch((e) => {
          notifyError(e.message.toString());
          return [];
        })
      : [];

    organizations = organizations && sortBy(organizations, (el: any) => el.fullname?.toLowerCase().trim());

    if (this.last === last) {
      organizations && organizations.length && (this.options = organizations as DomainForStats[]);
      if (organizations && !organizations.length) {
        this.disabled = true;
      }
    }
    this.loading = false;
  }
}
</script>
