<script setup>

import dayjs from "dayjs";
import {useSum} from "~/composables/useSum.js";
import {useSupabaseSelect} from "~/composables/useSupabase.js";
defineShortcuts({
  /*'/': () => {
    //console.log(searchinput)
    //searchinput.value.focus()
    document.getElementById("searchinput").focus()
  },*/
  'Enter': {
    usingInput: true,
    handler: () => {
      router.push(`/standardEntity/${props.topLevelType}/show/${props.item.createddocuments.value[selectedItem.value].id}`)
    }
  },
  'arrowdown': () => {
    if(selectedItem.value < props.item.createddocuments.length - 1) {
      selectedItem.value += 1
    } else {
      selectedItem.value = 0
    }
  },
  'arrowup': () => {
    if(selectedItem.value === 0) {
      selectedItem.value = props.item.createddocuments.length - 1
    } else {
      selectedItem.value -= 1
    }
  }
})

const props = defineProps({
  queryStringData: {
    type: String
  },
  item: {
    type: Object,
    required: true
  },
  type: {
    type: String,
    required: true
  },
  topLevelType: {
    type: String,
    required: true
  }
})

const dataStore = useDataStore()
const tempStore = useTempStore()

const router = useRouter()

const createddocuments = ref([])

const setup = async () => {
  createddocuments.value = await useSupabaseSelect("createddocuments")
}
setup()

const templateColumns = [
  {
    key: "reference",
    label: "Referenz",
    sortable: true
  },
  {
    key: 'type',
    label: "Typ",
    sortable: true
  },{
    key: 'state',
    label: "Status",
    sortable: true
  },
  {
    key: "date",
    label: "Datum",
    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 selectedItem = ref(0)

const getAvailableQueryStringData = (keys) => {
  let returnString = props.queryStringData

  function addParam (key,value) {
    if(returnString.length  === 0) {
      returnString += `${key}=${value}`
    } else {
      returnString += `&${key}=${value}`

    }
  }

  if(keys) {
    Object.keys(keys).forEach(key => {
      addParam(key, keys[key])
    })
  }

  return returnString

}

const invoiceDeliveryNotes = () => {
  router.push(`/createDocument/edit?type=invoices&linkedDocuments=[${props.item.createddocuments.filter(i => i.type === "deliveryNotes").map(i => i.id)}]`)
}


</script>

<template>
  <UCard class="mt-5" style="height: 80vh">
    <Toolbar>
      <UButton
          @click="invoiceDeliveryNotes"
          v-if="props.topLevelType === 'projects'"
      >
        Lieferscheine abrechnen
      </UButton>
      <UButton
          @click="router.push(`/createDocument/edit/?${getAvailableQueryStringData({type: 'quotes'})}`)"
      >
        + Angebot
      </UButton>
      <UButton
          @click="router.push(`/createDocument/edit/?${getAvailableQueryStringData({type: 'confirmationOrders'})}`)"
      >
        + Auftragsbestätigung
      </UButton>
      <UButton
          @click="router.push(`/createDocument/edit/?${getAvailableQueryStringData({type: 'deliveryNotes'})}`)"
      >
        + Lieferschein
      </UButton>
      <UButton
          @click="router.push(`/createDocument/edit/?${getAvailableQueryStringData({type: 'advanceInvoices'})}`)"
      >
        + Abschlagsrechnung
      </UButton>
      <UButton
          @click="router.push(`/createDocument/edit/?${getAvailableQueryStringData({type: 'invoices'})}`)"
      >
        + Rechnung
      </UButton>

      <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>
      </template>
    </Toolbar>

    <UTable
        :rows="props.item.createddocuments"
        :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}}
      </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 #reference-data="{row}">
        <span v-if="row === props.item.createddocuments[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.paymentDays && ['invoices','advanceInvoices'].includes(row.type)" >{{row.documentDate ? dayjs(row.documentDate).add(row.paymentDays,'day').format("DD.MM.YY") : ''}}</span>
      </template>
<!--      <template #amount-data="{row}">
        <span v-if="row.type !== 'deliveryNotes'">{{useCurrency(useSum().getCreatedDocumentSum(row, createddocuments))}}</span>
      </template>-->
    </UTable>

  </UCard>
</template>

<style scoped>

</style>