<script setup>
const router = useRouter()
const route = useRoute()

definePageMeta({
  middleware: ['auth', 'org']
})

const pdfSrc = ref('')
const pdfPreview = async () => {
  const response = await $fetch('/api/orders/'+route.params.id+'/print/PDF', {
    headers: useRequestHeaders(['cookie'])
  })
  if(response) {
    const base64Response = await fetch(`data:application/pdf;base64,${response.reportFile}`);
    const blob = await base64Response.blob();
    pdfSrc.value = URL.createObjectURL(blob)
  }
}
onMounted(pdfPreview)

const printReport = async (fileType) => {
  const response = await $fetch('/api/orders/'+route.params.id+'/print/'+fileType, {
    headers: useRequestHeaders(['cookie'])
  })
  if(response) {
    let mimeType = ''
    let blob = new Blob([])
    if(fileType === 'PDF') {
      mimeType = 'application/pdf'
      const base64Response = await fetch(`data:${mimeType};base64,${response.reportFile}`);
      blob = await base64Response.blob();
    } else if(fileType === 'HTML') {
      mimeType = 'text/html'
      blob = new Blob([atob(response.exportFile)], {type: mimeType})
    } else if(fileType === 'CSV') {
      mimeType = 'text/csv'
      blob = new Blob([atob(response.exportFile)], {type: mimeType})
    } else if(fileType === 'XLSX') {
      mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      blob = new Blob([atob(response.exportFile)], {type: mimeType})
    } else if(fileType === 'XLS') {
      mimeType = 'application/vnd.ms-excel'//data:application/octet-stream;base64
      blob = new Blob([atob(response.exportFile)], {type: mimeType})
    }
    const blobUrl = URL.createObjectURL(blob)
    open(blobUrl, '_blank')
  }
}

const back = () => {
  router.push('/sales/fulfillment-orders')
}

const dropDownHandler = (e) => {
  if(e.target.parentElement.classList.contains('show')) {
    e.target.parentElement.classList.remove('show')
  } else {
    e.target.parentElement.classList.add('show')
  }
}

const dropItemHandler = (e) => {
  if(e.target.parentElement.parentElement.classList.contains('show')) {
    e.target.parentElement.parentElement.classList.remove('show')
  } else {
    e.target.parentElement.parentElement.classList.add('show')
  }
}

const breadCrumb = computed(() => ([
  { link: '#', text: 'Sales'},
  { link: '/sales/fulfillment-orders', text: 'Fulfillment Orders'},
  { link: '#', text: 'Order Preview', active: true}
]))
</script>

<template>
  <Head>
    <Title>Order Preview</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <div class="banner">
      <div class="p-1.5rem">
        <div class="d-flex justify-between mb-3">
          <h4></h4>
          <div class="d-flex gap-0.75rem">
            <div>
              <button type="button" @click="back" class="button">
                <span class="tf-icon ti ti-chevron-left ti-xs me-1 color-inherit"></span> Back
              </button>
            </div>
            <div class="dropDown">
              <button type="button" class="button dropDownToggler" @click="dropDownHandler">
                <span class="tf-icon ti ti-file-export ti-xs me-1 color-inherit"></span> Print Report
              </button>
              <div class="dropDownBackdrop" @click="dropDownHandler"></div>
              <div class="dropDownMenu dropDownRight">
                <span class="dropDownItem" @click="dropItemHandler($event); printReport('PDF');">Print Report in PDF</span>
                <span class="dropDownItem" @click="dropItemHandler($event); printReport('HTML');">Print Report in HTML</span>
                <span class="dropDownItem" @click="dropItemHandler($event); printReport('CSV');">Print Report in CSV</span>
                <span class="dropDownItem" @click="dropItemHandler($event); printReport('XLSX');">Print Report in XLSX</span>
                <span class="dropDownItem" @click="dropItemHandler($event); printReport('XLS');">Print Report in XLS</span>
              </div>
            </div>
          </div>
        </div>
        <div>
          <div class="my-5 mx-5">
            <ClientOnly v-if="pdfSrc !== ''">
              <PrintViewer :url="pdfSrc" />
            </ClientOnly>
          </div>
        </div>
      </div>

    </div>
  </NuxtLayout>
</template>