<script setup>
import dayjs from "dayjs"
import {useSum} from "~/composables/useSum.js";
definePageMeta({
  middleware: "auth"
})

defineShortcuts({
  '/': () => {
    //console.log(searchinput)
    //searchinput.value.focus()
    document.getElementById("searchinput").focus()
  },
  '+': () => {
    router.push("/incomingInvoices/[mode]")
  },
  'Enter': {
    usingInput: true,
    handler: () => {
      router.push(`/incomingInvoices/show/${filteredRows.value[selectedItem.value].id}`)
    }
  },
  'arrowdown': () => {
    if(selectedItem.value < filteredRows.value.length - 1) {
      selectedItem.value += 1
    } else {
      selectedItem.value = 0
    }
  },
  'arrowup': () => {
    if(selectedItem.value === 0) {
      selectedItem.value = filteredRows.value.length - 1
    } else {
      selectedItem.value -= 1
    }
  }
})

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

const sum = useSum()

const items = ref([])
const selectedItem = ref(0)

const setupPage = async () => {
  items.value = await useSupabaseSelect("incominginvoices","*, vendor(id,name), statementallocations(id,amount)","created_at",false)
}

setupPage()

const templateColumns = [
  {
    key: 'reference',
    label: "Referenz:"
  }, {
    key: 'state',
    label: "Status:"
  },
  {
    key: "date",
    label: "Datum"
  },
  {
    key: "vendor",
    label: "Lieferant"
  },
  {
    key: "amount",
    label: "Betrag"
  },
  {
    key: "dueDate",
    label: "Fälligkeitsdatum"
  },
  {
    key: "paid",
    label: "Bezahlt"
  },
  {
    key: "paymentType",
    label: "Zahlart"
  },
  {
    key: "description",
    label: "Beschreibung"
  }
]
const selectedColumns = ref(templateColumns)
const columns = computed(() => templateColumns.filter((column) => selectedColumns.value.includes(column)))


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

const clearSearchString = () => {
  tempStore.clearSearchString('incominginvoices')
  searchString.value = ''
}
const filteredRows = computed(() => {
  let filteredItems = useSearch(searchString.value, items.value)

  return [...filteredItems.filter(i => i.state === "Vorbereitet"), ...filteredItems.filter(i => i.state !== "Vorbereitet")]


})

const displayCurrency = (value, currency = "€") => {
  return `${Number(value).toFixed(2).replace(".",",")} ${currency}`
}
const getInvoiceSum = (invoice) => {
  let sum = 0
  invoice.accounts.forEach(account => {
    sum += account.amountTax
    sum += account.amountNet
  })
  return sum.toFixed(2)
}

const isPaid = (item) => {
  let amountPaid = 0
  item.statementallocations.forEach(allocation => amountPaid += allocation.amount)
  return Math.abs(amountPaid) === Math.abs(Number(getInvoiceSum(item)))
}

const selectIncomingInvoice = (invoice) => {
  if(invoice.state === "Vorbereitet") {
    router.push(`/incomingInvoices/edit/${invoice.id}`)
  } else {
    router.push(`/incomingInvoices/show/${invoice.id}`)
  }


}



</script>

<template>
  <UDashboardNavbar title="Eingangsbelege" :badge="filteredRows.length">
    <template #right>
      <UInput
          id="searchinput"
          v-model="searchString"
          icon="i-heroicons-funnel"
          autocomplete="off"
          placeholder="Suche..."
          class="hidden lg:block"
          @keydown.esc="$event.target.blur()"
          @change="tempStore.modifySearchString('incominginvoices',searchString)"
      >
        <template #trailing>
          <UKbd value="/" />
        </template>
      </UInput>
      <UButton
          icon="i-heroicons-x-mark"
          variant="outline"
          color="rose"
          @click="clearSearchString()"
          v-if="searchString.length > 0"
      />

<!--      <UButton @click="router.push(`/incomingInvoices/create`)">+ Beleg</UButton>-->
    </template>
  </UDashboardNavbar>
  <UDashboardToolbar>
    <template #right>
      <USelectMenu
          v-model="selectedColumns"
          icon="i-heroicons-adjustments-horizontal-solid"
          :options="templateColumns"
          multiple
          class="hidden lg:block"
          by="key"
      >
        <template #label>
          Spalten
        </template>
      </USelectMenu>
    </template>
  </UDashboardToolbar>

  <UDashboardPanelContent>
    <UTable
        :rows="filteredRows"
        :columns="columns"
        class="w-full"
        :ui="{ divide: 'divide-gray-200 dark:divide-gray-800' }"
        @select="(i) => selectIncomingInvoice(i) "
        :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine Belege anzuzeigen' }"
    >
      <template #reference-data="{row}">
        <span v-if="row === filteredRows[selectedItem]" class="text-primary-500 font-bold">{{row.reference}}</span>
        <span v-else>{{row.reference}}</span>
      </template>
      <template #state-data="{row}">
        <span v-if="row.state === 'Vorbereitet'" class="text-cyan-500">{{row.state}}</span>
        <span v-else-if="row.state === 'Entwurf'" class="text-red-500">{{row.state}}</span>
        <span v-else-if="row.state === 'Gebucht'" class="text-primary-500">{{row.state}}</span>
      </template>
      <template #date-data="{row}">
        {{dayjs(row.date).format("DD.MM.YYYY")}}
      </template>
      <template #vendor-data="{row}">
        {{row.vendor ? row.vendor.name : ""}}
      </template>
      <template #amount-data="{row}">
        {{displayCurrency(sum.getIncomingInvoiceSum(row))}}
      </template>
      <template #dueDate-data="{row}">
        <span v-if="row.dueDate">{{dayjs(row.dueDate).format("DD.MM.YYYY")}}</span>
      </template>
      <template #paid-data="{row}">
        <span v-if="isPaid(row)" class="text-primary-500">Bezahlt</span>
        <span v-else class="text-rose-600">Offen</span>
      </template>
    </UTable>
  </UDashboardPanelContent>

</template>

<style scoped>

</style>