<script setup>
import dayjs from "dayjs"
import {useSum} from "~/composables/useSum.js";

// Zugriff auf API und Toast
const { $api } = useNuxtApp()
const toast = useToast()

defineShortcuts({
  '/': () => {
    //console.log(searchinput)
    //searchinput.value.focus()
    document.getElementById("searchinput").focus()
  },
  '+': () => {
    router.push("/incomingInvoices/[mode]")
  },
  'Enter': {
    usingInput: true,
    handler: () => {
      const invoice = filteredRows.value[selectedItem.value]
      if (invoice) {
        selectIncomingInvoice(invoice)
      }
    }
  },
  '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 sort = ref({
  column: 'date',
  direction: 'desc'
})

// Status für den Button
const isPreparing = ref(false)

const type = "incominginvoices"
const dataType = dataStore.dataTypes[type]

const setupPage = async () => {
  items.value = await useEntities(type).select("*, vendor(id,name), statementallocations(id,amount)",sort.value.column,sort.value.direction === "asc")
}

// Funktion zum Vorbereiten der Belege
const prepareInvoices = async () => {
  isPreparing.value = true
  try {
    await $api('/api/functions/services/prepareincominginvoices', { method: 'POST' })

    toast.add({
      title: 'Erfolg',
      description: 'Eingangsbelege wurden vorbereitet.',
      icon: 'i-heroicons-check-circle',
      color: 'green'
    })

    // Liste neu laden
    await setupPage()
  } catch (error) {
    console.error(error)
    toast.add({
      title: 'Fehler',
      description: 'Beim Vorbereiten der Belege ist ein Fehler aufgetreten.',
      icon: 'i-heroicons-exclamation-circle',
      color: 'red'
    })
  } finally {
    isPreparing.value = false
  }
}

setupPage()

const selectedColumns = ref(tempStore.columns[type] ? tempStore.columns[type] : dataType.templateColumns.filter(i => !i.disabledInTable))
const columns = computed(() => dataType.templateColumns.filter((column) => !column.disabledInTable && selectedColumns.value.find(i => i.key === column.key)))

const selectableFilters = ref(dataType.filters.map(i => i.name))
const selectedFilters = ref(dataType.filters.filter(i => i.default).map(i => i.name) || [])

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

const clearSearchString = () => {
  tempStore.clearSearchString(type)
  searchString.value = ''
}
const filteredRows = computed(() => {
  let tempItems = items.value.map(i => {
    return {
      ...i,
      class: i.archived ? 'bg-red-500/50 dark:bg-red-400/50' : null
    }
  })

  if(selectedFilters.value.length > 0) {
    selectedFilters.value.forEach(filterName => {
      let filter = dataType.filters.find(i => i.name === filterName)
      tempItems = tempItems.filter(filter.filterFunction)
    })
  }



  tempItems = useSearch(searchString.value, tempItems)


  return [...tempItems.filter(i => i.state === "Vorbereitet"), ...tempItems.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 === "Gebucht") {
    router.push(`/incomingInvoices/show/${invoice.id}`)
  } else {
    router.push(`/incomingInvoices/edit/${invoice.id}`)
  }
}



</script>

<template>
  <UDashboardNavbar title="Eingangsbelege" :badge="filteredRows.length">
    <template #right>

      <UButton
          label="Belege vorbereiten"
          icon="i-heroicons-sparkles"
          color="primary"
          variant="solid"
          :loading="isPreparing"
          @click="prepareInvoices"
          class="mr-2"
      />

      <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(type,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 #right>
      <USelectMenu
          v-model="selectedColumns"
          icon="i-heroicons-adjustments-horizontal-solid"
          :options="dataType.templateColumns.filter(i => !i.disabledInTable)"
          multiple
          class="hidden lg:block"
          by="key"
          :color="selectedColumns.length !== dataType.templateColumns.filter(i => !i.disabledInTable).length ? 'primary' : 'white'"
          :ui-menu="{ width: 'min-w-max' }"
          @change="tempStore.modifyColumns(type,selectedColumns)"
      >
        <template #label>
          Spalten
        </template>
      </USelectMenu>
      <USelectMenu
          v-if="selectableFilters.length > 0"
          icon="i-heroicons-adjustments-horizontal-solid"
          multiple
          v-model="selectedFilters"
          :options="selectableFilters"
          :color="selectedFilters.length > 0 ? 'primary' : 'white'"
          :ui-menu="{ width: 'min-w-max' }"
      >
        <template #label>
          Filter
        </template>
      </USelectMenu>
    </template>
  </UDashboardToolbar>

  <UTabs
      class="m-3"
      :items="[{label: 'In Bearbeitung'},{label: 'Gebucht'}]"
  >
    <template #default="{item}">
      {{item.label}}
      <UBadge
          variant="outline"
          class="ml-2"
      >
        {{filteredRows.filter(i => item.label === 'Gebucht' ? i.state === 'Gebucht' : i.state !== 'Gebucht' ).length}}
      </UBadge>
    </template>
    <template #item="{item}">
      <div style="height: 80dvh; overflow-y: scroll">
        <UTable
            v-model:sort="sort"
            sort-mode="manual"
            @update:sort="setupPage"
            :rows="filteredRows.filter(i => item.label === 'Gebucht' ? i.state === 'Gebucht' : i.state !== 'Gebucht' )"
            :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>
      </div>

    </template>
  </UTabs>

</template>

<style scoped>

</style>
