<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 createddocuments = ref([])

const setup = async () => {
  //createddocuments.value = (await useSupabaseSelect("createddocuments")).filter(i => !i.archived)
  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: 'paid',
    label: "Bezahlt"
  },{
    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 => i.type === "deliveryNotes").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 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="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="showFinalInvoiceConfig"
      >
        <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="isOpen = false" />
            </div>
          </template>

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

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

          <template #footer>
            <UButton
                @click="invoiceAdvanceInvoices"
            >
              Weiter
            </UButton>
          </template>
        </UCard>
      </UModal>
      <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.filter(i => !i.archived)"
        :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' }"
        style="height: 70vh"
    >
      <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 #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-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>