<template>
  <widget-wrapper v-bind="$props" ref="widget">
    <SelectBase
      v-model="mfc"
      :loading="loading"
      :label="label"
      :options="options"
      :multiple="false"
      :use-input="10"
      :search-by-ogrn="true"
      :disable="!currentOrgOkato"
      filled
      emit-value
      map-options
      class="q-mt-md"
      option-label="title"
    />
  </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';
import SelectBase from '@components/common/select-base.vue';

@Component({
  inheritAttrs: false,
  components: { WidgetWrapper, SelectBase },
})
export default class MfcDict extends Mixins(
  ValidatedField,
  FormWidget
) {
  protected options: Array<DictionaryDocument> = [];
  protected loading = true;
  protected mfc = null;
  protected organizationSelected = false;

  protected dictionaryName = 'MFC_ORG';

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

  get organization() {
    return this.$store.getters['formGenerator/data']?.organization;
  }

  get currentOrgOkato(): string {
    return this.organization?.okato;
  }

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

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

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

  async getValues(): Promise<Dictionary> {
    if (!this.currentOrgOkato) {
      return;
    }

    this.loading = true;
    try {
      const { data } = await axios.get(`/service/nsi-registry/registry/${this.dictionaryName}/records`, {
        params: {
          filter: `regokato==${this.currentOrgOkato}`,
          sort: `+title`
        }
      });
      if (!data?.length) {
        throw Error('Не нашёл МФЦ');
      }
      this.options = data;
    } catch (e) {
      throw Error(e);
    } finally {
      this.loading = false;
      this.mfc = null;
    }
  }
}
</script>
