<template>
  <widget-wrapper v-bind="$props" ref="widget">
    <q-field
      filled
      :label="label"
      stack-label
      class="q-mt-md cursor-pointer"
      :disable="!currentUserRegionId"
    >
        <template v-slot:control>
          <div tabindex="0" class="no-outline full-width">
            {{ selectedOrganizationLabel }}
          </div>
        </template>
        <template v-slot:append>
          <q-icon name="expand_more"></q-icon>
        </template>
        <q-menu fit auto-close>
          <q-tree
            :nodes="leafs"
            :selected.sync="organizationId"
            node-key="id"
            children-key="leafs"
            default-expand-all
          ></q-tree>
        </q-menu>
    </q-field>
  </widget-wrapper>
</template>

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

const graphApi = GraphApiFp();
const labelProperty = 'shortname';

@Component({
  inheritAttrs: false,
  components: { WidgetWrapper },
})
export default class HierarchyDictionarySelect extends Mixins(
  ValidatedField,
  FormWidget
) {
  protected currentUserRegionId = '';
  protected loading = true;
  protected organizationId: string = '';
  protected leafs = [];
  protected leavesPlainObj = {};

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

  get selectedOrganization() {
    return this.leavesPlainObj[this.organizationId];
  }

  get selectedOrganizationLabel() {
    return this.organizationId ? this.selectedOrganization[labelProperty] : '';
  }

  @Watch('organizationId')
  async onEmergencyChange(organizationId: any) {
    this.$refs.widget.inputEvents?.input(organizationId);
  }

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

  protected async getOrganizations() {
    if (this.leafs.length) {
      return;
    }
      
    this.loading = true;

    const currentUser = this.$store.getters['oidcClient/currentUser'];
    if (!!currentUser.ogrn) {
      const organization = await this.$store.dispatch(
        'idm/organizations/getOrganization',
        { id: currentUser.domain_id },
      )
      this.currentUserRegionId = organization.region
    } else {
      this.currentUserRegionId = currentUser.domain_id
    }

    // При использовании данного компонента для улучшения скорости работы запроса его стоит заменить на новый
    // getDomainChildrenTreeV1(this.currentUserRegionId, 1000, ['Organization'])
    const { data } = await (await graphApi.tree('Region', 'incoming', this.currentUserRegionId, 1000, ['Organization']))();
    const cb = (e) => {
      e.id = e.value.id;
      e.label = e.value[labelProperty];
      this.leavesPlainObj[e.id] = e.value;
      if (e.leafs) {
        e.leafs.forEach(cb);
      }
    }
    data.leafs.forEach(cb);
    this.leafs = data.leafs;

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