<i18n>
{
  "en": {
    "emptyList": "Not selected",
    "services": "Services"
  },
  "ru": {
    "emptyList": "Не выбраны",
    "services": "Услуги"
  }
}
</i18n>

<template>
  <div class="q-pb-md">
    <q-card v-if="model && !loading" class="no-shadow q-mx-md q-pa-lg">
      <div v-if='visibleRegion'>
        <p>{{ $t('mAddress.subject') }}:</p>
        <ul class="text-primary">
          <li v-for="region in regions" :key="region.id">
            {{ region.name || region.shortname }}
          </li>
        </ul>
        <p v-if="regions.length === 0" class="q-pb-none q-ml-md text-primary">
          {{ $t('emptyList') }}
        </p>
      </div>

      <p>{{ $t('services') }}:</p>
      <ul class="text-primary">
        <li v-for="service in services" :key="service.id">
          {{ service.fullName || service.shortName }}
        </li>
      </ul>
      <p v-if="services.length === 0" class="q-pb-none q-ml-md text-primary">
        {{ $t('emptyList') }}
      </p>
      <q-btn
        class="q-mt-lg"
        :label="$t('base.edit')"
        unelevated
        color="primary"
        text-color="white"
        @click="editVisibility"
      />
    </q-card>
    <q-inner-loading :showing="loading">
      <q-spinner-gears color="primary" size="50px" />
    </q-inner-loading>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { BaseCardCommon } from '@/interfaces';
import { CollapsedProfileApi, Region, RegionApi } from '@openapi/idm';
import { Account } from '@interfaces/entities/Account';
import { Service, ServiceApi } from '@openapi/registry-service';
import get from 'lodash/get';

const collapsedProfileApi = new CollapsedProfileApi();

@Component({})
export default class AccountAccessCard extends Vue {
  @Prop({}) private common: BaseCardCommon;
  @Prop({}) private model: Account;

  regions: Region[] = [];
  services: Service[] = [];
  regionIds: string[] = [];
  serviceIds: string[] = [];
  loading = false;

  @Watch('model', {
    immediate: true,
  })
  modelWatcher(account: Account): void {
    if (account) this.init();
  }

  private get visibleRegion() {
    return this.model.roles.some(role => role.name === 'fedStatObserver' || role.name === 'RFObserverScope')
  }

  async init(): Promise<void> {
    try {
      this.loading = true;
      await this.fetchIds();
      await Promise.allSettled([this.fetchRegions(), this.fetchServices()]);
    } finally {
      this.loading = false;
    }
  }

  async fetchIds(): Promise<void> {
    const { data } = await collapsedProfileApi.getCollapsedProfileByAccountId(
      this.common?.id || ''
    );
    this.regionIds = data?.sectionFilters?.regions || [];
    this.serviceIds = data?.sectionFilters?.services || [];
  }

  async fetchRegions(): Promise<void> {
    const idList: string[] = this.regionIds || [];
    const requests = idList.map(
      async (id) => await new RegionApi().getRegion(id)
    );

    this.regions = await Promise.all(requests).then((regions) =>
      regions.map((r) => r.data)
    );
  }

  async fetchServices(): Promise<void> {
    const idList: string[] = this.serviceIds || [];
    const requests = idList.map(
      async (id) => await new ServiceApi().getService(id)
    );
    this.services = await Promise.all(requests).then((services) =>
      services.map((s) => s.data)
    );
  }

  async editVisibility(): Promise<void> {
    this.loading = true;

    this.$store.dispatch('wf/processes/dispatchProcess', {
      processKey: 'setVisibilityProcess',
      data: {
        accountId: this.common.id,
        organizationId: get(this.model, 'user-domain.id'),
      },
    });
    setTimeout(() => (this.loading = false), 3000);
  }
}
</script>
