<template>
  <UDashboardNavbar  title="Ausgangsbelege" :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('createddocuments',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(`/createDocument/edit`)"
      >
        + Ausgangsbeleg
      </UButton>
    </template>
  </UDashboardNavbar>
  <UDashboardToolbar>
    <template #left>
<!--      <UCheckbox
          v-model="showDrafts"
          label="Entwürfe Anzeigen"
          class="my-auto mr-3"
      />-->
      <USelectMenu
          v-model="selectedTypes"
          icon="i-heroicons-adjustments-horizontal-solid"
          :options="templateTypes"
          multiple
          class="hidden lg:block"
          by="key"
          @change="tempStore.modifyFilter('createddocuments',selectedTypes)"
      >
        <template #label>
          Typ
        </template>
      </USelectMenu>
    </template>

    <template #right>
      <USelectMenu
          v-model="selectedColumns"
          icon="i-heroicons-adjustments-horizontal-solid"
          :options="templateColumns"
          multiple
          class="hidden lg:block"
          by="key"
          @change="tempStore.modifyColumns('createddocuments',selectedColumns)"
      >
        <template #label>
          Spalten
        </template>
      </USelectMenu>
      <USelectMenu
          icon="i-heroicons-adjustments-horizontal-solid"
          multiple
          v-model="selectedFilters"
          :options="['Nur offene anzeigen']"
          :color="selectedFilters.length > 0 ? 'primary' : 'white'"
          :ui-menu="{ width: 'min-w-max' }"
      >
        <template #label>
          Filter
        </template>
      </USelectMenu>
    </template>
  </UDashboardToolbar>

  <UTabs :items="selectedTypes" class="m-3">
    <template #item="{item}">
      <div style="height: 80vh; overflow-y: scroll">
        <UTable
            :rows="filteredRows.filter(i => item.key === 'invoices' ? ['invoices','advanceInvoices','cancellationInvoices'].includes(i.type) : item.key === i.type)"
            :columns="columns"
            class="w-full"
            :ui="{ divide: 'divide-gray-200 dark:divide-gray-800' }"
            @select="selectItem"
            :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine Belege anzuzeigen' }"
        >
          <template #type-data="{row}">
            {{dataStore.documentTypesForCreation[row.type].labelSingle}}
            <span v-if="row.type === 'cancellationInvoices'"> zu {{row.linkedDocument.documentNumber}}</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 === 'Gebucht' && !items.find(i => i.linkedDocument && i.linkedDocument.id === row.id)"
                class="text-primary-500"
            >
          {{row.state}}
      </span>
            <span
                v-else-if="row.state === 'Gebucht' && items.find(i => i.linkedDocument && i.linkedDocument.id === row.id && i.type === 'cancellationInvoices') && ['invoices','advanceInvoices'].includes(row.type)"
                class="text-cyan-500"
            >
          Storniert mit {{items.find(i => i.linkedDocument && i.linkedDocument.id === row.id).documentNumber}}
      </span>
            <span
                v-else-if="row.state === 'Gebucht'"
                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 v-if="row.state === 'Gebucht' && row.paymentDays && ['invoices','advanceInvoices'].includes(row.type) && !items.find(i => i.linkedDocument && i.linkedDocument.id === row.id)" :class="dayjs(row.documentDate).add(row.paymentDays,'day').diff(dayjs()) <= 0 && !isPaid(row) ? ['text-rose-500'] : '' ">{{row.documentDate ? dayjs(row.documentDate).add(row.paymentDays,'day').format("DD.MM.YY") : ''}}</span>
          </template>
          <template #paid-data="{row}">
            <div v-if="(row.type === 'invoices' ||row.type === 'advanceInvoices') && row.state === 'Gebucht' && !items.find(i => i.linkedDocument && i.linkedDocument.id === row.id)">
              <span v-if="useSum().getIsPaid(row,items)" class="text-primary-500">Bezahlt</span>
              <span v-else class="text-rose-600">Offen</span>
            </div>
          </template>
          <template #amount-data="{row}">
            <span v-if="row.type !== 'deliveryNotes'">{{displayCurrency(useSum().getCreatedDocumentSum(row,items))}}</span>
          </template>
          <template #amountOpen-data="{row}">
            <span v-if="!['deliveryNotes','cancellationInvoices','quotes','confirmationOrders'].includes(row.type) && row.state !== 'Entwurf' && !useSum().getIsPaid(row,items) && !items.find(i => i.linkedDocument && i.linkedDocument.id === row.id) ">{{displayCurrency(useSum().getCreatedDocumentSum(row, items) - row.statementallocations.reduce((n,{amount}) => n + amount, 0))}}</span>
          </template>
        </UTable>
      </div>

    </template>
  </UTabs>

</template>

<script setup>
import dayjs from "dayjs";

defineShortcuts({
  '/': () => {
    //console.log(searchinput)
    //searchinput.value.focus()
    document.getElementById("searchinput").focus()
  },
  '+': () => {
    router.push('/createDocument/edit')
  },
  'Enter': {
    usingInput: true,
    handler: () => {
      router.push(`/createDocument/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 items = ref([])
const selectedItem = ref(0)

const setupPage = async () => {
  //items.value = (await useSupabaseSelect("createddocuments","*, customer(id,name), statementallocations(id,amount),linkedDocument(*)","documentNumber")).filter(i => !i.archived)
  items.value = (await useEntities("createddocuments").select("*, customer(id,name), statementallocations(id,amount),linkedDocument(*)","documentNumber")).filter(i => !i.archived)
}

setupPage()

const templateColumns = [
  {
    key: "reference",
    label: "Referenz",
    sortable: true
  },
  {
    key: 'type',
    label: "Typ",
    sortable: true
  },{
    key: 'state',
    label: "Status",
    sortable: true
  },
  {
    key: "amount",
    label: "Betrag",
    sortable: true
  },
  {
    key: 'partner',
    label: "Kunde",
    sortable: true
  },
  {
    key: "date",
    label: "Datum",
    sortable: true
  },
  {
    key: "amountOpen",
    label: "Offener Betrag",
    sortable: true
  },
  {
    key: "paid",
    label: "Bezahlt",
    sortable: true
  },
  {
    key: "dueDate",
    label: "Fällig",
    sortable: true
  }
]
const selectedColumns = ref(tempStore.columns["createddocuments"] ? tempStore.columns["createddocuments"] : templateColumns)
const columns = computed(() => templateColumns.filter((column) => selectedColumns.value.find(i => i.key === column.key)))

const templateTypes = [
  {
    key: "invoices",
    label: "Rechnungen"
  }/*,{
    key: "cancellationInvoices",
    label: "Stornorechnungen"
  },{
    key: "advanceInvoices",
    label: "Abschlagsrechnungen"
  }*/, {
    key: "quotes",
    label: "Angebote"
  }, {
    key: "deliveryNotes",
    label: "Lieferscheine"
  }, {
    key: "confirmationOrders",
    label: "Auftragsbestätigungen"
  }
]
const selectedTypes = ref(tempStore.filters["createddocuments"] ? tempStore.filters["createddocuments"] : templateTypes)
const types = computed(() => {
  return templateTypes.filter((type) => selectedTypes.value.find(i => i.key === type.key))
})

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

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

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


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

const clearSearchString = () => {
  tempStore.clearSearchString('createddocuments')
  searchString.value = ''
}
const selectedFilters = ref([])
const filteredRows = computed(() => {

  let temp = items.value.filter(i => types.value.find(x => x.key === 'invoices' ? ['invoices','advanceInvoices','cancellationInvoices'].includes(i.type) : x.key === i.type))
  temp = temp.filter(i => i.type !== "serialInvoices")

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

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


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

})


const isPaid = (item) => {
  let amountPaid = 0
  item.statementallocations.forEach(allocation => amountPaid += allocation.amount)

  return Number(amountPaid.toFixed(2)) === useSum().getCreatedDocumentSum(item, items.value)
}
</script>

<style scoped>

</style>