<script setup>

import dayjs from "dayjs";
import {filter} from "vuedraggable/dist/vuedraggable.common.js";

definePageMeta({
  middleware: "auth"
})

defineShortcuts({
  'backspace': () => {
    router.push("/banking")
  }
})

const dataStore = useDataStore()
const profileStore = useProfileStore()
const route = useRoute()
const router = useRouter()
const mode = ref(route.params.mode || "show")
const supabase = useSupabaseClient()

const itemInfo = ref({statementallocations:[]})
const oldItemInfo = ref({})

const openDocuments = ref([])
const allocatedDocuments = ref([])
const openIncomingInvoices = ref([])

const setup = async () => {
  if(route.params.id) {
    itemInfo.value =  (await supabase.from("bankstatements").select("*, statementallocations(*)").eq("id",route.params.id).single()).data  //dataStore.bankstatements.find(i => i.id === Number(route.params.id))
  }
  if(itemInfo.value) oldItemInfo.value = JSON.parse(JSON.stringify(itemInfo.value))

  const documents = (await useSupabaseSelect("createddocuments","*, statementallocations(*), customer(id,name)")).filter(i => i.type === "invoices" ||i.type === "advanceInvoices")

  openDocuments.value = documents.filter(i => i.statementallocations.reduce((n,{amount}) => n + amount, 0).toFixed(2) !== getDocumentSum(i).toFixed(2))
  openDocuments.value = openDocuments.value.map(i => {


    return {
        ...i,
      docTotal: getDocumentSum(i),
      statementTotal: Number(i.statementallocations.reduce((n,{amount}) => n + amount, 0)),
      openSum: (Number(getDocumentSum(i)) - Number(i.statementallocations.reduce((n,{amount}) => n + amount, 0))).toFixed(2)
    }
  })

  console.log(openDocuments.value)

  allocatedDocuments.value = documents.filter(i => i.statementallocations.find(x => x.bs_id === itemInfo.value.id))
  console.log(allocatedDocuments.value)
  openIncomingInvoices.value = (await useSupabaseSelect("incominginvoices","*, statementallocations(*)")).filter(i => i.statementallocations.length === 0 || i.statementallocations.find(x => x.bs_id === itemInfo.value.id))
  //console.log(openIncomingInvoices.value)

  //        return incominginvoices.value.filter(i => bankstatements.value.filter(x => x.assignments.find(y => y.type === 'incomingInvoice' && y.id === i.id)).length === 0)


  let allocations = (await supabase.from("createddocuments").select(`*, statementallocations(*)`).eq("id",50)).data



}

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

const separateIBAN = (input)  => {
  const separates = input.match(/.{1,4}/g)
  return separates.join(" ")
}

const getDocumentSum = (doc) => {
  let sum = 0
  doc.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
}

const getInvoiceSum = (invoice) => {
  let sum = 0
  invoice.accounts.forEach(account => {
    sum += account.amountTax
    sum += account.amountNet
  })
  return sum.toFixed(2)
}

const calculateOpenSum = computed(() => {
    let startingAmount = itemInfo.value.amount || 0

    itemInfo.value.statementallocations.forEach(item => {
      if(item.cd_id) {
        startingAmount = startingAmount - item.amount
      } else if(item.ii_id) {
        startingAmount = Number(startingAmount) + item.amount
      }
    })

    return startingAmount.toFixed(2)
})

const calculateAllocatedSum = computed(() => {
  let startingAmount = 0

  itemInfo.value.statementallocations.forEach(item => {
    console.log(item)

    if(item.cd_id) {
      startingAmount = startingAmount + item.amount
    } else if(item.ii_id) {
      startingAmount = Number(startingAmount) + item.amount
    }
  })

  return startingAmount

})

const saveAllocations = async () =>  {
  let allocationsToBeSaved = itemInfo.value.statementallocations.filter(i => !i.id)

  for await (let i of allocationsToBeSaved) {
    await dataStore.createNewItem("statementallocations", i)
  }


}

const saveAllocation = async (allocation) => {
  const {data,error} = await supabase.from("statementallocations").insert({
    ...allocation,
    tenant: profileStore.currentTenant
  }).select()

  if(data) {
    await setup()
  }

}

const removeAllocation = async (allocationId) => {
  const {data,error} = await supabase.from("statementallocations").delete().eq("id",allocationId)

  await setup()
}

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


  return useSearch(searchString.value, openDocuments.value)

})


setup()

</script>

<template>
  <UDashboardNavbar
      :ui="{center: 'flex items-stretch gap-1.5 min-w-0'}"
  >
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.push(`/banking`)"
      >
        Kontobewegungen
      </UButton>
    </template>
    <template #center>
      <h1
          :class="['text-xl','font-medium', Number(calculateOpenSum) === 0 ? ['text-primary-500'] : ['text-rose-600']]"
      >Kontobewegung bearbeiten</h1>
    </template>
    <template #right>
<!--      <UButton
          v-if="mode === 'edit'"
          @click="saveAllocations"
      >
        Speichern
      </UButton>-->
      <!--<UButton
          v-else-if="mode === 'create'"
          @click="dataStore.createNewItem('customers',itemInfo)"
      >
        Erstellen
      </UButton>
      <UButton
          @click="cancelEditorCreate"
          color="red"
          class="ml-2"
          v-if="mode === 'edit' || mode === 'create'"
      >
        Abbrechen
      </UButton>
      <UButton
          v-if="mode === 'show'"
          @click="editItem"
      >
        Bearbeiten
      </UButton>-->
    </template>
    <template #badge v-if="itemInfo">
      <UBadge
          v-if="itemInfo.incomingInvoice || itemInfo.createdDocument"
      >
        Gebucht
      </UBadge>
      <UBadge
          v-else
          color="red"
      >
        Offen
      </UBadge>
    </template>
  </UDashboardNavbar>

  <UDashboardPanelContent
    class="flex flex-row"
  >
    <UCard
        class="w-2/5 mx-auto mt-5"
        v-if="itemInfo"
    >
      <template #header>
        <div class="flex flex-row justify-between">
        <span
            v-if="itemInfo.amount > 0"
            class="text-base font-semibold leading-6 text-gray-900 dark:text-white"
        >
            {{itemInfo.debName}}
          </span>
          <span
              v-else-if="itemInfo.amount < 0"
              class="text-base font-semibold leading-6 text-gray-900 dark:text-white"
          >
            {{itemInfo.credName}}
          </span>


          <span v-if="itemInfo.amount > 0" class="text-primary-500 font-semibold text-nowrap">{{displayCurrency(itemInfo.amount)}}</span>
          <span v-else-if="itemInfo.amount < 0" class="text-rose-600 font-semibold text-nowrap">{{displayCurrency(itemInfo.amount)}}</span>
          <span v-else>{{displayCurrency(itemInfo.amount)}}</span>
        </div>
      </template>

      <table class="w-full" v-if="itemInfo.id">
        <tbody>
          <tr class="flex-row flex justify-between">
            <td>
              <span class="font-semibold">Buchungsdatum:</span>
            </td>
            <td>
              {{dayjs(itemInfo.date).format("DD.MM.YYYY")}}
            </td>
          </tr>
          <tr class="flex-row flex justify-between">
            <td>
              <span class="font-semibold">Wertstellungsdatum:</span>
            </td>
            <td>
              {{dayjs(itemInfo.valueDate).format("DD.MM.YYYY")}}
            </td>
          </tr>
          <tr class="flex-row flex justify-between text-right">
            <td>
              <span class="font-semibold">Partner:</span>
            </td>
            <td>
              {{itemInfo.amount > 0 ? itemInfo.debName : itemInfo.credName}}

            </td>
          </tr>
          <tr class="flex-row flex justify-between">
            <td>
              <span class="font-semibold">Partner IBAN:</span>
            </td>
            <td>
              {{itemInfo.amount > 0 ? separateIBAN(itemInfo.debIban) : separateIBAN(itemInfo.credIban)}}
            </td>
          </tr>
          <tr class="flex-row flex justify-between">
            <td>
              <span class="font-semibold">Konto:</span>
            </td>
            <td>
              {{dataStore.getBankAccountById(itemInfo.account) ? dataStore.getBankAccountById(itemInfo.account).name || separateIBAN(dataStore.getBankAccountById(itemInfo.account).iban) : ""}}
            </td>
          </tr>
          <tr class="flex-row flex justify-between">
            <td colspan="2">
              <span class="font-semibold">Verknüpfte Dokumente:</span>
            </td>
          </tr>
          <tr
              class="flex-row flex justify-between mb-3"
              v-for="item in itemInfo.statementallocations"
          >

            <td>
              <!--            <span v-if="itemInfo.createdDocument"><nuxt-link :to="`/createDocument/show/${itemInfo.createdDocument}`">{{dataStore.createddocuments.find(i => i.id === itemInfo.createdDocument).documentNumber}}</nuxt-link></span>
                          <span v-else-if="itemInfo.incomingInvoice"><nuxt-link :to="`/incominInvoices/show/${itemInfo.incomingInvoice}`">{{dataStore.getIncomingInvoiceById(itemInfo.incomingInvoice).reference}}</nuxt-link></span>-->
              <span v-if="item.cd_id">
                {{dataStore.getCreatedDocumentById(item.cd_id).documentNumber}}
              </span>
              <span v-else-if="item.ii_id">
                {{dataStore.getVendorById(dataStore.getIncomingInvoiceById(item.ii_id).vendor).name}} - {{dataStore.getIncomingInvoiceById(item.ii_id).reference}}
              </span>
            </td>
            <td>
              <UButton
                  variant="outline"
                  icon="i-heroicons-arrow-right-end-on-rectangle"
                  @click="router.push(`/createDocument/show/${item.cd_id}`)"
                  v-if="item.cd_id"
              />
              <UButton
                  variant="outline"
                  icon="i-heroicons-arrow-right-end-on-rectangle"
                  @click="router.push(`/incominginvoices/show/${item.ii_id}`)"
                  v-else-if="item.ii_id"
              />
            </td>
          </tr>
          <tr class="flex-row flex justify-between">
            <td colspan="2">
              <span class="font-semibold">Beschreibung:</span>
            </td>
          </tr>
          <tr>
            <td colspan="2">
              {{itemInfo.text}}
            </td>
          </tr>
        </tbody>

      </table>

    </UCard>

<!--    <UDivider
        class="mt-5 w-2/5 mx-auto"
        v-if="!itemInfo.createdDocument && !itemInfo.incomingInvoice"
    />-->

    <div
        class="w-2/5 mx-auto"
        v-if="itemInfo.amount > 0 "
    >

      <UDivider v-if="allocatedDocuments.length > 0">
        <span>Zugewiesene Summe: {{displayCurrency(calculateAllocatedSum)}}</span>
      </UDivider>
      <UCard
          class="mt-5"
          :ui="{ring: itemInfo.statementallocations.find(i => i.cd_id === document.id) ? 'ring-primary-500' : 'ring-gray-200 dark:ring-gray-800'}"
          v-for="document in allocatedDocuments"
      >
        <template #header>
          <div class="flex flex-row justify-between">
            <span>{{document.customer ? document.customer.name : ""}} - {{document.documentNumber}}</span>
            <span class="font-semibold text-primary-500 text-nowrap">{{displayCurrency(getDocumentSum(document))}}</span>
          </div>
        </template>
        <UButton
            icon="i-heroicons-check"
            variant="outline"
            class="mr-3"
            v-if="!itemInfo.statementallocations.find(i => i.cd_id === document.id)"
            @click="saveAllocation({cd_id: document.id, bs_id: itemInfo.id, amount: Number(getDocumentSum(document))})"
        />
        <UButton
            icon="i-heroicons-x-mark"
            variant="outline"
            color="rose"
            class="mr-3"
            v-if="itemInfo.statementallocations.find(i => i.cd_id === document.id)"
            @click="removeAllocation(itemInfo.statementallocations.find(i => i.cd_id === document.id).id)"
        />

        <UButton
            variant="outline"
            icon="i-heroicons-arrow-right-end-on-rectangle"
            @click="router.push(`/createDocument/show/${document.id}`)"
        />
      </UCard>
      <UDivider class="mt-3">
        <span>Offene Summe: {{displayCurrency(calculateOpenSum)}}</span>
      </UDivider>
      <UInput
          id="searchinput"
          v-model="searchString"
          icon="i-heroicons-funnel"
          autocomplete="off"
          placeholder="Suche..."
          class="hidden lg:block mt-3"
          @keydown.esc="$event.target.blur()"
      >
        <template #trailing>
          <UKbd value="/" />
        </template>
      </UInput>
      <UCard
          class="mt-5"
          :ui="{ring: itemInfo.statementallocations.find(i => i.cd_id === document.id) ? 'ring-primary-500' : 'ring-gray-200 dark:ring-gray-800'}"
          v-for="document in filteredRows"
      >
        <template #header>
          <div class="flex flex-row justify-between">
            <span>{{document.customer ? document.customer.name : ""}} - {{document.documentNumber}}</span>
            <span class="font-semibold text-primary-500 text-nowrap">{{displayCurrency(document.openSum)}}</span>
          </div>
        </template>
        <UButton
            icon="i-heroicons-check"
            variant="outline"
            class="mr-3"
            v-if="!itemInfo.statementallocations.find(i => i.cd_id === document.id)"
            @click="saveAllocation({cd_id: document.id, bs_id: itemInfo.id, amount: Number(itemInfo.amount)})"
        />
        <UButton
            icon="i-heroicons-x-mark"
            variant="outline"
            color="rose"
            class="mr-3"
            v-if="itemInfo.statementallocations.find(i => i.cd_id === document.id)"
            @click="removeAllocation(itemInfo.statementallocations.find(i => i.ii_id === document.id).id)"
        />

        <UButton
            variant="outline"
            icon="i-heroicons-arrow-right-end-on-rectangle"
            @click="router.push(`/createDocument/show/${document.id}`)"
        />
      </UCard>

    </div>
    <div
        class="w-2/5 mx-auto"
        v-if="itemInfo.amount < 0 "
    >
      <UDivider>
        <span>Offene Summe: {{displayCurrency(calculateOpenSum)}}</span>
      </UDivider>
      <UCard
          class="mt-5"
          :ui="{ring: /*itemInfo.assignments.find(i => i.id === invoice.id)*/ false ? 'ring-primary-500' : 'ring-gray-200 dark:ring-gray-800'}"
          v-for="item in openIncomingInvoices"
      >
        <template #header>
          <div class="flex flex-row justify-between">
            <span>{{dataStore.getVendorById(item.vendor).name}} - {{item.reference}}</span>
            <span class="font-semibold text-rose-600 text-nowrap">-{{displayCurrency(getInvoiceSum(item))}}</span>
          </div>
        </template>
        <UButton
            icon="i-heroicons-check"
            variant="outline"
            class="mr-3"
            v-if="!itemInfo.statementallocations.find(i => i.ii_id === item.id)"
            @click="saveAllocation({ii_id: item.id, bs_id: itemInfo.id, amount: Number(itemInfo.amount)})"
        />
        <UButton
            icon="i-heroicons-x-mark"
            variant="outline"
            color="rose"
            class="mr-3"
            v-if="itemInfo.statementallocations.find(i => i.ii_id === item.id)"
            @click="removeAllocation(itemInfo.statementallocations.find(i => i.ii_id === item.id).id)"
        />
        <UButton
            variant="outline"
            icon="i-heroicons-arrow-right-end-on-rectangle"
            @click="router.push(`/incominginvoices/show/${item.id}`)"
        />

      </UCard>
    </div>
  </UDashboardPanelContent>
</template>

<style scoped>

</style>