import { Component, Watch, Mixins, Prop } from 'vue-property-decorator';
import {
  FormWidget,
  ValidatedField,
  WidgetWrapper,
} from '@devsun/form-generator/dist';
import { QSelectOption } from '@/models/models-ui';
import { Organization } from '@/interfaces/entities/Organization';
import { OrganizationApi } from '@/openapi/registry-service';
import SelectBase from '@components/common/select-base.vue';

const organizationApi = new OrganizationApi();

const CURRENT_USER_REGION = 'currentUserRegion';
const NAME_FIELD = 'fullname';

@Component({
  components: {
    WidgetWrapper,
    SelectBase,
  },
})
export default class OrganizationDict extends Mixins(
  ValidatedField,
  FormWidget
) {
  @Prop() filterBy: string[];
  
  organizations: Organization[] | null = null;
  organizationId = '';
  loading = false;

  $refs!: {
    widget: WidgetWrapper;
  };

  async mounted() {
    this.init();
  }

  async init() {
    this.loading = true;
    try {
      await this.setOrganizations();
      // const currentValue = this?.value?.__id;
      // if (!currentValue) {
      await this.setUserOrganization();
      // } else {
        // this.organizationId = currentValue;
      // }
    } catch (e) {
      console.error(e)
    } finally {
      this.loading = false;
    }
  }

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

  get organizationOptions(): QSelectOption[] {
    if (!this.organizations) {
      return [];
    }

    return this.organizations.map((org) => ({
      label: org[NAME_FIELD],
      value: org.tnsDepartmentId,
      data: org,
    }));
  }

  get currentUser() {
    return this.$store.getters['oidcClient/currentUser'];
  }

  @Watch('organizationId')
  onDictModelChange(newValue: string) {
    this.$refs.widget.inputEvents?.input(newValue);
    this.saveRegionId(newValue);
  }

  get serviceId() {
    return this.$store.getters['formGenerator/data']?.id || this.$route.query.serviceId;
  }

  @Watch('serviceId')
  onServiceChange() {
    this.init();
  }

  async setOrganizations(): Promise<void> {
    const serviceId = this.$store.getters['formGenerator/data']?.id || this.$route.query.serviceId;
    const {
      data: organizations,
    } = await organizationApi.filterOrganizationsByServiceId(serviceId);
    this.organizations = organizations.filter(
      (org: Organization) => org.tnsDepartmentId
    );
    
    if (this.filterBy?.includes(CURRENT_USER_REGION)) {
      this.filterByCurrentUserRegion();
    }

    this.sortAlphabetically();
  }

  async filterByCurrentUserRegion() {
    const { regionId: currentUserRegionId } = await this.$store.dispatch(
      'idm/organizations/getOrganization',
      { id: this.currentUser.domain_id },
    )
    const byRegion = (org: any) => org.regionId === currentUserRegionId;
    this.organizations = this.organizations?.filter(byRegion);
  }

  async setUserOrganization() {
    const organization = await this.$store.dispatch(
      'idm/organizations/getOrganization',
      { id: this.currentUser.domain_id }
    );
    this.organizationId = organization.tnsDepartmentId;
  }

  sortAlphabetically() {
    this.organizations = this.organizations.sort((a, b) => {
      const nameA = a[NAME_FIELD].toLowerCase(), nameB = b[NAME_FIELD].toLowerCase();
      if (nameA < nameB)
        return -1;
      if (nameA > nameB)
        return 1;
      return 0;
    });
  }

  saveRegionId(tnsDepartmentId) {
    const organization = this.organizations.find((org: Organization) => org.tnsDepartmentId === tnsDepartmentId);
    this.$store.commit('formGenerator/data', { organization });
  }
}
