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

const config = useRuntimeConfig()
const route = useRoute()
const user = useCookie('logship_user')

const searchRef = ref(null)
const searchNo = ref(route.query?.no ?? '')
const shipment = ref({})
const customerAddress = ref({})
const shippingMethod = ref({})
const shipmentData = ref([])
const shipmentLines = ref([])
const shipmentCart = ref([])
const showSuggestion = ref(false)
const paketTypes = ref({
  CODETEST: 1000001,
  // Paket Size S
  CODE: 1000204,
  CODE0: 1000204,
  CODE1: 1000204,
  // Paket Size M
  CODE2: 1000205,
  // Paket Size L
  CODE3: 1000206,
  // Paket Size XL
  CODE4: 1000213,
  CODE5: 1000857,
  CODE6: 1000911
})
const paketType = ref('')
const shippingService = ref('dhl') //sendcloud, other
const shippingPrinter = ref(
  typeof window !== 'undefined' && localStorage.getItem('shippingPrinter') 
    ? localStorage.getItem('shippingPrinter') 
    : 'labelprinter-1'
)
const searchNoHandler = async () => {
  showSuggestion.value = false

  if(searchNo.value !== '') {
    if(shipment.value?.M_Shipper_ID?.IsReadTrackingCommission == true && shipment.value?.M_Shipper_ID?.readtrackinglength == searchNo.value.length) {
      shipment.value.TrackingNo = searchNo.value
      setTimeout(() => {
        searchNo.value = ''
      }, 400)
    } else {
      if(Object.keys(paketTypes.value).includes(searchNo.value.toUpperCase())) {
        paketType.value = paketTypes.value[searchNo.value.toUpperCase()]
        searchNo.value = ''
      } else if(shipment.value?.id && !shipment.value?.IsCommissioned) {
        if(shipmentLines.value.length >= 1) {
          const newShipmentLines = shipmentLines.value.filter(i => i.M_Product_ID?.SKU === searchNo.value || i.M_Product_ID?.UPC === searchNo.value || i.M_Product_ID?.Value === searchNo.value)
          if(Number(newShipmentLines.length) === 1) {
            pickShipmentLine(newShipmentLines[0])
            searchNo.value = ''
          }
        }
      } else {
        const res = await $fetch('/api/filters/m_inout/'+string.urlEncode(`startswith(MovementType,'C') AND isActive eq true AND contains(DocumentNo,'${searchNo.value}') AND (DocStatus neq 'VO' AND DocStatus neq 'DR')`)+'&$expand=m_inoutline($expand=m_product_id),C_Order_ID,AD_User_ID,C_BPartner_Location_ID,M_Shipper_ID', {
          headers: useRequestHeaders(['cookie'])
        })
        if(res?.records) {
          if(Number(res.records.length) === 1) {
            pickShipmentItem(res.records[0])
            searchNo.value = ''
          } else {
            shipmentData.value = res.records.filter(i => i.m_inoutline.length >= 1)
            showSuggestion.value = true
          }
        }
      }
    }
  }
}

const restoreShipmentProduct = (item) => {
  const restoreShipmentLines = shipmentLines.value.filter(i => i.id === item.id)
  if(Number(restoreShipmentLines.length) === 0) {
    item.QtyCounter = 1
    shipmentLines.value.push(item)
  }
}

onMounted(() => {
  if(route.query?.no) {
    searchNo.value = route.query.no
    searchNoHandler()
  }
})

const getCustomerAddress = async () => {
  let resl = {}
  if(shipment.value?.C_BPartner_Location_ID?.id) {
    resl = await $fetch('/api/partners/partner-locations/'+shipment.value.C_BPartner_Location_ID.id, {
      headers: useRequestHeaders(['cookie'])
    })
  }
  customerAddress.value = resl
}

const loadDefaultTrackingNo = () => {
  let refNo = shipment.value?.C_Order_ID?.ExternalOrderId ?? shipment.value.uid.replaceAll('-', '') ?? null
  if(refNo) {
    let refNoDigit = ''
    if(refNo.length < 9) {
      refNoDigit = '0'
      for(let i = 0; i < (9 - Number(refNo.length)); i++) {
        refNoDigit += '0'
        refNo = `${refNoDigit}${refNo}`
      }
    }
    shipment.value.TrackingNo = refNo
  }
}

const validateOrderStatus = (order) => {
  if (!order) {
    return { isValid: false, message: 'Order information not available' }
  }

  // Extract DocStatus - it might be a string or an object with identifier/value property
  let docStatus = order.DocStatus
  if (typeof docStatus === 'object' && docStatus !== null) {
    docStatus = docStatus.identifier || docStatus.value || docStatus.Value || 'Unknown'
  }

  if (!docStatus) {
    return { isValid: false, message: 'Order status not available' }
  }

  switch (docStatus) {
    case 'CO':
    case 'Completed':
      return { isValid: true, message: 'Order is completed and ready for commission' }
    case 'VO':
      const voidedBy = order.UpdatedBy || order.updatedBy || 'Unknown user'
      const voidedTime = order.Updated || order.updated ? new Date(order.Updated || order.updated).toLocaleString() : 'Unknown time'
      return { 
        isValid: false, 
        message: `Order has been Canceled by ${voidedBy} at ${voidedTime}`,
        type: 'warning'
      }
    default:
      return { 
        isValid: false, 
        message: `Commission not possible because order is not in correct docstatus for commission. Current status: ${docStatus}`,
        type: 'info'
      }
  }
}

const pickShipmentItem = async (item) => {
  searchNo.value = ''

  // Validate order status before proceeding
  if (item.C_Order_ID) {
    const statusValidation = validateOrderStatus(item.C_Order_ID)

    if (!statusValidation.isValid) {
      toast({
        message: statusValidation.message,
        type: statusValidation.type === 'warning' ? 'is-warning' : 'is-info',
        duration: 8000
      })

      // Still load the shipment data but don't allow commission processing
      shipment.value = item
      shipmentLines.value = []
      showSuggestion.value = false
      return
    }
  }

  shipment.value = item
  if((shipment.value?.M_Shipper_ID?.Name ?? shipment.value?.C_Order_ID?.M_Shipper_ID?.identifier ?? 'dhl').toLowerCase() != 'dhl') {
    shippingService.value = 'other' //'sendcloud'
    loadDefaultTrackingNo()
  }

  shipmentLines.value = item.m_inoutline || []
  await getCustomerAddress()

  const newProducts = []
  for(let line of item.m_inoutline || []) {
    if(line?.M_Product_ID?.Strapi_Product_documentId) {
      const resp = await $fetch(`/api/materials/products/${line.M_Product_ID.Strapi_Product_documentId}/galleries/images`)
      if(resp) {
        line.galleries = resp
      }
    }
    if(newProducts.filter(i => i.M_Product_ID.id === line.M_Product_ID.id).length >= 1) {
      const prodInd = newProducts.findIndex(i => i.M_Product_ID.id === line.M_Product_ID.id)
      const prodItem = newProducts[prodInd]
      prodItem.QtyEntered = Number(prodItem.QtyEntered) + Number(line.QtyEntered)
      prodItem.QtyCounter = 1
      newProducts.splice(prodInd, 1, prodItem)
    } else {
      newProducts.push({
        ...line,
        QtyCounter: 1
      })
    }
  }
  shipmentLines.value = newProducts

  showSuggestion.value = false
}

const pickShipmentLine = async (item) => {
  if(shipment.value?.IsCommissioned !== true) {
    if(!shipmentCart.value.map(i => i.id).includes(item.id)) {
      item.QtyCounter = 1
      shipmentCart.value.push({
        ...item,
        show: false
      })

      if(item.QtyCounter >= item.QtyEntered) {
        shipmentLines.value = shipmentLines.value.filter(i => i.id !== item.id)
        searchNo.value = ''
      }
    } else {
      const indx = shipmentCart.value.findIndex(i => i.id === item.id)
      const newShipmentLine = shipmentCart.value[indx]
      newShipmentLine.QtyCounter = Number(newShipmentLine.QtyCounter) + 1
      shipmentCart.value.splice(indx, 1, newShipmentLine)

      if(newShipmentLine.QtyCounter >= newShipmentLine.QtyEntered) {
        shipmentLines.value = shipmentLines.value.filter(i => i.id !== item.id)
        searchNo.value = ''
      }
    }
  }
}

const unMatchActualQty = computed(() => {
  let docStatus = shipment.value?.C_Order_ID?.DocStatus
  if (typeof docStatus === 'object' && docStatus !== null) {
    docStatus = docStatus.identifier || docStatus.value || docStatus.Value
  }
  const hasInvalidOrderStatus = docStatus && docStatus !== 'CO' && docStatus !== 'Completed'
  return Number(shipmentCart.value.length) === 0 || Number(shipmentLines.value.length) !== 0 || shipmentCart.value.filter(i => Number(i.QtyCounter) !== Number(i.QtyEntered)).length >= 1 || paketType.value === '' || hasInvalidOrderStatus
})

const parcelItems = ref([])
const showCommissionModal = ref(false)
const openCommissionModal = async () => {
  parcelItems.value = shipmentCart.value.map(item => {
    const newWeight = Number((Number(item.QtyCounter ?? 1) * Number(item.M_Product_ID?.Weight ?? 0)).toFixed(2))
    return {
      item_id: item.id,
      description: item.M_Product_ID.Name,
      product_id: item.M_Product_ID.id,
      quantity: item.QtyCounter,
      value: Number(item.QtyCounter) * 1,
      weight: newWeight || 0.1,
      //hs_code: '84713010',
    }
  })

  if(!customerAddress.value?.id) {
    await getCustomerAddress()
  }

  showCommissionModal.value = true
}

const parcel = ref({})
const showShipmentMobile = ref(false)
const automaticPrinting = ref(true)

const showCommissionList = ref(false)
const openCommissionList = () => {
  showCommissionList.value = true
}
const editCommissionList = (item) => {
  showCommissionList.value = false
  parcel.value = item
  openCommissionModal()
}

const parcelCommissionLabel = ref({})
const showCommissionLabel = ref(false)
const openCommissionLabel = (item) => {
  showCommissionLabel.value = true
  parcelCommissionLabel.value = item
}

const handleCommissionModal = (item) => {
  if(item?.label?.label_printer && item?.parcel) {
    openCommissionLabel(item.parcel)
  } else {
    openCommissionList()
  }
  resetShipmentCart()
}

const parcelCommissionDHLLabel = ref({})
const showCommissionDHLLabel = ref(false)
const openCommissionDHLLabel = (item) => {
  showCommissionDHLLabel.value = true
  parcelCommissionDHLLabel.value = item
}

const resetShipmentCart = () => {
  shipment.value = {}
  customerAddress.value = {}
  parcel.value = {}
  parcelItems.value = []
  shipmentCart.value = []
  shipmentLines.value = []
  searchNo.value = ''
  paketType.value = ''
  // Keep shippingPrinter value persistent between commission processes
  if(searchRef.value) {
    searchRef.value.focus()
  }
}

const fullscreen = ref(false)
const fullscreenHandler = () => {
  const elem = document.documentElement
  if(!fullscreen.value) {
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem.webkitRequestFullscreen) { /* Safari */
      elem.webkitRequestFullscreen();
    } else if (elem.msRequestFullscreen) { /* IE11 */
      elem.msRequestFullscreen();
    }
    fullscreen.value = true
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.webkitExitFullscreen) { /* Safari */
      document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) { /* IE11 */
      document.msExitFullscreen();
    }
    fullscreen.value = false
  }
}

// const extractHouseNumber = (address) => {
//   let newAddressStr = ''
//   const newAddressArr = address.match(/\d/g)
//   if(newAddressArr) {
//     newAddressStr = (newAddressArr[Number(newAddressArr.length) - 2] || '')+''+(newAddressArr[Number(newAddressArr.length) - 1] || '')
//   }
//   return newAddressStr
// }

const extractStreetName = (address) => {
  const match = address.match(/^([^,\d]+(?:\.\s*)?)/);
  return match ? match[1].trim() : '';
};

const extractHouseNumber = (address) => {
  const match = address.match(/(\d+[a-zA-Z]*.*)$/);
  return match ? match[1].trim() : '';
};

//
// const extractHouseNumber = (address) => {
//   let newAddressStr = '';
//   const match = address.match(/^(.+?)\s+(\d+\s*[a-zA-Z]?(?:[.,\-/\s]*\w*)?)$/);
//
//   if (match) {
//     newAddressStr = match[2].trim();
//   }
//
//   return newAddressStr;
// };

const getShippingMethod = async () => {
  if(parcel.value?.country || customerAddress.value?.country?.CountryCode) {
    const res = await $fetch('/api/commission/shipping-methods/to_country='+(parcel.value?.country ?? customerAddress.value?.country?.CountryCode ?? 'DE'))
    if(res?.shipping_methods?.[0]) {
      shippingMethod.value = res.shipping_methods[0]
    }
  }
}

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 printParcelLabel = async () => {
  parcelItems.value = shipmentCart.value.map(item => {
    const newWeight = Number((Number(item.QtyCounter ?? 1) * Number(item.M_Product_ID?.Weight ?? 0)).toFixed(2))
    return {
      item_id: item.id,
      description: item.M_Product_ID.Name,
      product_id: item.M_Product_ID.id,
      quantity: item.QtyCounter,
      value: Number(item.QtyCounter) * 1,
      weight: newWeight || 0.1,
      //hs_code: '84713010',
    }
  })

  if(!customerAddress.value?.id) {
    await getCustomerAddress()
  }
  /*if(!shippingMethod.value?.id) {
    await getShippingMethod()
  }*/
  const newCountryCode = parcel.value?.country ?? customerAddress.value?.country?.CountryCode ?? 'DE'
  if(newCountryCode == 'DE') {
    shippingMethod.value['id'] = 89
  } else {
    shippingMethod.value['id'] = 94
  }

  const newForm = {
    id: '',
    inOutId: shipment.value?.id || '',
    inOutUId: shipment.value?.uid || '',
    name: shipment.value?.C_BPartner_Location_ID?.Name || '',
    companyName: '',
    email: shipment.value?.AD_User_ID?.EMail?.replaceAll(' ', '') || '',
    telephone: shipment.value?.C_BPartner_Location_ID?.Phone || '',
    // address: customerAddress.value?.C_Location_ID?.Address1?.replace(/\d+$/, '') || '',
    address: extractStreetName(customerAddress.value?.C_Location_ID?.Address1 || '',),
    houseNumber: extractHouseNumber(customerAddress.value?.C_Location_ID?.Address1 || ''),
    address2: customerAddress.value?.C_Location_ID?.Address2 || '',
    city: customerAddress.value?.C_Location_ID?.City || '',
    country: newCountryCode,
    countryName: parcel.value?.countryName ?? customerAddress.value?.country?.Name ?? 'Germany',
    countryId: customerAddress.value?.country?.id ?? 101,
    countryIso3: customerAddress.value?.country?.ISOCountryCodeAlpha3 ?? 'DEU',
    postalCode: customerAddress.value?.C_Location_ID?.Postal || '',
    countryState: '',
    toServicePoint: '',
    toPostNumber: '',
    // customsInvoiceNR: shipment.value?.DocumentNo || '',
    customsInvoiceNR: '',
    customsShipmentType: '',
    weight: Number(Number(parcelItems.value.map(i => i.weight).reduce((acc, prev) => Number(acc) + Number(prev), 0)).toFixed(2)),
    length: shipment.value?.Volume || '',
    width: '',
    height: '',
    // orderNumber: shipment.value?.C_OrderSource_ID?.identifier+'-'+shipment.value?.C_Order_ID?.ExternalOrderId || shipment.value?.C_Order_ID?.DocumentNo || '',
    orderNumber: shipment.value?.C_Order_ID?.ExternalOrderId || shipment.value?.C_Order_ID?.DocumentNo || '',
    totalOrderValue: shipment.value?.C_Order_ID?.GrandTotal || '',
    totalOrderValueCurrency: shipment.value?.C_Order_ID?.C_Currency_ID?.identifier || '',
    shippingMethodCheckoutName: '',
    senderAddress: 1,
    quantity: 1,
    totalInsuredValue: 0,
    isReturn: false,
    requestLabel: true,
    applyShippingRules: false,
    requestLabelAsync: false,
    //shipment: parcel.value?.shipment || 'Unstamped letter',
    shipmentId: shippingMethod.value?.['id'] ?? 8,
    parcelItems: parcelItems.value,
    paketType: paketType.value,
    shippingPrinter: shippingPrinter.value,
    trackingNo: shipment.value?.TrackingNo ?? null,
    shippingService: shippingService.value
  }

  // console.log(shipment.value?.C_Order_ID)
  let parcelEndpoint = 'parcels'
  if(shippingService.value === 'dhl') {
    parcelEndpoint = 'parcels/dhl'
  } else if(shippingService.value === 'other') {
    parcelEndpoint = 'parcels/other'
  }
  const res = await $fetch(`/api/commission/${parcelEndpoint}`, {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: newForm
  })

  // Log debug information to browser console
  console.log('[COMMISSION DEBUG] Full API Response:', res)
  if(res?.orderSourceDebug) {
    console.log('[COMMISSION DEBUG] Order Source Information:', res.orderSourceDebug)
  }
  if(res?.jtl_laravel) {
    console.log('[COMMISSION DEBUG] JTL-FFN Laravel Response:', res.jtl_laravel)
  }
  if(res?.jtl_warning) {
    console.warn('[COMMISSION DEBUG] JTL-FFN Warning:', res.jtl_warning)
  }
  if(res?.jtl) {
    console.error('[COMMISSION DEBUG] JTL-FFN Error:', res.jtl)
  }

  if(Number(res.status) === 200) {
    toast({
      message: 'Parcel Label has been created!',
      type: 'is-success',
      duration: 2000
    })
    if(Number(res?.shopware?.status  || 200) === 500) {
      toast({
        message: res?.shopware?.message || 'Fail saving to shopware',
        type: 'is-danger',
        duration: 10000
      })
    }
    if(Number(res?.shopify?.status  || 200) === 500) {
      toast({
        message: res?.shopify?.message || 'Fail saving to shopify',
        type: 'is-danger',
        duration: 10000
      })
    }
    if(res?.parcel?.id) {
      /*if(String(newForm.name).toLowerCase().trim() != String(res.parcel.name).toLowerCase().trim()) {
        toast({
          message: `Payload name: ${newForm.name}, Response name: ${res.parcel.name}, is it identical? If not then mean the issues are on Sendcloud side.`,
          type: 'is-warning',
          duration: 20000
        })
      }*/

      const resp = await $fetch(`/api/commission/labels/${res.parcel.id}/pdf`)
      if(resp) {
        const reader = new FileReader();
        reader.addEventListener('load', () => {
          serverSidePrinting({
            pathName: `label/${new Date().getFullYear()}`,
            fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-'+res.parcel.id+'-')}-LABEL-${user.value?.Name || 'SUPERUSER'}.pdf`,
            fileContent: reader.result?.replace('data:application/pdf;base64,', ''),
            shippingPrinter: shippingPrinter.value
          })
        })
        reader.readAsDataURL(resp);
      }
    } else if(res?.dhl_parcel?.shipmentNo) {
      const resp = await $fetch(`/api/commission/parcels/dhl?shipment_code=${res.dhl_parcel.shipmentNo}`)
      if(resp?.items?.[0]?.label?.b64 || res.dhl_parcel?.label?.b64) {
        serverSidePrinting({
          pathName: `label/${new Date().getFullYear()}`,
          fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-'+res.dhl_parcel.shipmentNo+'-')}-LABEL-${user.value?.Name || 'SUPERUSER'}.pdf`,
          fileContent: (resp?.items?.[0]?.label?.b64 ?? res.dhl_parcel.label.b64)?.replace('data:application/pdf;base64,', ''),
          shippingPrinter: shippingPrinter.value
        })
      }
    }
    resetShipmentCart()
  } else {
    toast({
      message: res.message || 'Fail saving parcel label',
      type: 'is-danger',
      duration: 10000
    })
  }
}
watch(unMatchActualQty, () => {
  if(Number(shipmentCart.value.length) !== 0 && Number(shipmentLines.value.length) === 0 && Number(shipmentCart.value.filter(i => Number(i.QtyCounter) !== Number(i.QtyEntered)).length) === 0 && automaticPrinting.value && paketType.value !== '') {
    printParcelLabel()
  } else {
    if(Number(shipmentCart.value.length) !== 0 && Number(shipmentLines.value.length) === 0 && Number(shipmentCart.value.filter(i => Number(i.QtyCounter) !== Number(i.QtyEntered)).length) === 0 && automaticPrinting.value && paketType.value === '') {
      toast({
        message: 'Paket Type is a mandatory. Please choose one of CODE1 (S), CODE2 (M), CODE3 (L), or CODE4 (XL).',
        type: 'is-warning',
        duration: 10000
      })
    }
  }
})

watch(shippingPrinter, (newValue) => {
  if (typeof window !== 'undefined' && newValue) {
    localStorage.setItem('shippingPrinter', newValue)
  }
})
</script>

<template>
  <div class="page">
    <div class="pageSectionLeft">
      <div class="shipmentCart" :class="{shipmentMobile: showShipmentMobile}">
        <div class="shipmentCartTable">
          <IntegrationsCommissionCart v-model="shipmentCart" @handler="restoreShipmentProduct" />
        </div>
        <div class="p-1.5rem">
          <button v-if="!automaticPrinting" type="button" @click="openCommissionModal" class="button w-100pct" :class="unMatchActualQty ? 'pointerEvents-none opacity-0.6' : ''">Pack and Ship</button>
          <button type="button" @click="resetShipmentCart" class="button w-100pct mt-2">Reset</button>
          <button v-if="showShipmentMobile" type="button" @click="resetShipmentCart(); showShipmentMobile = !showShipmentMobile;" class="button w-100pct mt-2">Close</button>
        </div>
      </div>
    </div>
    <div class="pageSectionMain">
      <div class="p-1.5rem">
        <div class="card sd-none">
          <div class="card-content">
            <div class="d-flex justify-between items-center gap-10px">
              <div class="flexGrow-1">
                <div class="picker" :class="{active: showSuggestion}">
                  <div class="pickerBackdrop" @click.self="showSuggestion = false"></div>
                  <div class="pickerWrap">
                    <input v-model="searchNo" ref="searchRef" type="search" class="input w-100pct" :placeholder="(shipment?.id && !shipment?.IsCommissioned) ? 'Enter Product Name, SKU, UPC or Value Here' : 'Enter Shipment No Here'" @keyup.enter="searchNoHandler" autofocus />
                    <div class="pickerContent w-100pct" style="margin-top: 5px;">
                      <div class="pickerBody mxh-450px overflowY-auto" style="box-shadow: 0 3px 8px rgba(0,0,0,.24);">
                        <div v-if="shipmentData.length >= 1" class="list flush">
                          <div v-for="(shipmentItem, index) in shipmentData" :key="index" @click.self="pickShipmentItem(shipmentItem)" class="listItem p-1 cursor-pointer">{{ shipmentItem.DocumentNo }}</div>
                        </div>
                        <div v-else>
                          No shipment found for {{ searchNo }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="d-flex items-center gap-10px">
                <div @click="showShipmentMobile = !showShipmentMobile" class="showShipmentMobile">
                  <span class="tf-icon ti ti-menu-2 ti-xl color-inherit cursor-pointer"></span>
                </div>
                <div @click="searchNoHandler">
                  <span class="tf-icon ti ti-search ti-xl color-inherit cursor-pointer"></span>
                </div>
                <div @click="openCommissionList">
                  <span class="tf-icon ti ti-clipboard-list ti-xl color-inherit cursor-pointer"></span>
                </div>
                <div @click="fullscreenHandler">
                  <span v-if="fullscreen" class="tf-icon ti ti-arrows-minimize ti-xl color-inherit cursor-pointer"></span>
                  <span v-else class="tf-icon ti ti-arrows-maximize ti-xl color-inherit cursor-pointer"></span>
                </div>
                <NuxtLink :to="route.query?.no ? '/sales/shipments' : '/integrations'">
                  <span class="tf-icon ti ti-logout ti-xl color-inherit cursor-pointer"></span>
                </NuxtLink>
              </div>
            </div>
          </div>
        </div>

        <div class="py-0.75rem">
          <div class="mainSection">
            <div class="productSection">
              <div v-if="shipment?.IsCommissioned" class="textAlign-center">
                Already commissioned
              </div>
              <div v-else class="d-flex flexGrow-1 flexWrap-wrap gap-0.75rem">
                <div v-for="(shipmentLine, ind) in shipmentLines" :key="ind" class="card w-145px mb-0px" @click="pickShipmentLine(shipmentLine)">
                  <div v-if="(shipmentLine?.galleries?.length || 0) >= 1" class="productChooserBox">
                    <img v-if="shipmentLine?.galleries[0]?.formats?.small" :src="config.public.strapi+'/files-api/'+shipmentLine?.galleries[0]?.formats?.small?.hash + shipmentLine?.galleries[0]?.formats?.small?.ext" :alt="shipmentLine?.galleries[0]?.name" />
                    <img v-else :src="config.public.strapi+'/files-api/'+shipmentLine?.galleries[0]?.formats?.thumbnail?.hash + shipmentLine?.galleries[0]?.formats?.thumbnail?.ext" :alt="shipmentLine?.galleries[0]?.name" />
                  </div>
                  <div v-else class="productChooserBox">
                    <img src="https://placehold.co/145x128" alt="Placeholder Image" />
                  </div>
                  <div class="cardBody p-10px preventSelectText">
                    <h3>{{ shipmentLine.M_Product_ID.Name }}</h3>
                    <p><small>Val: {{ shipmentLine.M_Product_ID.Value }}</small><br/><small>Qty: {{ shipmentLine.QtyEntered }}</small></p>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="shipment?.IsCommissioned !== true" class="infoSection">
              <div class="card w-100pct h-100pct mb-0px">
                <div class="cardBody p-10px h-100pct">
                  <div class="horizontalInfos h-100pct">
                    <div>
                      <div class="titleInfoText">Customer Address</div>
                      <div class="p-0.75rem" v-if="customerAddress?.id">
                        <div class="legend">
                          <label class="label"><strong>Address</strong></label>
                          <input type="text" :value="customerAddress.C_Location_ID?.Address1 || ''" class="input" readonly />
                        </div>
                        <div class="legend mt-2">
                          <label class="label"><strong>City</strong></label>
                          <input type="text" :value="customerAddress.C_Location_ID?.City || ''" class="input" readonly />
                        </div>
                        <div class="legend mt-2">
                          <label class="label"><strong>Region</strong></label>
                          <input type="text" :value="customerAddress.C_Location_ID?.C_Region_ID?.identifier || ''" class="input" readonly />
                        </div>
                        <div class="legend mt-2">
                          <label class="label"><strong>Country</strong></label>
                          <input type="text" :value="customerAddress.C_Location_ID?.C_Country_ID?.identifier || ''" class="input" readonly />
                        </div>
                        <div class="legend mt-2">
                          <label class="label"><strong>Postal Code</strong></label>
                          <input type="text" :value="customerAddress.C_Location_ID?.Postal || ''" class="input" readonly />
                        </div>
                      </div>
                      <div class="p-0.75rem textAlign-center" v-else>
                        No Shipment Selected
                      </div>
                      <div v-if="shipment?.C_Order_ID?.DocStatus && !['CO', 'Completed'].includes(typeof shipment.C_Order_ID.DocStatus === 'object' ? (shipment.C_Order_ID.DocStatus.identifier || shipment.C_Order_ID.DocStatus.value || shipment.C_Order_ID.DocStatus.Value) : shipment.C_Order_ID.DocStatus)" class="p-0.75rem">
                        <div class="notification" :class="(typeof shipment.C_Order_ID.DocStatus === 'object' ? (shipment.C_Order_ID.DocStatus.identifier || shipment.C_Order_ID.DocStatus.value || shipment.C_Order_ID.DocStatus.Value) : shipment.C_Order_ID.DocStatus) === 'VO' ? 'is-warning' : 'is-info'">
                          <div class="legend">
                            <label class="label"><strong>Order Status</strong></label>
                            <input type="text" :value="(typeof shipment.C_Order_ID.DocStatus === 'object' ? (shipment.C_Order_ID.DocStatus.identifier || shipment.C_Order_ID.DocStatus.value || shipment.C_Order_ID.DocStatus.Value) : shipment.C_Order_ID.DocStatus) || 'Unknown'" class="input" readonly />
                          </div>
                          <p class="mt-2" v-if="(typeof shipment.C_Order_ID.DocStatus === 'object' ? (shipment.C_Order_ID.DocStatus.identifier || shipment.C_Order_ID.DocStatus.value || shipment.C_Order_ID.DocStatus.Value) : shipment.C_Order_ID.DocStatus) === 'VO'">
                            <small><strong>Order Canceled:</strong> This order cannot be commissioned</small>
                          </p>
                          <p class="mt-2" v-else>
                            <small><strong>Invalid Status:</strong> Commission not available for this order status</small>
                          </p>
                        </div>
                      </div>
                      <template v-if="customerAddress?.id">
                        <div class="titleInfoText mt-2">Other</div>
                        <div class="p-0.75rem">
                          <div class="legend">
                            <label class="label"><strong>Paket Type *</strong></label>
                            <!--<input type="text" :value="paketType || ''" class="input" readonly />-->
                            <select v-model="paketType" class="select">
                              <option :value="1000204">CODE1</option>
                              <option :value="1000205">CODE2</option>
                              <option :value="1000206">CODE3</option>
                              <option :value="1000213">CODE4</option>
                              <option :value="1000857">CODE5</option>
                              <option :value="1000911">CODE6</option>
                              <option :value="1000001">CODETEST</option>
                            </select>
                          </div>
                        </div>
                        <div v-if="shipment?.M_Shipper_ID?.IsReadTrackingCommission || shippingService === 'other'" class="p-0.75rem">
                          <div class="legend">
                            <label class="label"><strong>Tracking No *</strong></label>
                            <input type="text" v-model="shipment.TrackingNo" class="input" />
                          </div>
                        </div>
                        <div class="p-0.75rem">
                          <label class="label d-block"><strong>Shipping Service *</strong></label>
                          <div class="d-flex flexDirection-column gap-5px">
                            <div class="check">
                              <input type="radio" v-model="shippingService" class="checkInput" name="shippingService" id="sendcloud" :checked="shippingService === 'sendcloud'" value="sendcloud">
                              <label class="checkLabel" for="sendcloud">Sendcloud</label>
                            </div>
                            <div class="check">
                              <input type="radio" v-model="shippingService" class="checkInput" name="shippingService" id="dhl" :checked="shippingService === 'dhl'" value="dhl" :disabled="(shipment?.M_Shipper_ID?.Name ?? shipment?.C_Order_ID?.M_Shipper_ID?.identifier ?? 'dhl').toLowerCase() != 'dhl'">
                              <label class="checkLabel" for="dhl">DHL</label>
                            </div>
                            <div class="check">
                              <input type="radio" v-model="shippingService" class="checkInput" name="shippingService" id="other" :checked="shippingService === 'other'" value="other" @change="loadDefaultTrackingNo" :disabled="['dhl'].includes((shipment?.M_Shipper_ID?.Name ?? shipment?.C_Order_ID?.M_Shipper_ID?.identifier ?? '').toLowerCase())">
                              <label class="checkLabel" for="other">Other</label>
                            </div>
                          </div>
                        </div>
                      </template>
                    </div>
                    <div>
                      <div class="p-0.75rem">
                        <div class="legend">
                          <label class="label"><strong>Shipping Printer *</strong></label>
                          <!--<input type="text" :value="shippingPrinter || ''" class="input" readonly />-->
                          <select v-model="shippingPrinter" class="select">
                            <option value="labelprinter-1">Tisch 1</option>
                            <option value="labelprinter-4">Tisch 2</option>
                            <option value="labelprinter-5">Tisch 3</option>
                          </select>
                        </div>
                      </div>
                      <div class="d-flex flexDirection-column mb-2 p-1.5rem">
                        <div class="check">
                          <input type="checkbox" v-model="automaticPrinting" class="checkInput" id="automaticPrinting" :checked="automaticPrinting">
                          <label class="checkLabel" for="automaticPrinting">Automatic Printing</label>
                        </div>
                      </div>
                      <div class="scanText">
                        {{ shipment?.id ? 'Scan Article' : 'Scan Shipment' }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="infoSection">
              <div class="card w-100pct h-100pct mb-0px">
                <div class="cardBody p-10px h-100pct">
                  <div class="horizontalInfos h-100pct">

                    <div class="p-0.75rem textAlign-center">
                      Shipped
                    </div>
                    <div class="p-0.75rem">
                      <div class="legend">
                        <label class="label"><strong>Shipping Printer *</strong></label>
                        <!--<input type="text" :value="shippingPrinter || ''" class="input" readonly />-->
                        <select v-model="shippingPrinter" class="select">
                          <option value="label">Commission Place 1</option>
                          <option value="label-2">Commission Place 2</option>
                          <option value="label-3">Commission Place 3</option>
                          <option value="label-4">Commission Place 4</option>
                        </select>
                      </div>
                      <div class="mb-2 p-1.5rem"></div>
                      <div class="scanText">
                        Scanned
                      </div>
                    </div>

                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>

      </div>
    </div>
  </div>

  <Teleport to="body">
    <IntegrationsCommissionModal v-model="showCommissionModal" :items="parcelItems" :shipment="shipment" :address="customerAddress" :parcel="parcel" v-model:paketType="paketType" v-model:shippingPrinter="shippingPrinter" @handler="handleCommissionModal" :shippingService="shippingService" />
    <IntegrationsCommissionList v-model="showCommissionList" :shippingPrinter="shippingPrinter" @edit="editCommissionList" @label="openCommissionLabel" @dhlLabel="openCommissionDHLLabel" />
    <IntegrationsCommissionLabel v-model="showCommissionLabel" :parcel="parcelCommissionLabel" :shippingPrinter="shippingPrinter" />
    <IntegrationsCommissionDHLLabel v-model="showCommissionDHLLabel" :parcel="parcelCommissionDHLLabel" :shippingPrinter="shippingPrinter" />
  </Teleport>
</template>

<style scoped>
@use page {
  layout: left;
}

.page {
  background-color: #f8f8f8;
  min-height: 100vh;
}

.pageSectionLeft .shipmentCart {
  display: block;
  width: 480px; /*640px*/
  min-height: 100vh;
  /*height: 100%;*/
  background-color: #fff;
  box-shadow: rgba(100, 100, 111, 0.2) 0px 0px 1px 0px;
  transform: translateX(0);
  transition: 0.3s ease;
  position: relative;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
}

.shipmentCart .shipmentCartTable {
  position: relative;
  overflow-y: auto;
  flex-grow: 1;
}

.preventSelectText {
  -webkit-user-select: none; /* Safari */
  -ms-user-select: none; /* IE 10 and IE 11 */
  user-select: none; /* Standard syntax */
  pointer-events: none;
  cursor: default;
}

.mainSection {
  display: flex;
  justify-content: space-between;
  gap: 1.5rem;
}

.mainSection .productSection {
  flex-grow: 1;
}

.mainSection .infoSection {
  display: block;
  width: 200px;
  height: calc(100vh - 120px);
}

.mainSection .infoSection .horizontalInfos {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  gap: 1.5rem;
  overflow-y: auto;
}

.mainSection .infoSection .titleInfoText {
  font-size: 16px;
  font-weight: bold;
  padding: 0.75rem;
  padding-bottom: 1.5rem;
  text-align: center;
}

.mainSection .infoSection .scanText {
  font-size: 20px;
  font-weight: bold;
  padding-top: 0.75rem;
  padding-bottom: 1.75rem;
  padding-right: 0.75rem;
  padding-left: 0.75rem;
  text-align: center;
}

.showShipmentMobile {
  display: none;
}

@media only screen and (max-width: 1024px) {
  .mainSection .infoSection,
  .pageSectionLeft .shipmentCart:not(.shipmentMobile) {
    display: none;
  }
  .pageSectionLeft .shipmentCart.shipmentMobile {
    display: flex;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 1;
  }
  .showShipmentMobile {
    display: block;
  }
}
</style>