<template>
  <widget-wrapper v-bind="$props" ref="widget">
    <q-select
      filled
      :option-value="optionValue"
      map-options
      :option-label="optionLabel"
      v-model="emergency"
      class="q-mt-md"
      :label="label"
      :options="options"
      :loading="loading"
      :disable="!organizationSelected"
    />
  </widget-wrapper>
</template>

<script lang="ts">
import { Component, Watch, Mixins } from 'vue-property-decorator';
import { DictionaryDocument, Dictionary } from '@openapi/registry-service';
import {
  FormWidget,
  ValidatedField,
  WidgetWrapper,
} from '@devsun/form-generator/dist';
import axios from 'axios';

const noEmergenciesErrorMessage = 'Не нашёл ЧС.';

@Component({
  inheritAttrs: false,
  components: { WidgetWrapper },
})
export default class EmergencyDict extends Mixins(
  ValidatedField,
  FormWidget
) {
  protected options: Array<DictionaryDocument> = [];
  protected loading = true;
  protected emergency = null;
  protected organizationSelected = false;
  protected optionLabel = 'Наименование чрезвычайной ситуации';
  protected optionValue = 'id';

  get label(): string {
    return this.fieldNode?.rawAttrs?.label || '';
  }

  @Watch('emergency')
  async onEmergencyChange(newValue: object) {
    this.$refs.widget.inputEvents?.input(newValue);
  }

  @Watch('$store.state.formGenerator.data.organization')
  async onRegionChange() {
    this.filterCurrentOrganizationEmergencies()
  }

  protected async created() {
    this.filterCurrentOrganizationEmergencies()
  }

  async getEmergencies(): Promise<Dictionary> {
    try {
      const { data } = await axios.get('/service/nsi-registry/mchs?perPage=1000');
      if (!data?.records.length) {
        this.loading = false;
        throw Error(noEmergenciesErrorMessage);
      }
      return data.records;
    } catch (e) {
      this.loading = false;
      throw Error(noEmergenciesErrorMessage);
    }
  }

  protected async filterCurrentOrganizationEmergencies() {
    const organization = this.$store.getters['formGenerator/data']?.organization;
    if (!organization) {
      this.organizationSelected = false;
      this.loading = false;
      return;
    }
    this.organizationSelected = true;

    const emergencies = await this.getEmergencies();

    this.options = emergencies.filter((doc: DictionaryDocument) =>
      doc.OKATO === organization.okato
    );

    this.loading = false;
    this.emergency = null;
  }
}
</script>
