<script setup>
import { date, string } from 'alga-js'
import { toast } from 'bulma-toast'

const user = useCookie('logship_user')

const props = defineProps({
  modelValue: Boolean,
  parcel: Object,
  shippingPrinter: String
})

const emit = defineEmits(['update:modelValue'])

const pdfContent = ref('')
const getPDFLabel = async () => {
  if(props.parcel?.DHL_Shipment_Code) {
    const resp = await $fetch(`/api/commission/parcels/dhl?shipment_code=${props.parcel.DHL_Shipment_Code}`)
    const base64Response = await fetch(`data:application/pdf;base64,${resp?.items?.[0]?.label?.b64 ?? props.parcel.DHL_Label_Base64}`);
    const blob = await base64Response.blob();
    pdfContent.value = URL.createObjectURL(blob)
  }
}
watch(() => props.parcel, getPDFLabel)

const showCommissionLabel = ref(props.modelValue || false)
const closeCommissionLabel = () => {
  showCommissionLabel.value = false
  pdfContent.value = ''
  emit('update:modelValue', showCommissionLabel.value)
}
watch(() => props.modelValue, () => {
  showCommissionLabel.value = props.modelValue
  getPDFLabel()
})

const serverSidePrinting = async (content) => {
  const res = await $fetch('/api/print/labelprint', {
    method: 'POST',
    body: content
  })
  if(res) {
    //console.log(res)
    if(res?.stdout) {
      toast({
        message: 'The label has been printed via server side printing!',
        type: 'is-success',
        duration: 2000
      })
    }
  }
}
const printCommissionLabel = async () => {
  if(props.parcel?.DHL_Shipment_Code) {
    const resp = await $fetch(`/api/commission/parcels/dhl?shipment_code=${props.parcel.DHL_Shipment_Code}`)
    serverSidePrinting({
      pathName: `label/${new Date().getFullYear()}`,
      fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-'+props.parcel.DHL_Shipment_Code+'-')}-LABEL-${user.value?.Name || 'SUPERUSER'}.pdf`,
      fileContent: (resp?.items?.[0]?.label?.b64 ?? props.parcel.DHL_Label_Base64)?.replace('data:application/pdf;base64,', ''),
      shippingPrinter: props.shippingPrinter
    })
  }
}
</script>

<template>
  <div class="modal" :class="{'active': showCommissionLabel}" :style="{display: showCommissionLabel ? 'block' : 'none'}">
    <div class="modalDialog modalCenter modalPrintPreview">
      <div class="modalContent">
        <div class="modalHeader modalHeaderNoPad">
          <div class="d-flex justify-between items-center bb-1px_solid_hexe2e2e2 p-0.75rem gap-0.75rem w-100pct">
            <h3 class="modalTitle">Print Label</h3>
            <div class="cursor-pointer" @click="closeCommissionLabel">
              <span class="tf-icon ti ti-x ti-sm me-1"></span>
            </div>
          </div>
        </div>
        <div v-if="pdfContent" class="modalBody mnh-450px p-0px">
          <ClientOnly v-if="pdfContent !== ''">
            <PrintViewer :url="pdfContent" />
          </ClientOnly>
        </div>
        <div class="modalFooter">
          <div></div>
          <div class="d-flex items-center gap-10px">
            <button type="button" class="button" @click="closeCommissionLabel">Close</button>
            <button type="button" class="button" @click="printCommissionLabel">Print Server</button>
            <a :href="pdfContent" download class="button">Download</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>