<script setup>

import dayjs from "dayjs";

definePageMeta({
  middleware: "auth"
})

defineShortcuts({
  '/': () => {
    //console.log(searchinput)
    //searchinput.value.focus()
    document.getElementById("searchinput").focus()
  },
  'escape': () => {
    //console.log(searchinput)
    //searchinput.value.focus()
    showStatementModal.value = false
  }
})

const dataStore = useDataStore()
const router = useRouter()
const supabase = useSupabaseClient()

const bankstatements = ref([])


const setupPage = async () => {
  bankstatements.value = (await supabase.from("bankstatements").select("*, statementallocations(*)").eq('tenant', dataStore.currentTenant).order("date", {ascending:false})).data

}



const selectedStatement = ref(null)
const showStatementModal = ref(false)

const templateColumns = [
  {
    key: "account",
    label: "Konto",
    sortable: true
  },{
    key: "valueDate",
    label: "Valuta",
    sortable: true
  },
  {
    key: "amount",
    label: "Betrag",
    sortable: true
  },
  {
    key: "openAmount",
    label: "Offener Betrag",
    sortable: true
  },
  {
    key: "partner",
    label: "Name",
    sortable: true
  },
  {
    key: "text",
    label: "Beschreibung",
    sortable: true
  }
]
const selectedColumns = ref(templateColumns)
const columns = computed(() => templateColumns.filter((column) => selectedColumns.value.includes(column)))


const searchString = ref('')
const filterAccount = ref(dataStore.bankAccounts || [])
const showOnlyNotAssigned = ref(true)

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

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 calculateOpenSum = (statement) => {
  let startingAmount = statement.amount || 0

  statement.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 filteredRows = computed(() => {
  return useSearch(searchString.value, bankstatements.value.filter(i => filterAccount.value.find(x => x.id === i.account) && (showOnlyNotAssigned.value ? Number(calculateOpenSum(i)) !== 0 : true)))
})

setupPage()
</script>

<template>
  <UDashboardNavbar title="Bankbuchungen">
    <template #right>
      <UInput
          id="searchinput"
          name="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>
    </template>
  </UDashboardNavbar>
  <UDashboardToolbar>
    <template #left>
      <USelectMenu
        :options="dataStore.bankAccounts"
        v-model="filterAccount"
        option-attribute="iban"
        multiple
        by="id"
      >
        <template #label>
          Konto
        </template>
      </USelectMenu>
      <UCheckbox
          v-model="showOnlyNotAssigned"
          class="my-auto ml-3"
          label="Nur offene anzeigen"
      />
    </template>
    <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>
    </template>
  </UDashboardToolbar>
  <UTable
      :rows="filteredRows"
      :columns="columns"
      class="w-full"
      :ui="{ divide: 'divide-gray-200 dark:divide-gray-800' }"
      @select="(i) => router.push(`/banking/statements/edit/${i.id}`)"
      :empty-state="{ icon: 'i-heroicons-circle-stack-20-solid', label: 'Keine Buchungen anzuzeigen' }"
  >

    <template #account-data="{row}">
      {{row.account ? (dataStore.getBankAccountById(row.account).name ? dataStore.getBankAccountById(row.account).name :dataStore.getBankAccountById(row.account).iban) : ""}}
    </template>
    <template #valueDate-data="{row}">
      {{dayjs(row.valueDate).format("DD.MM.YY")}}
    </template>
    <template #amount-data="{row}">
      <span
        v-if="row.amount >= 0"
        class="text-primary-500"
      >{{String(row.amount.toFixed(2)).replace(".",",")}} €</span>
      <span
        v-else-if="row.amount < 0"
        class="text-rose-500"
      >{{String(row.amount.toFixed(2)).replace(".",",")}} €</span>
    </template>
    <template #openAmount-data="{row}">
      {{displayCurrency(calculateOpenSum(row))}}
    </template>
    <template #partner-data="{row}">
      <span
        v-if="row.amount < 0"
      >
          {{row.credName}}
      </span>
      <span
        v-else-if="row.amount > 0"
      >
        {{row.debName}}
      </span>
    </template>
  </UTable>

  <UModal
    v-model="showStatementModal"
    class="no-doc-sroll"
  >

    <UCard class="h-full">
      <template #header>
        <div class="flex items-center justify-between">
          <span
              v-if="selectedStatement.amount > 0"
              class="text-base font-semibold leading-6 text-gray-900 dark:text-white"
          >
            {{selectedStatement.debName}}
          </span>
          <span
              v-else-if="selectedStatement.amount < 0"
              class="text-base font-semibold leading-6 text-gray-900 dark:text-white"
          >
            {{selectedStatement.credName}}
          </span>

          <UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1" @click="showStatementModal = false" />
        </div>
      </template>

      {{selectedStatement.id}}

      <div class="flex flex-row">
        <div class="w-1/2 truncate">
          <p>Betrag: {{String(selectedStatement.amount.toFixed(2)).replace(".",",")}} €</p>
          <p>Buchungsdatum: {{dayjs(selectedStatement.date).format("DD.MM.YYYY")}}</p>
          <p>Werstellungsdatum: {{dayjs(selectedStatement.valueDate).format("DD.MM.YYYY")}}</p>
          <p>Partner: {{selectedStatement.amount > 0 ? selectedStatement.debName : selectedStatement.credName}}</p>
          <p>Partner IBAN: {{selectedStatement.amount > 0 ? selectedStatement.debIban : selectedStatement.credIban}}</p>
          <p>Konto: {{selectedStatement.account}}</p>
          <p class="text-wrap">Beschreibung: <br>{{selectedStatement.text}}</p>
        </div>
        <div class="w-full p-2 overflow-scroll">
          <UCard
              v-for="document in dataStore.getOpenDocuments()"
          >


            {{document.documentNumber ||document.reference}}
            <!--        {{document}}-->
          </UCard>
        </div>
      </div>







<!--      <UFormGroup>
        <USelectMenu
          :options="dataStore.createddocuments"
        />
      </UFormGroup>-->



    </UCard>

  </UModal>
</template>



<style scoped>

</style>