<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('/procurements/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: 'Procurements'},
  { link: '/procurements/orders', text: 'Orders'},
  { link: '#', text: 'Order Preview', active: true}
]))
</script>

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

  <NuxtLayout name="app">
    <div>
      <BreadCrumb :items="breadCrumb" class="mb-1.5rem" />

      <div class="mb-5">
        <div class="d-flex justify-between mb-3">
          <h4 class="card-action-title">Order Preview</h4>
          <div class="card-action-element d-flex gap-0.75rem">
            <div>
              <button type="button" @click="back" class="btn btn-ms btn-secondary waves-effect waves-light">
                <span class="tf-icon ti ti-chevron-left ti-xs me-1"></span> Back
              </button>
            </div>
            <div class="dropDown">
              <button type="button" class="btn btn-ms btn-primary waves-effect waves-light dropDownToggler" @click="dropDownHandler">
                <span class="tf-icon ti ti-file-export ti-xs me-1"></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>