<template>
  <q-page padding>
    <q-card>
      <q-card-section class="text-center">
        <div class="text-h4">Aktueller Stand</div>
        <div style="font-size: 2em">{{ balance.toFixed(2) }}&#8239;€</div>
      </q-card-section>
      <q-separator />
      <q-card-section>
        <q-table
          title="Buchungen"
          :data="data"
          :columns="columns"
          row-key="id"
          :pagination.sync="pagination"
          :loading="loading"
          @request="onRequest"
          binary-state-sort
        >
          <template v-slot:top>
            <q-toggle v-model="showCancelled" label="Stornierte einblenden" />
          </template>
          <template v-slot:body-cell="props">
            <q-td :props="props" v-bind:class="{ 'bg-grey': props.row.reversal_id != null }">
              {{ props.value }}
            </q-td>
          </template>
        </q-table>
      </q-card-section>
    </q-card>
  </q-page>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, ref } from 'vue';
import { StateInterfaceBalance, TransactionsResponse } from '../store/balance';
import { Store } from 'vuex';
import { formatDateTime } from 'src/utils/datetime';

export default defineComponent({
  // name: 'PageName'
  setup(_, { root }) {
    const store = <Store<StateInterfaceBalance>>root.$store;

    onMounted(() => {
      void store.dispatch('balance/getBalance');
      void store.dispatch('user/getUsers').then(() =>
        onRequest({
          pagination: pagination.value,
          filter: undefined,
        })
      );
    });

    const showCancelled = ref(false);
    const data = ref<FG.Transaction[]>([]);
    const loading = ref(false);
    const pagination = ref({
      sortBy: 'time',
      descending: false,
      page: 1,
      rowsPerPage: 3,
      rowsNumber: 10,
    });

    interface PaginationInterface {
      sortBy: string;
      descending: boolean;
      page: number;
      rowsPerPage: number;
      rowsNumber: number;
    }

    function onRequest(props: { pagination: PaginationInterface; filter?: string }) {
      const { page, rowsPerPage, sortBy, descending } = props.pagination;

      loading.value = true;
      // get all rows if "All" (0) is selected
      const fetchCount = rowsPerPage === 0 ? pagination.value.rowsNumber : rowsPerPage;
      // calculate starting row of data
      const startRow = (page - 1) * rowsPerPage;
      store
        .dispatch('balance/getTransactions', {
          filter: {
            offset: startRow,
            limit: fetchCount,
            showCancelled: showCancelled.value,
            showReversals: false,
          },
        })
        .then((result: TransactionsResponse) => {
          // clear out existing data and add new
          data.value.splice(0, data.value.length, ...result.transactions);
          // don't forget to update local pagination object
          pagination.value.page = page;
          pagination.value.rowsPerPage = rowsPerPage;
          pagination.value.sortBy = sortBy;
          pagination.value.descending = descending;
          if (result.count) pagination.value.rowsNumber = result.count;
        })
        .finally(() => (loading.value = false));
    }

    const balance = computed(
      () =>
        store.state.balance.balances.get((<FG.User>store.state.user.currentUser).userid)?.balance ||
        NaN
    );

    const columns = [
      {
        name: 'time',
        label: 'Datum',
        field: 'time',
        required: true,
        sortable: true,
        format: (val: Date) => formatDateTime(new Date(val), true, true, true),
      },
      {
        name: 'type',
        label: 'Type',
        format: (_: undefined, row: FG.Transaction) => {
          if (row.sender_id == null) return 'Gutschrift';
          else {
            if (row.receiver_id == null) return 'Angeschrieben';
            else {
              if (row.receiver_id === store.state.user.currentUser?.userid) return 'Bekommen von X';
              else return 'Gesendet an X';
            }
          }
        },
      },
      {
        name: 'text',
        label: 'Text',
        format: (_: undefined, row: FG.Transaction) => {
          if (row.sender_id == null) return 'Gutschrift';
          else {
            if (row.receiver_id == null) return 'Angeschrieben';
            else {
              if (row.receiver_id === store.state.user.currentUser?.userid) return 'Bekommen von X';
              else return 'Gesendet an X';
            }
          }
        },
      },
      {
        name: 'amount',
        label: 'Betrag',
        field: 'amount',
        format: (val: number) => `${val.toFixed(2)}€`,
      },
      {
        name: 'author_id',
        label: 'Benutzer',
        field: 'author_id',
        format: (val: string) => {
          const user = store.state.user.users.filter((x) => x.userid == val);
          if (user.length > 0) return user[0].display_name;
          else return val;
        },
      },
    ];

    return { data, pagination, onRequest, loading, balance, columns, showCancelled };
  },
});
</script>
