<template>
  <q-card>
    <BalanceHeader
      @update:user="userUpdated"
      :show-selector="showSelector"
      @open-history="openHistory"
    />
    <q-separator />

    <q-card-section class="row q-col-gutter-md" v-if="shortCuts">
      <div :key="index" v-for="(shortcut, index) in shortCuts" class="col-4">
        <q-btn
          push
          v-if="shortcut"
          color="primary"
          style="width: 100%"
          :label="shortcut.toFixed(2).toString() + ' €'"
          @click="changeBalance(shortcut)"
        >
          <q-popup-proxy context-menu>
            <q-btn label="Entfernen" @click="removeShortcut(shortcut)" />
          </q-popup-proxy>
          <q-tooltip>Rechtsklick um Verknüpfung zu entfernen</q-tooltip>
        </q-btn>
      </div></q-card-section
    >
    <q-card-section class="row q-col-gutter-md items-center">
      <div class="col-sm-4 col-xs-12">
        <q-input
          v-model.number="amount"
          type="number"
          filled
          label="Eigener Betrag"
          step="0.1"
          min="0"
        />
      </div>
      <div class="col-sm-4 col-xs-6">
        <q-btn
          style="width: 100%"
          color="primary"
          label="Anschreiben"
          @click="changeBalance(amount * -1)"
          ><q-tooltip>Rechtsklick um Betrag als Verknüpfung hinzuzufügen</q-tooltip>
          <q-popup-proxy context-menu v-model="showAddShortcut">
            <q-btn label="neue Verknüpfung" @click="addShortcut"></q-btn>
          </q-popup-proxy>
        </q-btn>
      </div>
      <div class="col-sm-4 col-xs-6">
        <q-btn
          v-if="canAddCredit"
          style="width: 100%"
          color="secondary"
          label="Gutschreiben"
          @click="changeBalance(amount)"
        />
      </div>
    </q-card-section>
  </q-card>
</template>

<script lang="ts">
import { computed, ref, defineComponent, onBeforeMount } from 'vue';
import { hasPermission } from 'src/utils/permission';
import { Store, useStore, mapGetters } from 'vuex';
import BalanceHeader from '../components/BalanceHeader.vue';
import PERMISSIONS from '../permissions';
import { StateInterface } from 'src/store';

export default defineComponent({
  name: 'BalanceAdd',
  components: { BalanceHeader },
  emits: { 'open-history': () => true },
  setup(_, { emit }) {
    onBeforeMount(() => {
      void store.dispatch('balance/getShortcuts');
      if ((<FG.Transaction[]>balanceGatters.transactions())?.length == 0)
        // No transaction, load at most six since yesterday
        void store.dispatch('balance/getTransactions', {
          filter: { limit: 6, from: new Date(new Date().setDate(new Date().getDate() - 1)) },
        });
    });
    //const store = <Store<StateInterfaceBalance>>root.$store;
    const store = useStore<Store<StateInterface>>();
    const userGetters = mapGetters('users', ['currentUser', 'roles', 'users']);
    const balanceGatters = mapGetters('balance', ['balances', 'transactions', 'shortcuts']);

    const amount = ref<number>(0);
    const showAddShortcut = ref(false);
    const user = ref(<FG.User>userGetters.currentUser());
    //const shortCuts = ref(balanceState.shortcuts);
    const shortCuts = computed(() => <number[]>balanceGatters.shortcuts());

    const canAddCredit = computed(() => hasPermission(PERMISSIONS.CREDIT));
    const showSelector = computed(
      () => hasPermission(PERMISSIONS.DEBIT) || hasPermission(PERMISSIONS.CREDIT)
    );

    function addShortcut() {
      if (amount.value != 0) void store.dispatch('balance/addShortcut', amount.value * -1);
    }
    function removeShortcut(shortcut: number) {
      void store.dispatch('balance/removeShortcut', shortcut);
    }
    function userUpdated(selectedUser: FG.User) {
      user.value = selectedUser;
    }
    function changeBalance(amount: number) {
      store
        .dispatch('balance/changeBalance', { amount: amount, user: user.value?.userid })
        .catch((err) => console.log(err));
    }

    function openHistory() {
      emit('open-history');
    }

    return {
      user,
      addShortcut,
      canAddCredit,
      removeShortcut,
      showAddShortcut,
      changeBalance,
      amount,
      showSelector,
      shortCuts,
      userUpdated,
      openHistory,
    };
  },
});
</script>
