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

const props = defineProps({
  modelValue: Boolean,
  items: Array,
  shipment: Object,
  parcel: Object,
  address: Object,
  paketType: [String, Number],
  shippingService: String,
  shippingPrinter: String,
  // Table/printer picker options from the parent (CUST_CommissionTable). Falls
  // back to the built-in Tisch 1/2/3 defaults when not provided / empty.
  printerOptions: { type: Array, default: () => [] }
})

const emit = defineEmits(['update:modelValue', 'update:paketType', 'update:shippingPrinter', 'handler'])

const printerSelectOptions = computed(() => (props.printerOptions && props.printerOptions.length)
  ? props.printerOptions
  : [
      { value: 'labelprinter-1', label: 'Tisch 1' },
      { value: 'labelprinter-4', label: 'Tisch 2' },
      { value: 'labelprinter-5', label: 'Tisch 3' }
    ])

const tab = ref('customer')
const tabs = ref([
  {value: 'customer', text: 'Customer Info'},
  {value: 'shipment', text: 'Shipment Details'},
  {value: 'method', text: 'Shipping Method'},
])

const showCommissionModal = ref(props.modelValue || false)
const closeCommissionModal = () => {
  showCommissionModal.value = false
  emit('update:modelValue', showCommissionModal.value)
}
watch(() => props.modelValue, () => {
  showCommissionModal.value = props.modelValue
})

// 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 extractHouseNumber = (address, country = '') => {
  if (!address) return '';
  const trimmed = String(address).trim();
  // US-only: Anglo format, house number at start, e.g. "11653 E Sorrel Ln"
  if (String(country).toUpperCase() === 'US' && /^\d/.test(trimmed)) {
    const match = trimmed.match(/^(\d+[a-zA-Z]?)\s/);
    return match ? match[1].trim() : '';
  }
  // Default (non-US): original regex - everything from first digit to end
  const match = address.match(/(\d+[a-zA-Z]*.*)$/);
  return match ? match[1].trim() : '';
};

const extractStreetName = (address, country = '') => {
  if (!address) return '';
  const trimmed = String(address).trim();
  // US-only: Anglo format, house number at start, street follows
  if (String(country).toUpperCase() === 'US' && /^\d/.test(trimmed)) {
    const match = trimmed.match(/^\d+[a-zA-Z]?\s+(.+)$/);
    return match ? match[1].trim() : trimmed;
  }
  // Default (non-US): original regex - street name before first digit/comma
  const match = address.match(/^([^,\d]+(?:\.\s*)?)/);
  return match ? match[1].trim() : '';
};

const form = ref({
  id: props.parcel?.id || '',
  inOutId: props.parcel?.inOutId || props.shipment?.id || '',
  inOutUId: props.parcel?.inOutUId || props.shipment?.uid || '',
  name: props.parcel?.name || props.shipment?.C_BPartner_Location_ID?.Name || '',
  companyName: props.parcel?.companyName || '',
  email: props.parcel?.email || props.shipment?.AD_User_ID?.EMail?.replaceAll(' ', '') || '',
  telephone: props.parcel?.telephone || props.shipment?.C_BPartner_Location_ID?.Phone || '',
  // address: props.parcel?.address || props.address?.C_Location_ID?.Address1?.replace(/\d+$/, '') || '',
  address: props.parcel?.address || extractStreetName(props.address?.C_Location_ID?.Address1 || '', props.parcel?.country || props.address?.country?.CountryCode || 'DE'),
  houseNumber: props.parcel?.houseNumber || extractHouseNumber(props.address?.C_Location_ID?.Address1 || '', props.parcel?.country || props.address?.country?.CountryCode || 'DE'),
  address2: props.parcel?.address2 || props.address?.C_Location_ID?.Address2 || '',
  city: props.parcel?.city || props.address?.C_Location_ID?.City || '',
  country: props.parcel?.country || props.address?.country?.CountryCode || 'DE',
  countryName: props.parcel?.countryName || props.address?.country?.Name || 'Germany',
  countryId: props.address?.country?.id || 101,
  countryIso3: props.address?.country?.ISOCountryCodeAlpha3 || 'DEU',
  postalCode: props.parcel?.postalCode || props.address?.C_Location_ID?.Postal || '',
  countryState: props.parcel?.countryState || '',
  toServicePoint: props.parcel?.toServicePoint || '',
  toPostNumber: props.parcel?.toPostNumber || '',
  customsInvoiceNR: props.parcel?.customsInvoiceNR || '',
  customsShipmentType: props.parcel?.customsShipmentType || '',
  weight: Number(Number(props.parcel?.weight || props.items.map(i => i.weight.toFixed(2)).reduce((acc, prev) => Number(acc) + Number(prev), 0)).toFixed(2)),
  length: props.parcel?.length || props.shipment?.Volume || '',
  width: props.parcel?.width || '',
  height: props.parcel?.height || '',
  orderNumber: props.parcel?.orderNumber || props.shipment?.C_Order_ID?.ExternalOrderId || props.shipment?.C_Order_ID?.DocumentNo || '',
  totalOrderValue: props.parcel?.totalOrderValue || props.shipment?.C_Order_ID?.GrandTotal || '',
  totalOrderValueCurrency: props.parcel?.totalOrderValueCurrency || props.shipment?.C_Order_ID?.C_Currency_ID?.identifier || '',
  shippingMethodCheckoutName: props.parcel?.shippingMethodCheckoutName || '',
  senderAddress: props.parcel?.senderAddress || 1,
  quantity: props.parcel?.quantity || 1,
  totalInsuredValue: props.parcel?.totalInsuredValue || 0,
  isReturn: props.parcel?.isReturn ?? false,
  requestLabel: props.parcel?.requestLabel ?? false,
  applyShippingRules: props.parcel?.applyShippingRules ?? false,
  requestLabelAsync: props.parcel?.requestLabelAsync ?? false,
  shipment: props.parcel?.shipment || '', //'Unstamped letter' or 'DHL Paket'
  shipmentId: props.parcel?.shipmentId ?? '', //8 or 89
  dateCreated: props.parcel?.dateCreated || '',
  dateUpdated: props.parcel?.dateUpdated || '',
  dateAnnounced: props.parcel?.dateAnnounced || '',
  paketType: props.paketType || '',
  shippingPrinter: props.shippingPrinter || '',
  trackingNo: props.shipment?.TrackingNo ?? null,
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const loading = ref({})
const filtering = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    getOptions.value[key] = res

    if(key === 'shipping_methods' && form.value.shipmentId == '') {
      if(res?.shipping_methods?.length >= 1) {
        form.value.shipment = res.shipping_methods[0].name
        form.value.shipmentId = res.shipping_methods[0].id
      } else {
        form.value.shipment = 'Unstamped letter'
        form.value.shipmentId = 8
      }
    } else if(key === 'countries' && (form.value.countryId == 101 && form.value.country != 'DE')) {
      form.value.countryId = res.records?.[0]?.id ?? ''
    } else if(key === 'provinces') { // && form.value.countryState == ''
      //form.value.countryState = res.records?.[0]?.Name ?? ''
      getOptions.value[key].records.push({Name: ''})
    }
  }
  loading.value[key] = false
}

const filterOptions = async (model, key, filter = '') => {
  if(filter) {
    await setOptions('filters/'+model+'/'+filter, key)
    filtering.value[key] = filter
  } else {
    if(!filtering.value?.[key] || filtering.value?.[key] === '') {
      await setOptions('models/'+model, key)
    }
  }
}

watch(() => props.shipment, () => {
  form.value.inOutId = props.shipment?.id || ''
  form.value.inOutUId = props.shipment?.uid || ''
  form.value.name = props.shipment?.C_BPartner_Location_ID?.Name || ''
  form.value.email = props.shipment?.AD_User_ID?.EMail?.replaceAll(' ', '') || ''
  form.value.telephone = props.shipment?.C_BPartner_Location_ID?.Phone || ''
  form.value.customsInvoiceNR = ''
  form.value.weight = Number(Number(props.items.map(i => i.weight.toFixed(2)).reduce((acc, prev) => Number(acc) + Number(prev), 0)).toFixed(2))
  form.value.length = props.shipment?.Volume || ''
  // form.value.orderNumber = props.shipment?.C_Order_ID?.DocumentNo || ''
  form.value.orderNumber = props.shipment?.C_Order_ID?.ExternalOrderId || props.shipment?.C_Order_ID?.DocumentNo  || ''
  form.value.totalOrderValue = props.shipment?.C_Order_ID?.GrandTotal || ''
  form.value.totalOrderValueCurrency = props.shipment?.C_Order_ID?.C_Currency_ID?.identifier || ''
  form.value.trackingNo = props.shipment?.TrackingNo ?? null
}, {deep: true})

watch(() => props.address, () => {
  // form.value.address = props.address?.C_Location_ID?.Address1?.replace(/\d+$/, '') || ''
  form.value.address = extractStreetName(props.address?.C_Location_ID?.Address1 || '', props.address?.country?.CountryCode || 'DE')
  form.value.houseNumber = extractHouseNumber(props.address?.C_Location_ID?.Address1 || '', props.address?.country?.CountryCode || 'DE')
  form.value.address2 = props.address?.C_Location_ID?.Address2 || ''
  form.value.city = props.address?.C_Location_ID?.City || ''
  form.value.postalCode = props.address?.C_Location_ID?.Postal || ''
  form.value.country = props.address?.country?.CountryCode || 'DE'
  form.value.countryName = props.address?.country?.Name || 'Germany'
  form.value.countryId = props.address?.country?.id || 101
  form.value.countryIso3 = props.address?.country?.ISOCountryCodeAlpha3 || 'DEU'

  if((form.value.shipmentId == 8 || form.value.shipmentId == '') && props.address?.country?.CountryCode) {
    setOptions('commission/shipping-methods/to_country='+props.address.country.CountryCode, 'shipping_methods')
  }

  if(form.value.countryId) {
    filterOptions('c_region', 'provinces', string.urlEncode(`isActive eq true AND C_Country_ID eq ${form.value.countryId}`))
  }
})

watch(() => props.items, () => {
  form.value.weight = parseFloat(Number(props.items.map(i => i.weight.toFixed(2)).reduce((acc, prev) => Number(acc) + Number(prev), 0)).toFixed(2))
})

watch(() => props.paketType, () => {
  form.value.paketType = props.paketType
})

watch(() => props.shippingPrinter, () => {
  form.value.shippingPrinter = props.shippingPrinter
})

watch(() => props.parcel, () => {
  form.value.id = props.parcel?.id || ''
  form.value.inOutId = props.parcel?.inOutId || props.shipment?.id || ''
  form.value.inOutUId = props.parcel?.inOutUId || props.shipment?.uid || ''
  form.value.name = props.parcel?.name || props.shipment?.C_BPartner_Location_ID?.Name || ''
  form.value.companyName = props.parcel?.companyName || ''
  form.value.email = props.parcel?.email || props.shipment?.AD_User_ID?.EMail?.replaceAll(' ', '') || ''
  form.value.telephone = props.parcel?.telephone || props.shipment?.C_BPartner_Location_ID?.Phone || ''
    // form.value.address = props.parcel?.address || props.address?.C_Location_ID?.Address1?.replace(/\d+$/, '') || ''
  form.value.address = props.parcel?.address || extractStreetName(props.address?.C_Location_ID?.Address1 || '', props.parcel?.country || props.address?.country?.CountryCode || 'DE')
  form.value.houseNumber = props.parcel?.houseNumber || extractHouseNumber(props.address?.C_Location_ID?.Address1 || '', props.parcel?.country || props.address?.country?.CountryCode || 'DE')
  form.value.address2 = props.parcel?.address2 || props.address?.C_Location_ID?.Address2 || ''
  form.value.city = props.parcel?.city || props.address?.C_Location_ID?.City || ''
  form.value.country = props.parcel?.country || props.address?.country?.CountryCode || 'DE'
  form.value.countryName = props.parcel?.countryName || props.address?.country?.Name || 'Germany'
  form.value.countryIso3 = props.address?.country?.ISOCountryCodeAlpha3 || 'DEU'
  form.value.postalCode = props.parcel?.postalCode || props.address?.C_Location_ID?.Postal || ''
  form.value.countryState = props.parcel?.countryState || ''
  form.value.toServicePoint = props.parcel?.toServicePoint || ''
  form.value.toPostNumber = props.parcel?.toPostNumber || ''
  form.value.customsInvoiceNR = props.parcel?.customsInvoiceNR || ''
  form.value.customsShipmentType = props.parcel?.customsShipmentType || ''
  form.value.weight = Number(Number(props.parcel?.weight || props.items.map(i => i.weight.toFixed(2)).reduce((acc, prev) => Number(acc) + Number(prev), 0)).toFixed(2))
  form.value.length = props.parcel?.length || props.shipment?.Volume || ''
  form.value.width = props.parcel?.width || ''
  form.value.height = props.parcel?.height || ''
  form.value.orderNumber = props.parcel?.orderNumber || props.shipment?.C_Order_ID?.ExternalOrderId || props.shipment?.C_Order_ID?.DocumentNo || ''
  form.value.totalOrderValue = props.parcel?.totalOrderValue || props.shipment?.C_Order_ID?.GrandTotal || ''
  form.value.totalOrderValueCurrency = props.parcel?.totalOrderValueCurrency || props.shipment?.C_Order_ID?.C_Currency_ID?.identifier || ''
  form.value.shippingMethodCheckoutName = props.parcel?.shippingMethodCheckoutName || ''
  form.value.senderAddress = props.parcel?.senderAddress || 1
  form.value.quantity = props.parcel?.quantity || 1
  form.value.totalInsuredValue = props.parcel?.totalInsuredValue || 0
  form.value.isReturn = props.parcel?.isReturn ?? false
  form.value.requestLabel = props.parcel?.requestLabel ?? false
  form.value.applyShippingRules = props.parcel?.applyShippingRules ?? false
  form.value.requestLabelAsync = props.parcel?.requestLabelAsync ?? false
  form.value.shipment = props.parcel?.shipment || '' //'Unstamped letter' or 'DHL Paket'
  form.value.shipmentId = props.parcel?.shipmentId ?? '' //8 or 89
  form.value.dateCreated = props.parcel?.dateCreated || ''
  form.value.dateUpdated = props.parcel?.dateUpdated || ''
  form.value.dateAnnounced = props.parcel?.dateAnnounced || ''

  if(!form.value.countryId) {
    setOptions('settings/countries/'+form.value.country+'/code', 'countries')
  }
})

onMounted(() => {
  if((form.value.shipmentId == 8 || form.value.shipmentId == '') && props.address?.country?.CountryCode) {
    setOptions('commission/shipping-methods/to_country='+props.address.country.CountryCode, 'shipping_methods')
  }
})

const handleCountry = (val, opt) => {
  form.value.countryId = opt.id
  form.value.countryState = ''
  filterOptions('c_region', 'provinces', string.urlEncode(`isActive eq true AND C_Country_ID eq ${form.value.countryId}`))
}

const submit = async (type = '') => {
  form.value.alert.processing = true

  let newObjValue = {}
  if(form.value.id === '' && props.items) {
    newObjValue = {...newObjValue,
      parcelItems: props.items
    }
  }
  if(type === 'label') {
    if(form.value.shipmentId != 8 && form.value.shipmentId != '') {
      form.value.requestLabel = true
    } else {
      toast({
        message: 'Currently the default shipment method is Unstamped letter, the label cannot be created, please choose other shipment methods first!',
        type: 'is-warning',
        duration: 2000
      })
      form.value.alert.processing = false
      return;
    }
  }

  let parcelEndpoint = 'parcels'
  if(props.shippingService === 'dhl') {
    parcelEndpoint = 'parcels/dhl'
  } else if(props.shippingService === 'other') {
    parcelEndpoint = 'parcels/other'
  }
  const res = await $fetch(`/api/commission/${parcelEndpoint}`, {
    method: form.value.id !== '' ? 'PUT' : 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      inOutId: form.value.inOutId,
      inOutUId: form.value.inOutUId,
      name: form.value.name,
      companyName: form.value.companyName,
      email: form.value.email,
      telephone: form.value.telephone,
      address: form.value.address,
      houseNumber: form.value.houseNumber,
      address2: form.value.address2,
      city: form.value.city,
      country: form.value.country,
      countryIso3: form.value.countryIso3,
      postalCode: form.value.postalCode,
      countryState: form.value.countryState,
      toServicePoint: form.value.toServicePoint,
      toPostNumber: form.value.toPostNumber,
      customsInvoiceNR: form.value.customsInvoiceNR,
      customsShipmentType: form.value.customsShipmentType,
      weight: form.value.weight,
      length: form.value.length,
      width: form.value.width,
      height: form.value.height,
      orderNumber: form.value.orderNumber,
      // Order description → CN23 "Comments" (exportDescription) when present
      orderDescription: props.shipment?.C_Order_ID?.Description || '',
      totalOrderValue: form.value.totalOrderValue,
      totalOrderValueCurrency: form.value.totalOrderValueCurrency,
      shippingMethodCheckoutName: form.value.shippingMethodCheckoutName,
      senderAddress: form.value.senderAddress,
      quantity: form.value.quantity,
      totalInsuredValue: form.value.totalInsuredValue,
      isReturn: form.value.isReturn,
      requestLabel: form.value.requestLabel,
      applyShippingRules: form.value.applyShippingRules,
      requestLabelAsync: form.value.requestLabelAsync,
      shipmentId: form.value.shipmentId,
      paketType: form.value.paketType,
      shippingPrinter: form.value.shippingPrinter,
      trackingNo: form.value.trackingNo,
      shippingService: props.shippingService,
      ...newObjValue
    }
  })

  if(Number(res.status) === 200) {
    toast({
      message: 'Saved!',
      type: 'is-success',
      duration: 2000
    })
    emit('handler', res)
    closeCommissionModal()

    if(form.value.id === '') {
      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
        })
      }
    }

    form.value = {
      id: '',
      inOutId: props.shipment?.id || '',
      inOutUId: props.shipment?.uid || '',
      name: props.shipment?.C_BPartner_Location_ID?.Name || '',
      companyName: '',
      email: props.shipment?.AD_User_ID?.EMail?.replaceAll(' ', '') || '',
      telephone: props.shipment?.C_BPartner_Location_ID?.Phone || '',
      // address: props.address?.C_Location_ID?.Address1?.replace(/\d+$/, '') || '',
      address: extractStreetName(props.address?.C_Location_ID?.Address1 || '', props.parcel?.country || props.address?.country?.CountryCode || 'DE'),
      houseNumber: extractHouseNumber(props.address?.C_Location_ID?.Address1 || '', props.parcel?.country || props.address?.country?.CountryCode || 'DE'),
      address2: props.address?.C_Location_ID?.Address2 || '',
      city: props.address?.C_Location_ID?.City || '',
      country: props.parcel?.country || props.address?.country?.CountryCode || 'DE',
      countryName: props.parcel?.countryName || props.address?.country?.Name || 'Germany',
      countryId: props.address?.country?.id || 101,
      postalCode: props.address?.C_Location_ID?.Postal || '',
      countryState: '',
      toServicePoint: '',
      toPostNumber: '',
      customsInvoiceNR: '',
      customsShipmentType: '',
      weight: Number(Number(props.items.map(i => i.weight.toFixed(2)).reduce((acc, prev) => Number(acc) + Number(prev), 0)).toFixed(2)),
      length: props.shipment?.Volume || '',
      width: '',
      height: '',
      orderNumber: props.shipment?.C_Order_ID?.ExternalOrderId || props.shipment?.C_Order_ID?.DocumentNo || '',
      totalOrderValue: props.shipment?.C_Order_ID?.GrandTotal || '',
      totalOrderValueCurrency: props.shipment?.C_Order_ID?.C_Currency_ID?.identifier || '',
      shippingMethodCheckoutName: '',
      senderAddress: 1,
      quantity: 1,
      totalInsuredValue: 0,
      isReturn: false,
      requestLabel: false,
      applyShippingRules: false,
      requestLabelAsync: false,
      shipment: '', //'Unstamped letter' or 'DHL Paket'
      shipmentId: '', //8 or 89
      dateCreated: '',
      dateUpdated: '',
      dateAnnounced: '',
      paketType: '',
      alert: {
        status: '',
        message: '',
        processing: false,
      }
    }
  } else {
    //form.value.alert.status = res.status
    //form.value.alert.message = res.message
    form.value.alert.processing = false
    toast({
      message: res.message || 'Save error',
      type: 'is-danger',
      duration: 2000
    })
    //window.scrollTo(0, 0)
  }
}
</script>

<template>
  <div class="modal" :class="{'active': showCommissionModal}" :style="{display: showCommissionModal ? '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="closeCommissionModal">
              <span class="tf-icon ti ti-x ti-sm me-1"></span>
            </div>
          </div>
        </div>
        <div class="modalBody mnh-450px">
          <div class="p-1.5rem">
            <template v-if="tab === 'customer'">
              <div class="columns">
                <div class="column is-one-third">
                  <div class="legend">
                    <label class="label">Name *</label>
                    <input type="text" v-model="form.name" class="input" />
                  </div>

                  <div class="legend mt-2">
                    <label class="label">Email</label>
                    <input type="email" v-model="form.email" class="input" />
                  </div>

                  <div class="legend mt-2">
                    <label class="label">Street name *</label>
                    <input type="text" v-model="form.address" class="input" />
                  </div>

                  <div class="legend mt-2">
                    <label class="label">Address 2 (optional)</label>
                    <input type="text" v-model="form.address2" class="input" />
                  </div>

                  <div class="legend mt-2">
                    <label class="label">City *</label>
                    <input type="text" v-model="form.city" class="input" />
                  </div>
                  
                  <div class="legend mt-2">
                    <label class="label">Postal code *</label>
                    <input type="text" v-model="form.postalCode" class="input" />
                  </div>
                </div>
                <div class="column is-one-third">
                  <div class="legend">
                    <label class="label">Company name (optional)</label>
                    <input type="text" v-model="form.companyName" class="input" />
                  </div>

                  <div class="legend mt-2">
                    <label class="label">Phone number</label>
                    <input type="text" v-model="form.telephone" class="input" />
                  </div>

                  <div class="legend mt-2">
                    <label class="label">House number *</label>
                    <input type="text" v-model="form.houseNumber" class="input" />
                  </div>

                  <div class="legend mt-2">
                    <label class="label">Destination country *</label>
                    <ClientOnly>
                      <SelectBox v-model="form.country" :options="getOptions?.['countries']?.records || [{CountryCode: form.country, Name: form.countryName}]" prop="Name" dataprop="CountryCode" datatype="string" :size="5" @load="filterOptions('c_country', 'countries')" @search="(val) => filterOptions('c_country', 'countries', string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" @change="handleCountry" :loading="loading?.['countries'] ?? true" />
                    </ClientOnly>
                  </div>

                  <div v-if="form.countryId" class="legend mt-2">
                    <label class="label">Country State</label>
                    <ClientOnly>
                      <SelectBox v-model="form.countryState" :options="getOptions?.['provinces']?.records || [{Name: form.countryState}]" prop="Name" dataprop="Name" datatype="string" :size="5" @load="filterOptions('c_region', 'provinces', string.urlEncode(`isActive eq true AND C_Country_ID eq ${form.countryId}`))" @search="(val) => filterOptions('c_region', 'provinces', string.urlEncode(`isActive eq true AND C_Country_ID eq ${form.countryId} AND contains(Name,'${val}')`))" :loading="loading?.['provinces'] ?? true" :defaultOption="true" />
                    </ClientOnly>
                  </div>
                </div>
                <div class="column is-one-third">
                  <div class="legend">
                    <label class="label">Order Number</label>
                    <input type="text" :value="form.orderNumber" class="input" readonly />
                  </div>

                  <!--<div class="legend mt-2">
                    <label class="label">Shipment Number</label>
                    <input type="text" :value="form.customsInvoiceNR" class="input" readonly />
                  </div>-->

                  <div class="legend mt-2">
                    <label class="label">Shipment ID</label>
                    <input type="text" :value="form.inOutId" class="input" readonly />
                  </div>
                  
                  <div class="legend mt-2">
                    <label class="label">Paket Type *</label>
                    <!--<input type="text" :value="form.paketType" class="input" readonly />-->
                    <select v-model="form.paketType" class="select" @change="emit('update:paketType', form.paketType)">
                      <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 class="legend mt-2">
                    <label class="label"><strong>Tisch *</strong></label>
                    <!--<input type="text" :value="form.shippingPrinter || ''" class="input" readonly />-->
                    <select v-model="form.shippingPrinter" class="select is-fullwidth" @change="emit('update:shippingPrinter', form.shippingPrinter)">
                      <option v-for="opt in printerSelectOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
                    </select>
                  </div>

                  <div v-if="form.trackingNo" class="legend mt-2">
                    <label class="label">Tracking No *</label>
                    <input type="text" :value="form.trackingNo" class="input" readonly />
                  </div>
                </div>
              </div>
            </template>
            <template v-else-if="tab === 'shipment'">
              <div class="columns">
                <div class="column is-half">
                  <div class="legend">
                    <label class="label">Order number (optional)</label>
                    <input type="text" v-model="form.orderNumber" class="input" />
                  </div>

                  <div class="legend mt-2">
                    <label class="label">Number of parcels</label>
                    <input type="text" v-model="form.quantity" class="input" />
                  </div>
                </div>
                <div class="column is-half">
                  <div class="legend">
                    <label class="label">Box (optional)</label>
                    <input type="text" class="input" readonly />
                  </div>

                  <div class="legend mt-2">
                    <label class="label">Parcel weight</label>
                    <input type="text" v-model="form.weight" class="input" />
                  </div>
                </div>
              </div>

              <div class="columns">
                <div class="column is-one-third">
                  <div class="legend mt-2">
                    <label class="label">Parcel length</label>
                    <input type="text" v-model="form.length" class="input" />
                  </div>
                </div>
                <div class="column is-one-third">
                  <div class="legend mt-2">
                    <label class="label">Parcel width</label>
                    <input type="text" v-model="form.width" class="input" />
                  </div>
                </div>
                <div class="column is-one-third">
                  <div class="legend mt-2">
                    <label class="label">Parcel height</label>
                    <input type="text" v-model="form.height" class="input" />
                  </div>
                </div>
              </div>
            </template>
            <template v-else-if="tab === 'method'">
              <div class="columns">
                <div class="column is-full">
                  <div v-if="shippingService == 'other' && shipment?.C_Order_ID?.M_Shipper_ID?.id" class="legend">
                    <label class="label">Shipping Method</label>
                    <input type="text" :value="shipment.C_Order_ID.M_Shipper_ID.identifier" class="input" />
                  </div>
                  <div v-else class="legend">
                    <label class="label">Shipping Method (Required only for label creation)</label>
                    <ClientOnly>
                      <SelectBox v-model="form.shipmentId" :options="getOptions?.['shipping_methods']?.shipping_methods || [{id: form.shipmentId, name: form.shipment}]" prop="name" dataprop="id" datatype="string" :size="5" @load="setOptions('commission/shipping-methods/to_country='+form.country, 'shipping_methods')" :loading="loading?.['shipping_methods'] ?? true" />
                    </ClientOnly>
                  </div>
                </div>
              </div>
              <div class="columns">
                <div class="column is-half">
                  <div class="legend mt-2">
                    <label class="label">Order currency</label>
                    <ClientOnly>
                      <SelectBox v-model="form.totalOrderValueCurrency" :options="getOptions?.['currencies']?.records || [{ISO_Code: form.totalOrderValueCurrency}]" prop="ISO_Code" dataprop="ISO_Code" datatype="string" :size="5" @click="filterOptions('c_currency', 'currencies')" @search="(val) => filterOptions('c_currency', 'currencies', string.urlEncode(`isActive eq true AND contains(ISO_Code,'${val}')`))" :loading="loading?.['currencies'] ?? true" />
                    </ClientOnly>
                  </div>
                </div>
                <div class="column is-half">
                  <div class="legend mt-2">
                    <label class="label">Total order value (optional)</label>
                    <input type="text" v-model="form.totalOrderValue" class="input" />
                  </div>
                </div>
              </div>
            </template>
          </div>
        </div>
        <div class="modalFooter">
          <div></div>
          <div class="d-flex items-center gap-10px">
            <button type="button" class="button" @click="closeCommissionModal">Close</button>
            <button type="button" @click="submit()" class="button" :class="(form.inOutId === '' || form.name === '' || form.address === '' || form.postalCode === '' || form.city === '' || form.country === '' || form.houseNumber === '' || form.shipmentId === '' || form.paketType === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            <button type="button" @click="submit('label')" class="button" :class="(form.shipmentId === '' || form.inOutId === '' || form.name === '' || form.address === '' || form.postalCode === '' || form.city === '' || form.country === '' || form.houseNumber === '' || form.shipmentId === '' || form.paketType === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit &amp; Create Label</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>