

<template>
  <UDashboardNavbar title="Serienrechnungen" :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()"
      >
        <template #trailing>
          <UKbd value="/" />
        </template>
      </UInput>
      <UButton
          @click="router.push(`/createDocument/edit?type=serialInvoices`)"
      >
        + Serienrechnung
      </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>
      <USelectMenu
          v-model="selectedFilters"
          icon="i-heroicons-adjustments-horizontal-solid"
          :options="filterOptions"
          option-attribute="name"
          value-attribute="name"
          multiple
          class="hidden lg:block"
          :color="selectedFilters.length > 0 ? 'primary' : 'white'"
          :ui-menu="{ width: 'min-w-max' }"
      >
        <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="(row) => router.push(`/createDocument/edit/${row.id}`)"
      :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine Belege anzuzeigen' }"
  >
    <template #type-data="{row}">
      {{dataStore.documentTypesForCreation[row.type].labelSingle}}
    </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">{{row.customer ? row.customer.name : ""}}</span>

    </template>
    <!--<template #reference-data="{row}">
      <span v-if="row === filteredRows[selectedItem]" class="text-primary-500 font-bold">{{row.documentNumber}}</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>
      <span v-if="row.documentDate">{{row.documentDate ? dayjs(row.documentDate).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}">
      <div v-if="row.type === 'invoices' ||row.type === 'advanceInvoices'">
        <span v-if="isPaid(row)" class="text-primary-500">Bezahlt</span>
        <span v-else class="text-rose-600">Offen</span>
      </div>
    </template>-->
    <template #amount-data="{row}">
      {{displayCurrency(calculateDocSum(row))}}
    </template>
    <template #serialConfig.active-data="{row}">
      <span v-if="row.serialConfig.active" class="text-primary">Ja</span>
      <span v-else class="text-rose-600">Nein</span>
    </template>
  </UTable>

</template>

<script setup>
import dayjs from "dayjs";

const router = useRouter()
const dataStore = useDataStore()
const items = ref([])
const selectedItem = ref(0)

const setupPage = async () => {
  items.value = await useEntities("createddocuments").select("*, customer(id,name)","documentDate",undefined,true)
}

const searchString = ref("")
const filteredRows = computed(() => {



  let temp = items.value.filter(i => i.type === "serialInvoices").map(i => {
    return {
      ...i,
      class: i.archived ? 'bg-red-500/50 dark:bg-red-400/50' : null
    }
  })

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

  selectedFilters.value.forEach(filterName => {
    let filter = filterOptions.value.find(i => i.name === filterName)
    temp = temp.filter(filter.filterFunction)
  })

  return useSearch(searchString.value, temp.slice().reverse())

})

const templateColumns = [
  {
    key: 'type',
    label: "Typ"
  },{
    key: 'state',
    label: "Status"
  },
  {
    key: "amount",
    label: "Betrag"
  },
  {
    key: 'partner',
    label: "Kunde"
  },
  {
    key: 'serialConfig.active',
    label: "Aktiv"
  }
]
const selectedColumns = ref(templateColumns)
const columns = computed(() => templateColumns.filter((column) => selectedColumns.value.includes(column)))

const filterOptions = ref([
  {
    name: "Archivierte ausblenden",
    default: true,
    "filterFunction": function (row) {
      if(!row.archived) {
        return true
      } else {
        return false
      }
    }
  },{
    name: "Inaktive ausblenden",
    default: true,
    "filterFunction": function (row) {
      if(row.serialConfig.active) {
        return true
      } else {
        return false
      }
    }
  }
])
const selectedFilters = ref(filterOptions.value.filter(i => i.default).map(i => i.name) ||[])


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

const calculateDocSum = (row) => {
  let sum = 0

  row.rows.forEach(row => {
    if(row.mode === "normal" || row.mode === "service" || row.mode === "free") {
      sum += row.quantity * row.price * (1 - row.discountPercent / 100) * (1 + row.taxPercent / 100)
    }
  })

  return sum.toFixed(2)
}

setupPage()
</script>

<style scoped>

</style>