<template>
  <operation-dialog
    persistent
    sign
    ref="dialog"
    :title="openedAccountFio"
    sub="Список ролей"
    v-model="opened"
    @hide="$emit('close')"
  >
    <q-spinner
      color="primary"
      size="50px"
      :thickness="2"
      v-if="loading"
    ></q-spinner>
    <div v-else-if="accountRoles.length">
      <q-chip v-for="role in accountRoles" :key="role.id">
        {{ role.displayName }}
      </q-chip>
    </div>
    <div v-else>У пользователя нет ролей</div>

    <template #left-actions-panel>
      <r-btn
        outline
        label="Закрыть"
        icon="pgs-close"
        color="primary"
        @click="$emit('close')"
      />
    </template>
  </operation-dialog>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { AccountApi, RoleTO } from '@openapi/idm';
import { AccountSearchRecord } from '../utils/types';

const accountApi = new AccountApi();

@Component({})
export default class RolesModal extends Vue {
  @Prop({ default: null }) openedAccount: AccountSearchRecord | null;

  accountRoles: RoleTO[] = [];
  loading = false;
  opened = false;

  @Watch('openedAccount')
  private async openedAccountHandler(): Promise<void> {
    // openedAccountHandler приходит null - значит надо закрыть окно
    this.opened = false;
    this.accountRoles = [];
    if (!this.openedAccount?.accountId) return;

    if (this.openedAccount.roles?.length) {
      this.accountRoles =
        this.openedAccount.roles.filter((Role) => Role?.ervuRole) || [];
      this.opened = true;
      return;
    }

    this.opened = true;
    this.loading = true;
    const { data } = await accountApi.getAccountRolesByAccountId(
      this.openedAccount.accountId
    );
    this.accountRoles = data.filter((Role) => Role?.ervuRole) || [];
    this.loading = false;
  }

  get openedAccountFio(): string {
    return this.openedAccount?.accountFullName || '';
  }
}
</script>
