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

const config = useRuntimeConfig()
const user = useCookie('logship_user')
const { getMenuType } = useRoleMenu()

const props = defineProps({
  params: Object
})

const isFulCustomer = computed(() => getMenuType())

const attachmentQty = ref(0)
const attachments = ref([])

// Check if C_Order.M_Shipper_ID has IsAttachmentRequired = true
const isTargetShipper = computed(() => {
  return props?.params?.data?.isAttachmentRequired || false
})

// Check if C_Order.M_Shipper_ID has IsPrintDINA4 = 'Y'
const isPrintDINA4 = computed(() => {
  return props?.params?.data?.isPrintDINA4 || false
})

// Check if document is voided
const isVoided = computed(() => {
  return props?.params?.data?.DocStatus === 'VO'
})

const getAttachment = async () => {
  attachmentQty.value = 0
  attachments.value = []
  const getAttachmentRecord = await $fetch(`/api/attachments/C_Order/${props.params.data.id}`)
  if(getAttachmentRecord?.Strapi_Attachment_ID && getAttachmentRecord?.Strapi_Attachment_documentId) {
    const res = await $fetch(`/api/attachments/C_Order/${getAttachmentRecord.Strapi_Attachment_documentId}/files`, {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      attachmentQty.value = res?.length ?? 0
      attachments.value = res
    }
  }
}

const serverSidePrinting = async (content, type) => {
  let newUrl = '/api/print/'
  if(type === 'label') {
    newUrl = '/api/print/attachment-labels'
  }
  const res = await $fetch(newUrl, {
    method: 'POST',
    body: content
  })
  if(res) {
    if(res?.stdout) {
      toast({
        message: `The attachment has been printed via server side printing!`,
        type: 'is-success',
        duration: 2000
      })
    }
  }
}

const printInLabelSize = async (attachment) => {
  const response = await fetch(config.public.strapi+'/files-api/'+attachment.hash + attachment.ext);
  if(response) {
    const blob = await response.blob();
    const reader = new FileReader();
    reader.onloadend = () => {
      serverSidePrinting({
        pathName: `attachments/${new Date().getFullYear()}`,
        fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-'+attachment.documentId+'-')}-ATTACHMENTS-${user.value?.Name || 'SUPERUSER'}.pdf`,
        fileContent: reader.result.split(',')[1]
      }, 'label')
    }
    reader.onerror = (e) => {
      console.log(reader.error)
    }
    reader.readAsDataURL(blob);
  }
}

const printInNormalSize = async (attachment) => {
  const response = await fetch(config.public.strapi+'/files-api/'+attachment.hash + attachment.ext);
  if(response) {
    const blob = await response.blob();
    const reader = new FileReader();
    reader.onloadend = () => {
      serverSidePrinting({
        pathName: `attachments/${new Date().getFullYear()}`,
        fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-'+attachment.documentId+'-')}-ATTACHMENTS-${user.value?.Name || 'SUPERUSER'}.pdf`,
        fileContent: reader.result.split(',')[1]
      }, 'normal')
    }
    reader.onerror = (e) => {
      console.log(reader.error)
    }
    reader.readAsDataURL(blob);
  }
}

const handleClick = () => {
  if (attachmentQty.value > 0 && attachments.value.length > 0) {
    // Check if shipper requires normal size printing (DIN A4)
    if (isPrintDINA4.value) {
      toast({
        message: `Sending attachment to normal printer...`,
        type: 'is-info',
        duration: 2000
      })
      printInNormalSize(attachments.value[0])
    } else {
      toast({
        message: `Sending attachment to label printer...`,
        type: 'is-info',
        duration: 2000
      })
      printInLabelSize(attachments.value[0])
    }
  }
}

onMounted(getAttachment)
watch(() => props.params?.data?.id, getAttachment)
</script>

<template>
  <div class="d-inlineFlex items-center gap-5px">
    <div class="tags are-small">
      <span v-if="!isTargetShipper && attachmentQty > 0" class="tag is-rounded" :class="isFulCustomer !== 'c' ? 'cursor-pointer' : ''" style="margin-top: 3px; height: 19px; font-weight: bold; background-color: #d3d3d3 !important; color: #696969 !important;" @click="isFulCustomer !== 'c' ? handleClick() : null">
        <i v-if="isFulCustomer !== 'c'" style="font-size: 14px; color: #696969; margin-right: 5px;" class="ti ti-script"></i>{{ attachmentQty }} Files
      </span>
      <span v-if="isTargetShipper && attachmentQty > 0 && !isVoided" class="tag is-rounded" :class="isFulCustomer !== 'c' ? 'cursor-pointer' : ''" style="margin-top: 3px; height: 19px; font-weight: bold; background-color: #d4f8d4 !important; color: #2e7d32 !important;" @click="isFulCustomer !== 'c' ? handleClick() : null">
        <i v-if="isFulCustomer !== 'c'" style="font-size: 14px; color: #2e7d32; margin-right: 5px;" class="ti ti-script"></i>Label
      </span>
      <span v-if="isTargetShipper && attachmentQty === 0 && !isVoided" class="tag is-rounded" style="margin-top: 3px; height: 19px; font-weight: bold; background-color: #ffb6c1 !important; color: #db7093 !important;">
        <i v-if="isFulCustomer !== 'c'" style="font-size: 14px; color: #db7093; margin-right: 5px;" class="ti ti-ban"></i>Label
      </span>
    </div>
  </div>
</template>

<style scoped>
.tag {
  width: 40px;
  height: 20px;
}

.tag-base {
  margin-top: 3px;
  height: 19px;
  font-weight: bold;
}

.tag-file {
  background-color: lightgrey;
  color: dimgrey;
}

.tag-label-success {
  background-color: #d4f8d4 !important;
  color: #2e7d32 !important;
}

.tag-label-error {
  background-color: #ffcdd2 !important;
  color: #c62828 !important;
}


.tag-icon {
  font-size: 14px;
  margin-right: 5px;
}

.tag-file .tag-icon {
  color: dimgrey;
}

.tag-label-success .tag-icon {
  color: #2e7d32;
}

.tag-label-error .tag-icon {
  color: palevioletred;
}
</style>