<script setup>

import dayjs from "dayjs";
import {useSum} from "~/composables/useSum.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
  },
  platform: {
    type: String,
    required: true
  }
})

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

const router = useRouter()
const deliveryNoteLikeDocumentTypes = ['deliveryNotes', 'packingSlips']

const createddocuments = ref([])

const setup = async () => {
  createddocuments.value = (await useEntities("createddocuments").select()).filter(i => !i.archived)
}
setup()

const templateColumns = [
  {
    key: "reference",
    label: "Referenz"


  },
  {
    key: 'type',
    label: "Typ"
  },{
    key: 'state',
    label: "Status"
  },{
    key: 'amount',
    label: "Betrag"
  },
  {
    key: "date",
    label: "Datum"
  },
  {
    key: "dueDate",
    label: "Fällig"
  }
]
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&loadMode=deliveryNotes&linkedDocuments=[${props.item.createddocuments.filter(i => deliveryNoteLikeDocumentTypes.includes(i.type)).map(i => i.id)}]`)
}

const showFinalInvoiceConfig = ref(false)
const referenceDocument = ref(null)
const advanceInvoicesToAdd = ref([])
const invoiceAdvanceInvoices = () => {
  router.push(`/createDocument/edit?type=invoices&loadMode=finalInvoice&linkedDocuments=[${[referenceDocument.value, ... advanceInvoicesToAdd.value]}]`)
}

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}`)
  }
}

</script>

<template>
  <UCard class="mt-5" :style="props.platform !== 'mobile' ? 'height: 80vh' : ''">
    <template #header v-if="props.platform === 'mobile'">
      <span>Ausgangsbelege</span>
    </template>
    <Toolbar>
      <!-- TODO Rendering when Screen is too small      -->
      <UButton
          @click="invoiceDeliveryNotes"
          v-if="props.topLevelType === 'projects'"
      >
        Lieferscheine/Packscheine abrechnen
      </UButton>
      <UButton
          @click="router.push(`/createDocument/edit/?${getAvailableQueryStringData({type: 'quotes'})}`)"
      >
        + Angebot
      </UButton>
      <UButton
          @click="router.push(`/createDocument/edit/?${getAvailableQueryStringData({type: 'costEstimates'})}`)"
      >
        + Kostenschätzung
      </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: 'packingSlips'})}`)"
      >
        + Packschein
      </UButton>
      <UButton
          @click="router.push(`/createDocument/edit/?${getAvailableQueryStringData({type: 'advanceInvoices'})}`)"
      >
        + Abschlagsrechnung
      </UButton>
      <UButton
          @click="showFinalInvoiceConfig = true"
          v-if="props.topLevelType === 'projects'"
          :disabled="!props.item.createddocuments?.filter(i => !i.archived && i.type === 'advanceInvoices').length > 0"
      >
        + Schlussrechnung
      </UButton>
      <UModal
          prevent-close
          v-model:open="showFinalInvoiceConfig"
      >
        <template #content>
          <UCard>
            <template #header>
              <div class="flex items-center justify-between">
                <h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
                  Schlussrechnung konfigurieren
                </h3>
                <UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1" @click="showFinalInvoiceConfig = false" />
              </div>
            </template>

            <UFormField
                label="Rechnungsvorlage"
            >
              <USelectMenu
                  :items="props.item.createddocuments.filter(i => ['confirmationOrders','quotes','costEstimates'].includes(i.type))"
                  value-key="id"
                  label-key="documentNumber"
                  v-model="referenceDocument"
              />
            </UFormField>

            <UFormField
                label="Abschlagsrechnungen"
            >
              <USelectMenu
                  :items="props.item.createddocuments.filter(i => ['advanceInvoices'].includes(i.type))"
                  multiple
                  value-key="id"
                  label-key="documentNumber"
                  v-model="advanceInvoicesToAdd"
              />
            </UFormField>

            <template #footer>
              <UButton
                  @click="invoiceAdvanceInvoices"
              >
                Weiter
              </UButton>
            </template>
          </UCard>
        </template>
      </UModal>
      <UButton
          @click="router.push(`/createDocument/edit/?${getAvailableQueryStringData({type: 'invoices'})}`)"
      >
        + Rechnung
      </UButton>

      <template #right>
        <USelectMenu
            v-model="selectedColumns"
            icon="i-heroicons-adjustments-horizontal-solid"
            :items="templateColumns"
            multiple
            class="hidden lg:block"
            by="key"
            @change="tempStore.modifyColumns('createddocuments',selectedColumns)"
        >
          <template #default>
            Spalten
          </template>
        </USelectMenu>
      </template>
    </Toolbar>
    <UTable
        :data="props.item.createddocuments.filter(i => !i.archived)"
        :columns="normalizeTableColumns(columns)"
        class="w-full"
        :ui="{ divide: 'divide-gray-200 dark:divide-gray-800' }"
        :on-select="(row) => selectItem(row.original)"
        style="height: 70vh"
    >
      <template #type-cell="{ row }">
        {{ dataStore.documentTypesForCreation[row.original.type].labelSingle }}
      </template>
      <template #state-cell="{ row }">
        <span
            v-if="row.original.state === 'Entwurf'"
            class="text-error-500"
        >
          {{ row.original.state }}
        </span>
        <span
            v-if="row.original.state === 'Gebucht'"
            class="text-cyan-500"
        >
          {{ row.original.state }}
        </span>
        <span
            v-if="row.original.state === 'Abgeschlossen'"
            class="text-primary-500"
        >
          {{ row.original.state }}
        </span>
      </template>
<!--      <template #paid-data="{row}">
        <div v-if="(row.type === 'invoices' ||row.type === 'advanceInvoices') && row.state === 'Gebucht'">
          <span v-if="useSum().getIsPaid(row,createddocuments)" class="text-primary-500">Bezahlt</span>
          <span v-else class="text-rose-600">Offen</span>
        </div>
      </template>-->
      <template #reference-cell="{ row }">
        <span v-if="row.original === props.item.createddocuments[selectedItem]" class="text-primary-500 font-bold">{{ row.original.documentNumber }}</span>
        <span v-else>{{ row.original.documentNumber }}</span>
      </template>
      <template #date-cell="{ row }">
        <span v-if="row.original.date">{{ row.original.date ? dayjs(row.original.date).format("DD.MM.YY") : '' }}</span>
        <span v-if="row.original.documentDate">{{ row.original.documentDate ? dayjs(row.original.documentDate).format("DD.MM.YY") : '' }}</span>
      </template>
      <template #dueDate-cell="{ row }">
        <span v-if="row.original.paymentDays && ['invoices','advanceInvoices'].includes(row.original.type)">{{ row.original.documentDate ? dayjs(row.original.documentDate).add(row.original.paymentDays,'day').format("DD.MM.YY") : '' }}</span>
      </template>
      <template #amount-cell="{ row }">
        <span v-if="!deliveryNoteLikeDocumentTypes.includes(row.original.type)">{{ useCurrency(useSum().getCreatedDocumentSum(row.original, createddocuments)) }}</span>
      </template>
      <template #empty>
        <TableEmptyState label="Keine Belege anzuzeigen" />
      </template>
    </UTable>


  </UCard>
</template>

<style scoped>

</style>
