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

const user = useCookie('logship_user')

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

const emit = defineEmits(['update:modelValue', 'edit', 'label', 'dhlLabel'])

const tab = ref('lists')
const tabs = ref([
  {value: 'lists', text: 'Lists'},
  {value: 'labels', text: 'Created Labels'},
  {value: 'dhl', text: 'DHL'},
  {value: 'other', text: 'Other'},
])

const parcels = ref([])
const dhlParcels = ref([])
const otherParcels = ref([])
const labels = ref([])
const retrieveParcels = async () => {
  const res = await $fetch('/api/commission/parcels')
  if(res?.parcels) {
    parcels.value = res.parcels.filter(i => !i.tracking_number || i.tracking_number === '')
    labels.value = res.parcels.filter(i => i.tracking_number !== '')
  }
}
onMounted(retrieveParcels)

const retrieveDHLParcels = async () => {
  const res = await $fetch('/api/commission/parcels/dhl/inouts')
  if(res?.records) {
    dhlParcels.value = res.records
  }
}
onMounted(retrieveDHLParcels)

const retrieveOtherParcels = async () => {
  const res = await $fetch('/api/commission/parcels/other/inouts')
  if(res?.records) {
    otherParcels.value = res.records
  }
}
onMounted(retrieveOtherParcels)

const showCommissionList = ref(props.modelValue || false)
const closeCommissionList = () => {
  showCommissionList.value = false
  emit('update:modelValue', showCommissionList.value)
}
watch(() => props.modelValue, () => {
  showCommissionList.value = props.modelValue
  retrieveParcels()
  retrieveDHLParcels()
  retrieveOtherParcels()
})

const edit = (item) => {
  emit('edit', {
    id: item.id,
    inOutId: item.external_reference,
    name: item.name,
    companyName: item.company_name,
    email: item.email,
    telephone: item.telephone,
    address: item.address_divided?.street || '',
    houseNumber: item.address_divided?.house_number ?? '',
    address2: item.address_2,
    city: item.city,
    country: item.country?.iso_2 || 'DE',
    countryName: item.country?.name || 'Germany',
    countryIso3: item.country?.iso_3 || 'DEU',
    postalCode: item.postal_code,
    countryState: item.country_state || '',
    toServicePoint: item.to_service_point || '',
    toPostNumber: item.to_post_number || '',
    customsInvoiceNR: item.customs_invoice_nr || '',
    customsShipmentType: item.customs_shipment_type || '',
    weight: item.weight,
    length: item.length,
    width: item.width,
    height: item.height,
    orderNumber: item.order_number,
    totalOrderValue: item.total_order_value,
    totalOrderValueCurrency: item.total_order_value_currency,
    shippingMethodCheckoutName: item.shipping_method_checkout_name,
    senderAddress: item.sender_address || 1,
    quantity: item.quantity || 1,
    totalInsuredValue: item.total_insured_value ?? 0,
    isReturn: item.is_return ?? false,
    requestLabel: item.request_label ?? false,
    applyShippingRules: item.apply_shipping_rules ?? false,
    requestLabelAsync: item.request_label_async ?? false,
    shipment: item.shipment?.name || item.shipping_method?.name || '', //'Unstamped letter'
    shipmentId: item.shipment?.id ?? item.shipping_method?.id ?? '', //8
    dateCreated: item.date_created,
    dateUpdated: item.date_updated,
    dateAnnounced: item.date_announced,
  })
  closeCommissionList()
}

const createLabel = async (item) => {
  if((item.shipment?.id ?? 8) != 8 && (item.shipment?.id ?? '') != '') {
    if(item.external_reference) {
      const res = await $fetch('/api/commission/labels', {
        method: 'POST',
        body: {
          id: item.id,
          inOutId: item.external_reference
        }
      })
      if(Number(res.status) === 200) {
        toast({
          message: 'Label has been created',
          type: 'is-success',
          duration: 2000
        })
        tab.value = 'labels'
        retrieveParcels()
        //emit('label', res)
      } else {
        toast({
          message: res.message || 'Save error',
          type: 'is-danger',
          duration: 2000
        })
      }
    } else {
      toast({
        message: 'InOut ID as External Reference is required',
        type: 'is-danger',
        duration: 2000
      })
    }
  } else {
    toast({
      message: 'Currently the default shipment method is Unstamped letter, the label cannot be created, please edit by choosing other shipment methods first!',
      type: 'is-warning',
      duration: 2000
    })
  }
}

const destroy = async (item) => {
  const res = await $fetch(`/api/commission/parcels/${item.id}/destroy`, {
    method: 'POST',
    body: {
      id: item.id,
      inOutId: item.external_reference
    }
  })
  if(res?.status) {
    toast({
      message: 'Parcel has been removed',
      type: 'is-success',
      duration: 2000
    })
    retrieveParcels()
  }
}

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 printServer = async (label) => {
  if(label?.id) {
    const res = await $fetch(`/api/commission/labels/${label.id}/pdf`)
    if(res) {
      const reader = new FileReader();
      reader.addEventListener('load', () => {
        serverSidePrinting({
          pathName: `label/${new Date().getFullYear()}`,
          fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-'+label.id+'-')}-LABEL-${user.value?.Name || 'SUPERUSER'}.pdf`,
          fileContent: reader.result?.replace('data:application/pdf;base64,', ''),
          shippingPrinter: props.shippingPrinter
        })
      })
      reader.readAsDataURL(res);
    }
  }
}

const printDHLServer = async (dhlParcel) => {
  if(dhlParcel?.DHL_Shipment_Code) {
    const resp = await $fetch(`/api/commission/parcels/dhl?shipment_code=${dhlParcel.DHL_Shipment_Code}`)
    serverSidePrinting({
      pathName: `label/${new Date().getFullYear()}`,
      fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-'+dhlParcel.DHL_Shipment_Code+'-')}-LABEL-${user.value?.Name || 'SUPERUSER'}.pdf`,
      fileContent: (resp?.items?.[0]?.label?.b64 ?? dhlParcel.DHL_Label_Base64)?.replace('data:application/pdf;base64,', ''),
      shippingPrinter: props.shippingPrinter
    })
  }
}

const destroyDHL = async (dhlParcel) => {
  const res = await $fetch(`/api/commission/parcels/dhl`, {
    method: 'PUT',
    body: {
      shipmentNo: dhlParcel.DHL_Shipment_Code,
      inOutId: dhlParcel.id
    }
  })
  if(res?.status) {
    toast({
      message: 'DHL Parcel has been removed',
      type: 'is-success',
      duration: 2000
    })
    retrieveDHLParcels()
  }
}

const destroyOther = async (otherParcel) => {
  const res = await $fetch(`/api/commission/parcels/other`, {
    method: 'PUT',
    body: {
      inOutId: otherParcel.id
    }
  })
  if(res?.status) {
    toast({
      message: 'Other Parcel has been removed',
      type: 'is-success',
      duration: 2000
    })
    retrieveOtherParcels()
  }
}
</script>

<template>
  <div class="modal" :class="{'active': showCommissionList}" :style="{display: showCommissionList ? '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 px-0.75rem pt-0.75rem gap-0.75rem w-100pct">
            <div class="tabs is-boxed" style="margin-bottom: 0px;width: 100%;">
              <ul>
                <li v-for="(item, index) in tabs" :class="{'is-active': tab === item.value}">
                  <a @click="tab = item.value">
                    <span :class="{'fg-hex999': tab === item.value}">{{ item.text }}</span>
                  </a>
                </li>
              </ul>
            </div>
            <div class="cursor-pointer" @click="closeCommissionList">
              <span class="tf-icon ti ti-x ti-sm me-1"></span>
            </div>
          </div>
        </div>
        <div class="modalBody mnh-450px p-0px">
          <template v-if="tab === 'lists'">
            <div class="tableResponsive">
              <table class="table tableList tableFlush">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Company</th>
                    <th>Country</th>
                    <th>Date</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(parcel, index) in parcels" :key="index">
                    <td class="verticalAlignMiddle">{{ parcel.name }}</td>
                    <td class="verticalAlignMiddle">{{ parcel.company_name }}</td>
                    <td class="verticalAlignMiddle">{{ parcel.country.name }}</td>
                    <td class="verticalAlignMiddle">{{ parcel.date_created }}</td>
                    <td class="verticalAlignMiddle textAlignRight">
                      <div class="d-flex justifyContent-flexEnd gap-5px">
                        <span @click="edit(parcel)" class="cursor-pointer" title="Edit">
                          <i class="menu-icon tf-icons ti ti-pencil"></i>
                        </span>
                        <template v-if="parcel?.shipping_method?.id || parcel?.shipment?.id">
                          <span @click="createLabel(parcel)" class="cursor-pointer" title="Create Label">
                            <i class="menu-icon tf-icons ti ti-tag"></i>
                          </span>
                          <span class="cursor-pointer" title="Create Shipping List">
                            <i class="menu-icon tf-icons ti ti-checklist"></i>
                          </span>
                          <span class="cursor-pointer" title="Create Shipping Slip">
                            <i class="menu-icon tf-icons ti ti-file-check"></i>
                          </span>
                        </template>
                        <span @click="destroy(parcel)" class="cursor-pointer" title="Delete">
                          <i class="menu-icon tf-icons ti ti-trash"></i>
                        </span>
                        <!--<span class="cursor-pointer fg-warning">
                          <i v-if="entry?.show" class="menu-icon tf-icons ti ti-chevron-up"></i>
                          <i v-else class="menu-icon tf-icons ti ti-chevron-down"></i>
                        </span>-->
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </template>
          <template v-else-if="tab === 'labels'">
            <div class="tableResponsive">
              <table class="table tableList tableFlush">
                <thead>
                  <tr>
                    <th>Tracking No</th>
                    <th>Name</th>
                    <th>Country</th>
                    <th>Date</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(label, index) in labels" :key="index">
                    <td class="verticalAlignMiddle">{{ label.tracking_number }}</td>
                    <td class="verticalAlignMiddle">{{ label.name }} - {{ label.company_name }}</td>
                    <td class="verticalAlignMiddle">{{ label.country.name }}</td>
                    <td class="verticalAlignMiddle">{{ label.date_announced }}</td>
                    <td class="verticalAlignMiddle textAlignRight">
                      <div class="d-flex justifyContent-flexEnd gap-5px">
                        <span @click="emit('label', label)" class="cursor-pointer" title="Print Label">
                          <i class="menu-icon tf-icons ti ti-printer"></i>
                        </span>
                        <span @click="printServer(label)" class="cursor-pointer" title="Print Server Side Label">
                          <i class="menu-icon tf-icons ti ti-shredder"></i>
                        </span>
                        <!--<span class="cursor-pointer" title="Return Parcel">
                          <i class="menu-icon tf-icons ti ti-truck-return"></i>
                        </span>-->
                        <span @click="destroy(label)" class="cursor-pointer" title="Cancel">
                          <i class="menu-icon tf-icons ti ti-playstation-x"></i>
                        </span>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </template>
          <template v-else-if="tab === 'dhl'">
            <div class="tableResponsive">
              <table class="table tableList tableFlush">
                <thead>
                  <tr>
                    <th>Shipment No</th>
                    <th>Routing Code</th>
                    <th>Name</th>
                    <th>Country</th>
                    <th>Date</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(dhlParcel, index) in dhlParcels" :key="index">
                    <td class="verticalAlignMiddle">{{ dhlParcel.DHL_Shipment_Code }}</td>
                    <td class="verticalAlignMiddle">{{ dhlParcel.DHL_Routing_Code }}</td>
                    <td class="verticalAlignMiddle">{{ dhlParcel.C_BPartner_ID.identifier }}</td>
                    <td class="verticalAlignMiddle">{{ dhlParcel.C_BPartner_Location_ID?.C_Location_ID?.C_Country_ID?.identifier ?? '' }}</td>
                    <td class="verticalAlignMiddle">{{ dhlParcel.shipping_date }}</td>
                    <td class="verticalAlignMiddle textAlignRight">
                      <div class="d-flex justifyContent-flexEnd gap-5px">
                        <span @click="emit('dhlLabel', dhlParcel)" class="cursor-pointer" title="Print Label">
                          <i class="menu-icon tf-icons ti ti-printer"></i>
                        </span>
                        <span @click="printDHLServer(dhlParcel)" class="cursor-pointer" title="Print Server Side Label">
                          <i class="menu-icon tf-icons ti ti-shredder"></i>
                        </span>
                        <span @click="destroyDHL(dhlParcel)" class="cursor-pointer" title="Cancel">
                          <i class="menu-icon tf-icons ti ti-playstation-x"></i>
                        </span>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </template>
          <template v-else-if="tab === 'other'">
            <div class="tableResponsive">
              <table class="table tableList tableFlush">
                <thead>
                  <tr>
                    <th>Tracking No</th>
                    <th>Name</th>
                    <th>Country</th>
                    <th>Date</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(otherParcel, index) in otherParcels" :key="index">
                    <td class="verticalAlignMiddle">{{ otherParcel.TrackingNo }}</td>
                    <td class="verticalAlignMiddle">{{ otherParcel.C_BPartner_ID.identifier }}</td>
                    <td class="verticalAlignMiddle">{{ otherParcel.C_BPartner_Location_ID?.C_Location_ID?.C_Country_ID?.identifier ?? '' }}</td>
                    <td class="verticalAlignMiddle">{{ otherParcel.shipping_date }}</td>
                    <td class="verticalAlignMiddle textAlignRight">
                      <div class="d-flex justifyContent-flexEnd gap-5px">
                        <span @click="destroyOther(otherParcel)" class="cursor-pointer" title="Cancel">
                          <i class="menu-icon tf-icons ti ti-playstation-x"></i>
                        </span>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </template>
        </div>
        <div class="modalFooter">
          <div></div>
          <div class="d-flex items-center gap-10px">
            <button type="button" class="button" @click="closeCommissionList">Close</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>