<template>
  <div>
    <q-page padding>
      <q-table :rows="rows" row-key="userid" :columns="columns">
        <template #top-right>
          <div class="full-width row q-gutter-sm">
            <q-input
              v-model.number="limit"
              label="Limit"
              type="number"
              step="0.01"
              suffix="€"
              filled
              dense
            />
            <q-btn label="Limits Setzen" color="primary" dense @click="setLimits(limit)" />
          </div>
        </template>
      </q-table>
    </q-page>
  </div>
</template>

<script lang="ts">
// TODO: Fill usefull data

import { ref, defineComponent, computed, onBeforeMount } from 'vue';
import { useBalanceStore } from '../store';
import { useUserStore } from 'src/plugins/user/store';

export default defineComponent({
  // name: 'PageName'
  setup() {
    const store = useBalanceStore();
    const userStore = useUserStore();

    onBeforeMount(() => {
      void store.getBalances();
      void userStore.getUsers();
      void store.getLimits();
    });

    const rows = computed(() => store.balances);
    const limit = ref<number>();

    const columns = [
      {
        name: 'userid',
        label: 'Benutzer ID',
        field: 'userid',
        required: true,
        align: 'left',
        sortable: true,
        format: (val: string) => userStore.users.find((a) => a.userid === val)?.display_name,
      },
      /*{
        name: 'credit',
        label: 'Haben',
        field: 'credit',
        format: (val: number) => val.toFixed(2),
      },
      {
        name: 'debit',
        label: 'Soll',
        field: 'debit',
        format: (val: number) => val.toFixed(2),
      },*/
      {
        name: 'limit',
        label: 'Limit',
        format: (_: undefined, row: { userid: string }) =>
          store.user_limits.find((a) => a.userid === row.userid)?.limit?.toFixed(2),
      },
      {
        name: 'balance',
        label: 'Kontostand',
        format: (_: undefined, row: { debit: number; credit: number }) =>
          (row.credit - row.debit).toFixed(2),
      },
    ];

    return { rows, columns, limit, setLimits: store.setLimits };
  },
});
</script>
