<i18n>
{
  "en": {
    "RolesAndPermissions": {
      "more": "and {length} more",
      "roles": {
        "columns": {
          "description": "Description",
          "name": "System name",
          "displayName": "Наименование",
          "permissions": "Permissions"
        },
        "title": "Roles and permissions"
      }
    }
  },
  "ru": {
    "RolesAndPermissions": {
      "more": "и ещё {length}",
      "roles": {
        "columns": {
          "description": "Описание",
          "name": "Системное имя",
          "displayName": "Наименование",
          "permissions": "Разрешения"
        },
        "title": "Роли и разрешения"
      }
    }
  }
}
</i18n>

<template>
  <q-card
    v-if="common.active === 'rolesAndPermissions'"
    class="no-shadow q-pb-md q-gutter-y-md q-mx-md"
  >
    <div
      class="items-center justify-between row q-pa-md"
      style="border-radius: 0"
    >
      <div class="q-gutter-y-md full-width">
        <q-table
          class="no-shadow text-grey-9"
          row-key="id"
          :columns="rolesColumns"
          :data="roles.records"
          :pagination.sync="roles.pagination"
          :title="$t('RolesAndPermissions.roles.title')"
          :grid="$q.screen.xs"
        >
          <template #body="props">
            <q-tr :props="props">
              <q-td key="name" :props="props">
                {{ props.row.name }}
              </q-td>
              <q-td key="displayName" :props="props">
                {{ props.row.displayName }}
              </q-td>
              <q-td key="description" :props="props">
                {{ props.row.description }}
              </q-td>
              <q-td key="permissions" :props="props">
                <div v-if="props.row.children" class="items-center row">
                  <q-chip
                    v-for="permission in props.row.children.slice(0, 3)"
                    :key="permission.id"
                  >
                    {{ permission.name }}
                  </q-chip>
                  <q-chip
                    v-if="props.row.children.slice(3).length"
                    clickable
                    outline
                    @click="
                      showPermissions(
                        props.row.children.slice(3).map((el) => el.name)
                      )
                    "
                  >
                    ...
                    {{
                      $t('RolesAndPermissions.more', {
                        length: props.row.children.slice(3).length,
                      })
                    }}
                  </q-chip>
                </div>
              </q-td>
            </q-tr>
          </template>
          <template #item="props">
            <div class="col-12 q-px-md q-py-xs">
              <q-card class="q-table__grid-item col-12 overflow-auto">
                <div class="q-table__grid-item-card">
                  <div
                    v-for="col in props.cols"
                    :key="col.name"
                    class="q-table__grid-item-row"
                  >
                    <div v-if="col.name !== 'permissions'">
                      <div class="q-table__grid-item-title">
                        {{ col.label }}
                      </div>
                      <div class="q-table__grid-item-value">
                        {{ col.value }}
                      </div>
                    </div>
                    <div v-else>
                      <div v-if="props.row.children" class="items-center row">
                        <q-chip
                          v-for="permission in props.row.children.slice(0, 3)"
                          :key="permission.id"
                        >
                          {{ permission.name }}
                        </q-chip>
                        <q-chip
                          v-if="props.row.children.slice(3).length"
                          clickable
                          outline
                          @click="
                            showPermissions(
                              props.row.children.slice(3).map((el) => el.name)
                            )
                          "
                        >
                          ...
                          {{
                            $t('RolesAndPermissions.more', {
                              length: props.row.children.slice(3).length,
                            })
                          }}
                        </q-chip>
                      </div>
                    </div>
                  </div>
                </div>
              </q-card>
            </div>
          </template>
        </q-table>
      </div>
    </div>
  </q-card>
</template>

<script lang="ts">
import { BaseCardCommon } from '@interfaces/components';
import { GraphApi, NodeTO, Role } from '@openapi/idm';
import { Component, Prop, Vue } from 'vue-property-decorator';
import get from 'lodash/get';

const graphApi = new GraphApi();

@Component({})
export default class RolesAndPermissions extends Vue {
  @Prop()
  private common?: BaseCardCommon;

  @Prop({
    default: Object,
  })
  private model?: any;

  private roles = {
    pagination: {
      page: 1,
      rowsPerPage: 10,
    },
    records: [] as NodeTO[],
  };

  private get rolesColumns() {
    return [
      {
        align: 'left',
        field: (val: any) => val.name || '',
        label: this.$t('RolesAndPermissions.roles.columns.name'),
        name: 'name',
        sortable: true,
      },
      {
        align: 'left',
        field: (val: any) => val.displayName || '',
        label: this.$t('RolesAndPermissions.roles.columns.displayName'),
        name: 'displayName',
        sortable: true,
      },
      {
        align: 'left',
        field: (val: any) => val.description || '',
        label: this.$t('RolesAndPermissions.roles.columns.description'),
        name: 'description',
        sortable: true,
      },
      {
        align: 'left',
        field: (val: any) => val.children || [],
        label: this.$t('RolesAndPermissions.roles.columns.permissions'),
        name: 'permissions',
        sortable: true,
      },
    ];
  }

  private created() {
    this.initRoles();
  }

  private initRoles() {
    graphApi
      .tree('Solution', 'outgoing', get(this.common, 'id', ''), 2, [
        'Permission,Role',
      ])
      .then(({ data }) => {
        const getTreeStructure = function (node: any) {
          const result = {
            ...node.value,
            id: node.value.id,
            label: node.value.fullname || node.value.name,
          };

          if (node.leafs && node.leafs instanceof Array) {
            result.children = node.leafs.map((childNode: any) => {
              return getTreeStructure(childNode);
            });
          }

          return result;
        };

        if (data.leafs) {
          this.roles.records = data.leafs.map((node) => {
            return getTreeStructure(node);
          });
        } else {
          this.roles.records = [];
        }
      })
      .catch(() => {
        throw new Error(
          '[components][cards][solutions][RolesAndPermissions][graphApi]'
        );
      });
  }

  private showPermissions(permissions: any) {
    this.$q.dialog({
      message: permissions.join(', '),
      title: `${this.$t('RolesAndPermissions.roles.columns.permissions')}`,
    });
  }
}
</script>
