<template>
  <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" suffix="€" />
  </div>
  <div class="col-sm-4 col-xs-6">
    <q-btn v-close-popup style="width: 100%" color="primary" label="Anschreiben" @click="changeBalance(amount * -1)">
      <q-tooltip v-if="canAddShortcut"> Rechtsklick um Betrag als Verknüpfung hinzuzufügen </q-tooltip>
      <q-menu v-if="canAddShortcut" anchor="bottom middle" self="top middle" context-menu>
        <q-btn label="neue Verknüpfung" @click="addShortcut"></q-btn>
      </q-menu>
    </q-btn>
  </div>
  <div class="col-sm-4 col-xs-6">
    <q-btn
      v-if="canAddCredit"
      v-close-popup
      style="width: 100%"
      color="secondary"
      label="Gutschreiben"
      @click="changeBalance(amount)"
    />
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, PropType, computed, watch } from 'vue';
import { useBalanceStore } from '../store';
import { hasPermission, useUserStore } from '@flaschengeist/api';
import PERMISSIONS from '../permissions';
export default defineComponent({
  name: 'BalanceAddBody',
  props: {
    user: {
      type: [Object, String] as PropType<FG.User | string>,
      required: true,
    },
    canAddShortcut: {
      type: Boolean,
      default: false,
    },
  },
  emits: {
    changeBalance: (user: FG.User) => user,
  },
  setup(props, { emit }) {
    const store = useBalanceStore();
    const userStore = useUserStore();
    const amount = ref<number>(0);
    async function changeBalance(amount: number) {
      await store.changeBalance(amount, user.value);
      emit('changeBalance', user.value);
    }
    function addShortcut() {
      if (amount.value != 0) void store.createShortcut(amount.value * -1);
    }
    const canAddCredit = hasPermission(PERMISSIONS.CREDIT);
    const user = computed(() =>
      (<FG.User>props.user).userid
        ? <FG.User>props.user
        : <FG.User>userStore.users.find((a) => a.userid === <string>props.user)
    );
    watch(amount, (a) => {
      amount.value = Math.abs(a);
    });
    return { changeBalance, addShortcut, canAddCredit, amount };
  },
});
</script>

<style scoped></style>
