<script setup>
import CopyCreatedDocumentModal from "~/components/copyCreatedDocumentModal.vue";

definePageMeta({
  middleware: "auth"
})

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

const supabase = useSupabaseClient()
const modal = useModal()
const dataStore = useDataStore()
const profileStore = useProfileStore()
const route = useRoute()
const router = useRouter()

const itemInfo = ref({})
const linkedDocument =ref({})
const currentTenant = ref({})
const setupPage = async () => {
  if(route.params) {
    if(route.params.id) itemInfo.value = await useSupabaseSelectSingle("createddocuments",route.params.id,"*, files(*)")

    console.log(itemInfo.value)

    linkedDocument.value = await useFiles().selectDocument(itemInfo.value.files[0].id)



    //const {data,error} = await supabase.from("files").select("id").eq("createddocument", route.params.id).order("id",{ascending:true})
    //linkedDocument.value = data[data.length -1]

  }

  currentTenant.value = (await supabase.from("tenants").select().eq("id",profileStore.currentTenant).single()).data
  console.log(currentTenant.value)

}

setupPage()

const openEmail = () => {
  if(["invoices","advanceInvoices"].includes(itemInfo.value.type)){
    router.push(`/email/new?loadDocuments=["${linkedDocument.value.id}"]&bcc=${encodeURIComponent(currentTenant.value.standardEmailForInvoices)}`)
  } else {
    router.push(`/email/new?loadDocuments=["${linkedDocument.value.id}"]`)
  }
}
</script>

<template>
  <UDashboardNavbar
    title="Erstelltes Dokument anzeigen"
  >

  </UDashboardNavbar>
  <UDashboardToolbar>
    <template #left>
      <UButton
          @click="router.push(`/createDocument/edit/${itemInfo.id}`)"
          v-if="itemInfo.state === 'Entwurf'"
      >
        Bearbeiten
      </UButton>
<!--      <UButton
          :to="dataStore.documents.find(i => i.createdDocument === itemInfo.id) ? dataStore.documents.find(i => i.createdDocument === itemInfo.id).url : ''"
          target="_blank"
      >In neuen Tab anzeigen</UButton>-->
      <UButton
          icon="i-heroicons-arrow-right-end-on-rectangle"
          @click="modal.open(CopyCreatedDocumentModal, {
              id: itemInfo.id,
          })"
          variant="outline"
      >
        Kopieren
      </UButton>
<!--      <UTooltip
        text="Kopieren in Angebot"
      >
        <UButton
            icon="i-heroicons-arrow-right-end-on-rectangle"
            @click="router.push(`/createDocument/edit/?linkedDocument=${itemInfo.id}&type=quotes`)"
            variant="outline"
        >
          Angebot
        </UButton>
      </UTooltip>
      <UTooltip
        text="Kopieren in Auftragsbestätigung"
      >
        <UButton
            icon="i-heroicons-arrow-right-end-on-rectangle"
            @click="router.push(`/createDocument/edit/?linkedDocument=${itemInfo.id}&type=confirmationOrders`)"
            variant="outline"
        >
          Auftragsbestätigung
        </UButton>
      </UTooltip>
      <UTooltip
        text="Kopieren in Lieferschein"
      >
        <UButton
            icon="i-heroicons-arrow-right-end-on-rectangle"
            @click="router.push(`/createDocument/edit/?linkedDocument=${itemInfo.id}&type=deliveryNotes`)"
            variant="outline"
        >
          Lieferschein
        </UButton>
      </UTooltip>
      <UTooltip
        text="Kopieren in Abschlagsrechnung"
      >
        <UButton
            icon="i-heroicons-arrow-right-end-on-rectangle"
            @click="router.push(`/createDocument/edit/?linkedDocument=${itemInfo.id}&type=advanceInvoices`)"
            variant="outline"
        >
          Abschlagsrechnung
        </UButton>
      </UTooltip>
      <UTooltip
        text="Kopieren in Rechnung"
      >
        <UButton
            icon="i-heroicons-arrow-right-end-on-rectangle"
            @click="router.push(`/createDocument/edit/?linkedDocument=${itemInfo.id}&type=invoices`)"
            variant="outline"
        >
          Rechnung
        </UButton>
      </UTooltip>-->
      <UButton
        @click="openEmail"
        icon="i-heroicons-envelope"
      >
        E-Mail
      </UButton>
      <UButton
          @click="router.push(`/createDocument/edit/?linkedDocument=${itemInfo.id}&loadMode=storno`)"
          variant="outline"
          color="rose"
          v-if="itemInfo.type === 'invoices' || itemInfo.type === 'advanceInvoices'"
      >
        Stornieren
      </UButton>
      <UButton
          v-if="itemInfo.project"
        @click="router.push(`/standardEntity/projects/show/${itemInfo.project}`)"
        icon="i-heroicons-link"
          variant="outline"
      >
        Projekt
      </UButton>
      <UButton
          v-if="itemInfo.customer"
        @click="router.push(`/standardEntity/customers/show/${itemInfo.customer}`)"
        icon="i-heroicons-link"
          variant="outline"
      >
        Kunde
      </UButton>

    </template>
  </UDashboardToolbar>
  <UDashboardPanelContent>
    <object
        :data="linkedDocument.url"
        class="w-full previewDocumentMobile"
    />
  </UDashboardPanelContent>
</template>

<style scoped>
.previewDocumentMobile {
  aspect-ratio: 1 / 1.414;

}
</style>