<script setup>

import dayjs from "dayjs";

defineShortcuts({
  '/': () => {
    //console.log(searchinput)
    //searchinput.value.focus()
    document.getElementById("searchinput").focus()
  }
})

const tempStore = useTempStore()
const router = useRouter()

const bankstatements = ref([])
const bankaccounts = ref([])

const setupPage = async () => {
  bankstatements.value = (await useEntities("bankstatements").select("*, statementallocations(*)", "date", false))
  bankaccounts.value = await useEntities("bankaccounts").select()
}

const templateColumns = [
  {
    key: "account",
    label: "Konto"
  },{
    key: "valueDate",
    label: "Valuta"
  },
  {
    key: "amount",
    label: "Betrag"
  },
  {
    key: "openAmount",
    label: "Offener Betrag"
  },
  {
    key: "partner",
    label: "Name"
  },
  {
    key: "text",
    label: "Beschreibung"
  }
]
const selectedColumns = ref(templateColumns)
const columns = computed(() => templateColumns.filter((column) => selectedColumns.value.includes(column)))


const searchString = ref(tempStore.searchStrings["bankstatements"] ||'')

const clearSearchString = () => {
  tempStore.clearSearchString("bankstatements")
  searchString.value = ''
}

const filterAccount = ref(bankaccounts || [])

const displayCurrency = (value, currency = "€") => {
  return `${Number(value).toFixed(2).replace(".",",")} ${currency}`
}



const calculateOpenSum = (statement) => {
  let startingAmount = 0

  statement.statementallocations.forEach(item => {
    startingAmount += item.amount
  })

  return (statement.amount - startingAmount).toFixed(2)
}

const selectedFilters = ref(tempStore.filters["banking"] ? tempStore.filters["banking"] : ['Nur offene anzeigen'])

const filteredRows = computed(() => {
  let temp = bankstatements.value

  if(selectedFilters.value.includes("Nur offene anzeigen")){
    temp = temp.filter(i => Number(calculateOpenSum(i)) !== 0)
  }

  if(selectedFilters.value.includes("Nur positive anzeigen")){
    temp = temp.filter(i => i.amount >= 0)
  }

  if(selectedFilters.value.includes("Nur negative anzeigen")){
    temp = temp.filter(i => i.amount < 0)
  }

  return useSearch(searchString.value, temp.filter(i => filterAccount.value.find(x => x.id === i.account)))
})

setupPage()
</script>

<template>
  <UDashboardNavbar title="Bankbuchungen" :badge="filteredRows.length">
    <template #right>
      <UInput
          id="searchinput"
          name="searchinput"
          v-model="searchString"
          icon="i-heroicons-funnel"
          autocomplete="off"
          placeholder="Suche..."
          class="hidden lg:block"
          @keydown.esc="$event.target.blur()"
          @change="tempStore.modifySearchString('bankstatements',searchString)"
      >
        <template #trailing>
          <UKbd value="/" />
        </template>
      </UInput>
      <UButton
          icon="i-heroicons-x-mark"
          variant="outline"
          color="rose"
          @click="clearSearchString()"
          v-if="searchString.length > 0"
      />
    </template>
  </UDashboardNavbar>
  <UDashboardToolbar>
    <template #left>
      <USelectMenu
        :options="bankaccounts"
        v-model="filterAccount"
        option-attribute="iban"
        multiple
        by="id"
        :ui-menu="{ width: 'min-w-max' }"
      >
        <template #label>
          Konto
        </template>
      </USelectMenu>
    </template>
    <template #right>
      <USelectMenu
          v-model="selectedColumns"
          icon="i-heroicons-adjustments-horizontal-solid"
          :options="templateColumns"
          multiple
          class="hidden lg:block"
          by="key"
          :ui-menu="{ width: 'min-w-max' }"
      >
        <template #label>
          Spalten
        </template>
      </USelectMenu>
      <USelectMenu
          icon="i-heroicons-adjustments-horizontal-solid"
          multiple
          v-model="selectedFilters"
          :options="['Nur offene anzeigen','Nur positive anzeigen','Nur negative anzeigen']"
          :color="selectedFilters.length > 0 ? 'primary' : 'white'"
          :ui-menu="{ width: 'min-w-max' }"
          @change="tempStore.modifyFilter('banking',selectedFilters)"
      >
        <template #label>
          Filter
        </template>
      </USelectMenu>
    </template>
  </UDashboardToolbar>
  <UTable
      :rows="filteredRows"
      :columns="columns"
      class="w-full"
      :ui="{ divide: 'divide-gray-200 dark:divide-gray-800' }"
      @select="(i) => router.push(`/banking/statements/edit/${i.id}`)"
      :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine Buchungen anzuzeigen' }"
  >

    <template #account-data="{row}">
      {{row.account ? bankaccounts.find(i => i.id === row.account).iban : ""}}
    </template>
    <template #valueDate-data="{row}">
      {{dayjs(row.valueDate).format("DD.MM.YY")}}
    </template>
    <template #amount-data="{row}">
      <span
        v-if="row.amount >= 0"
        class="text-primary-500"
      >{{String(row.amount.toFixed(2)).replace(".",",")}} €</span>
      <span
        v-else-if="row.amount < 0"
        class="text-rose-500"
      >{{String(row.amount.toFixed(2)).replace(".",",")}} €</span>
    </template>
    <template #openAmount-data="{row}">
      {{displayCurrency(calculateOpenSum(row))}}
    </template>
    <template #partner-data="{row}">
      <span
        v-if="row.amount < 0"
      >
          {{row.credName}}
      </span>
      <span
        v-else-if="row.amount > 0"
      >
        {{row.debName}}
      </span>
    </template>
  </UTable>


</template>



<style scoped>

</style>