<i18n>
{
  "en": {
    "AccountsCard": {
      "columns": {
        "email": "Email address",
        "firstname": "First name",
        "middlename": "Middle name",
        "roles": "Roles",
        "sex": "Sex",
        "surname": "Surname",
        "department": "Department",
        "FIO": "Full name"
      },
      "tab": "Accounts",
      "title": "Accounts"
    }
  },
  "ru": {
    "AccountsCard": {
      "columns": {
        "email": "Адрес электронной почты",
        "firstname": "Имя",
        "middlename": "Отчество",
        "roles": "Роли",
        "sex": "Пол",
        "surname": "Фамилия",
        "department": "Подразделение",
        "FIO": "ФИО"
      },
      "tab": "Сотрудники",
      "title": "Сотрудники"
    }
  }
}
</i18n>

<template>
  <div v-if="common.active === 'accounts'" class="q-py-none">
    <q-card
      v-if="card && !loading"
      class="no-shadow q-pb-md q-gutter-y-md q-mx-md"
    >
      <div class="q-mx-md">
        <div class="q-py-md">
          <BaseTable
            class="no-shadow text-grey-9"
            row-key="id"
            :columns="columns"
            :data="accounts"
            :pagination.sync="pagination"
            :title="$t('AccountsCard.title')"
            :grid="$q.screen.xs"
          >
            <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 class="q-table__grid-item-title">
                        {{ col.label }}
                      </div>
                      <div class="q-table__grid-item-value">
                        {{ col.value }}
                      </div>
                    </div>
                  </div>
                </q-card>
              </div>
            </template>
          </BaseTable>
        </div>
      </div>
    </q-card>
    <q-inner-loading :showing="loading">
      <q-spinner-gears color="primary" size="50px" />
    </q-inner-loading>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import { LinksApi } from '@openapi/idm';
import get from 'lodash/get';

const linksApi = new LinksApi();

export default {
  props: ['common', 'model'],
  data() {
    return {
      accounts: [],
      pagination: {
        descending: true,
        page: 1,
        rowsNumber: 0,
        rowsPerPage: 10,
        sortBy: 'modified',
      },
    };
  },
  computed: {
    card() {
      return this.accounts || null;
    },
    columns() {
      return [
        {
          align: 'left',
          field: (val) => get(val, 'person', ''),
          label: this.$t('AccountsCard.columns.FIO'),
          name: 'person.surname',
          sortable: true,
          format: (val) => {
            if (val && typeof val === 'object') {
              return `${get(val, 'surname', '')} ${get(
                val,
                'firstname',
                ''
              )} ${get(val, 'middlename', '')} `;
            }
            return '';
          },
          handler: (id) => {
            // @ts-ignore // FIXME Преобразовать в *.ts
            const account = this.accounts.find((item) => {
              return item.person && item.person.id === id;
            });
            this.$router.push({
              name: 'account',
              params: {
                id: account.id,
              },
            });
          },
          handlerField: 'id',
          required: true,
        },
        {
          align: 'left',
          field: (val) => get(val, 'person.sex', ''),
          label: this.$t('AccountsCard.columns.sex'),
          name: 'person.sex',
          sortable: true,
        },
        {
          align: 'left',
          field: (val) => get(val, 'person.surname', ''),
          label: this.$t('AccountsCard.columns.email'),
          name: 'person.email',
          sortable: true,
        },
        {
          align: 'left',
          field: (val) => get(val, 'roles', []),
          format: (val) => val.map((role) => role.name).join(', '),
          label: this.$t('AccountsCard.columns.roles'),
          name: 'roles',
          sortable: true,
        },
        {
          align: 'left',
          field: (val) => get(val, 'user-domain.fullname', ''),
          label: this.$t('AccountsCard.columns.department'),
          name: 'userDomain',
          sortable: true,
        },
      ];
    },
    loading() {
      return this.card === null;
    },
  },
  watch: {
    model() {
      this.init();
    },
    card: {
      handler: function (val) {
        if (val) {
          if (val.accounts) {
            this.accounts = val.accounts;
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    init() {
      this.initAccounts();
    },
    initAccounts() {
      linksApi
        .pagingLinks(
          this.model.schema,
          this.model.id,
          'Account',
          undefined,
          undefined,
          undefined,
          undefined,
          'person, user-domain, roles'
        )
        .then(({ data }) => {
          this.accounts = data.records || [];
          this.pagination.rowsNumber = this.accounts.length;
        })
        .catch(() => {
          throw new Error('[components][cards][regions][Accounts][linksApi]');
        });
    },
  },
};
</script>
