<template>
  <div id="main">

    <InputGroup>
<!--
      <UButton @click="router.push(`/incominginvoices/create/`)">+ Eingangsrechnung</UButton>
-->
      <UButton
          @click="router.push(`/createDocument/edit?type=quotes`)"
      >
        + Angebot
      </UButton>
      <UButton
          @click="router.push(`/createDocument/edit?type=invoices`)"
      >
        + Rechnung
      </UButton>

      <UInput
          v-model="searchString"
          placeholder="Suche..."
      />

      <UCheckbox
        v-model="showDrafts"
        label="Entwürfe Anzeigen"
      />
    </InputGroup>



    <UTable
        :rows="filteredRows"
        :columns="itemColumns"
        @select="selectItem"
        :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Noch keine Einträge' }"
    >
      <template #type-data="{row}">
        <span v-if="row.type === 'incomingInvoice'">Eingangsrechnung</span>
        <span v-else>{{dataStore.documentTypesForCreation[row.type].labelSingle}}</span>
      </template>
      <template #state-data="{row}">
        <span
          v-if="row.state === 'Entwurf'"
          class="text-rose-500"
        >
          {{row.state}}
        </span>
        <span
          v-if="row.state === 'Gebucht'"
          class="text-cyan-500"
        >
          {{row.state}}
        </span>
        <span
          v-if="row.state === 'Abgeschlossen'"
          class="text-primary-500"
        >
          {{row.state}}
        </span>
      </template>
      <template #partner-data="{row}">
        <span v-if="row.customer">{{dataStore.getCustomerById(row.customer) ? dataStore.getCustomerById(row.customer).name : ''}}</span>
        <span v-else-if="row.vendor">{{dataStore.getVendorById(row.vendor) ? dataStore.getVendorById(row.vendor).name : ''}}</span>

      </template>
      <template #reference-data="{row}">
        <span v-if="row.type === 'incomingInvoice'">{{row.reference}}</span>
        <span v-else>{{row.documentNumber}}</span>
      </template>
      <template #date-data="{row}">
        <span v-if="row.date">{{row.date ? dayjs(row.date).format("DD.MM.YY") : ''}}</span>
      </template>
      <template #dueDate-data="{row}">
        <span :class="dayjs(row.dueDate).diff(dayjs()) <= 0 ? ['text-rose-500'] : '' ">{{row.dueDate ? dayjs(row.dueDate).format("DD.MM.YY") : ''}}</span>
      </template>
      <template #paid-data="{row}">
        <span v-if="row.paid" class="text-primary-500">Bezahlt</span>
        <span v-if="!row.paid" :class="dayjs(row.dueDate).diff(dayjs()) <= 0 ? ['text-rose-500'] : ['text-cyan-500'] ">Offen</span>
      </template>
      <template #amount-data="{row}">
        <div
            class="text-right font-bold"
            v-if="row.type === 'incomingInvoice'"
        >
          {{getRowAmount(row) === 0 ? '' : `${String(getRowAmount(row).toFixed(2)).replace('.',',')} €`}}
        </div>
      </template>
    </UTable>



  </div>
</template>

<script setup>
import dayjs from "dayjs";

definePageMeta({
  middleware: "auth"
})

const dataStore = useDataStore()
const router = useRouter()
const mode = ref("show")

const itemColumns = [
  {
    key: 'type',
    label: "Typ",
    sortable: true
  },{
    key: 'state',
    label: "Status.",
    sortable: true
  },
  {
    key: 'partner',
    label: "Kunde / Lieferant",
    sortable: true
  },
  {
    key: "reference",
    label: "Referenz",
    sortable: true
  },
  {
    key: "date",
    label: "Datum",
    sortable: true
  },
  {
    key: "paid",
    label: "Bezahlt:",
    sortable: true
  },
  {
    key: "dueDate",
    label: "Fällig:",
    sortable: true
  },
  {
    key: "amount",
    label: "Betrag",
    sortable: true
  },
]


const selectItem = (item) => {
  console.log(item)

  if(item.type === "incomingInvoice"){
    if(item.state === "Entwurf") {
      router.push(`/receipts/incominginvoices/edit/${item.id} `)
    } else if(item.state === "Gebucht") {
      router.push(`/receipts/incominginvoices/show/${item.id}`)
    }
  } else {
    if(item.state === "Entwurf"){
      router.push(`/createDocument/edit/${item.id}`)
    } else if(item.state !== "Entwurf") {
      router.push(`/createDocument/show/${item.id}`)
    }
  }





}

const getRowAmount = (row) => {
  let amount = 0

  row.accounts.forEach(account => {
    amount += account.amountNet
    amount += account.amountTax
  })

  return amount
}


const searchString = ref('')
const showDrafts = ref(false)

const filteredRows = computed(() => {
  let items = [...dataStore.incominginvoices.map(i => {return {...i, type: "incomingInvoice"}}),...dataStore.createddocuments]

  console.log(dataStore.createddocuments)

  if(showDrafts.value === true) {
    items = items.filter(i => i.state === "Entwurf")
  } else {
    items = items.filter(i => i.state !== "Entwurf")
  }


  if(!searchString.value) {
    return items
  }

  return items.filter(item => {
    return Object.values(item).some((value) => {
      return String(value).toLowerCase().includes(searchString.value.toLowerCase())
    })
  })
})
</script>

<style scoped>

</style>