<template>
  <div>
    <select-base
      :options="options"
      :loading="loading"
      use-input="10"
      v-bind="$attrs"
      option-value="id"
      option-label="fullname"
      v-on="$listeners"
      :multiple="false"
      :disable="allRegions && isSpecialReport"
    />
    <q-checkbox
      class="allRegions"
      v-if="reducedServices && isSpecialReport"
      v-model="allRegions"
      label="Все субъекты"
    />
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import SelectBase from './select-base.vue';
import sortBy from 'lodash/sortBy';
import { RegionApi, Region } from '@openapi/idm';
import { notifyError } from '@utils/notify';

const regionApi = new RegionApi();

@Component({
  inheritAttrs: false,
  components: { SelectBase },
})
export default class SelectRegions extends Vue {
  @Prop() reducedServices?: boolean;
  @Prop() isSpecialReport?: boolean;
  protected allRegions = false;
  protected options = [] as Region[];
  protected loading = true;

  protected async created(): Promise<void> {
    this.options = await (regionApi
      .searchRegions()
      .then(({ data }) => data)
      .catch((e) => {
        notifyError(e.message.toString());

        return [];
      }) as unknown) as Region[];
    this.options = sortBy(this.options, (el: { fullname?: string }) =>
      el.fullname?.toLowerCase().trim()
    );
    this.loading = false;
  }

  @Watch('allRegions')
  setAllRegions(value: boolean): void {
    this.$emit('allRegions', value);
  }

  @Watch('isSpecialReport')
  resetAllRegions(value: boolean): void {
    if (!value) {
      this.allRegions = false;
    }
  }
}
</script>
<style lang="sass">
.allRegions.row.inline
  display: flex
</style>
