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

const props = defineProps({
  modelValue: Object,
  tab: String
})

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

const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
const warehouses = useCookie('logship_warehouses')
const warehouse = useCookie('logship_warehouse')
const warehouseId = useCookie('logship_warehouse_id')

const clientName = ref('')
onMounted(() => {
  const getClient = localStorage.getItem('logship_clients')
  if(getClient) {
    const clientObj = JSON.parse(getClient)
    clientName.value = clientObj[0].name
  }
  console.log('it seems the latest code is not up to date on dev-app.logship.de on current pushed')
})

const showDocumentAction = ref(false)
const form = ref({
  id: props.modelValue.id || '',
  client: props.modelValue.client|| '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  warehouse: props.modelValue.warehouse || warehouse.value?.Name || '',
  warehouseId: props.modelValue.warehouseId || warehouseId.value || '',
  isActive: props.modelValue.isActive ?? true,
  documentNo: props.modelValue.documentNo || '',
  poReference: props.modelValue.poReference || '',
  isApproved: props.modelValue.isApproved ?? false,
  isCreditApproved: props.modelValue.isCreditApproved ?? false,
  isDelivered: props.modelValue.isDelivered ?? false,
  isInvoiced: props.modelValue.isInvoiced ?? false,
  isPrinted: props.modelValue.isPrinted ?? false,
  isTransferred: props.modelValue.isTransferred ?? false,
  dateOrdered: props.modelValue.dateOrdered || date.now('date'),
  datePromised: props.modelValue.datePromised || date.now('date'),
  dateAcct: props.modelValue.dateAcct || date.now('date'),
  freightAmt: props.modelValue.freightAmt || 0,
  totalLines: props.modelValue.totalLines || 1,
  grandTotal: props.modelValue.grandTotal || 0,
  chargeAmt: props.modelValue.chargeAmt || 0,
  processed: props.modelValue.processed ?? false,
  isSOTrx: props.modelValue.isSOTrx ?? false,
  isDiscountPrinted: props.modelValue.isDiscountPrinted ?? false,
  isTaxIncluded: props.modelValue.isTaxIncluded ?? false,
  isSelected: props.modelValue.isSelected ?? false,
  sendEMail: props.modelValue.sendEMail ?? false,
  isSelfService: props.modelValue.isSelfService ?? false,
  isDropShip: props.modelValue.isDropShip ?? false,
  processedOn: props.modelValue.processedOn || 0,
  isPayScheduleValid: props.modelValue.isPayScheduleValid ?? false,
  isPriviledgedRate: props.modelValue.isPriviledgedRate ?? false,
  docStatus: props.modelValue.docStatus || '',
  docStatusId: props.modelValue.docStatusId || 'DR',
  docType: props.modelValue.docType || '',
  docTypeId: props.modelValue.docTypeId || 0,
  docTypeTarget: props.modelValue.docTypeTarget || '',
  docTypeTargetId: props.modelValue.docTypeTargetId || '',
  salesRep: props.modelValue.salesRep || '',
  salesRepId: props.modelValue.salesRepId || '',
  paymentTerm: props.modelValue.paymentTerm || '',
  paymentTermId: props.modelValue.paymentTermId || '',
  currency: props.modelValue.currency || '',
  currencyId: props.modelValue.currencyId || '',
  invoiceRule: props.modelValue.invoiceRule || '',
  invoiceRuleId: props.modelValue.invoiceRuleId || '',
  deliveryViaRule: props.modelValue.deliveryViaRule || '',
  deliveryViaRuleId: props.modelValue.deliveryViaRuleId || '',
  deliveryRule: props.modelValue.deliveryRule || '',
  deliveryRuleId: props.modelValue.deliveryRuleId || '',
  priorityRule: props.modelValue.priorityRule || '',
  priorityRuleId: props.modelValue.priorityRuleId || '',
  freightCostRule: props.modelValue.freightCostRule || '',
  freightCostRuleId: props.modelValue.freightCostRuleId || '',
  paymentRule: props.modelValue.paymentRule || '',
  paymentRuleId: props.modelValue.paymentRuleId || '',
  priceList: props.modelValue.priceList || '',
  priceListId: props.modelValue.priceListId || '',
  partner: props.modelValue.partner || '',
  partnerId: props.modelValue.partnerId || '',
  partnerLocation: props.modelValue.partnerLocation || '',
  partnerLocationId: props.modelValue.partnerLocationId || '',
  cashLine: props.modelValue.cashLine || '',
  cashLineId: props.modelValue.cashLineId || '',
  billPartner: props.modelValue.billPartner || '',
  billPartnerId: props.modelValue.billPartnerId || '',
  billPartnerLocation: props.modelValue.billPartnerLocation || '',
  billPartnerLocationId: props.modelValue.billPartnerLocationId || '',
  project: props.modelValue.project || '',
  projectId: props.modelValue.projectId || '',
  campaign: props.modelValue.campaign || '',
  campaignId: props.modelValue.campaignId || '',
  shipper: props.modelValue.shipper || '',
  shipperId: props.modelValue.shipperId || '',
  freightCategory: props.modelValue.freightCategory || '',
  freightCategoryId: props.modelValue.freightCategoryId || '',
  user: props.modelValue.user || '',
  userId:  props.modelValue.userId || '',
  billUser: props.modelValue.billUser || '',
  billUserId:  props.modelValue.billUserId || '',
  promotionCode: props.modelValue.promotionCode || '',
  dropShipPartner: props.modelValue.dropShipPartner || '',
  dropShipPartnerId: props.modelValue.dropShipPartnerId || '',
  dropShipPartnerLocation: props.modelValue.dropShipPartnerLocation || '',
  dropShipPartnerLocationId: props.modelValue.dropShipPartnerLocationId || '',
  dropShipUser: props.modelValue.dropShipUser || '',
  dropShipUserId:  props.modelValue.dropShipUserId || '',
  conversionType: props.modelValue.conversionType || '',
  conversionTypeId:  props.modelValue.conversionTypeId || '',
  orderSource: props.modelValue.orderSource || '',
  orderSourceId:  props.modelValue.orderSourceId || '',
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || '',
    processing: props.modelValue.alert.processing ?? false
  }
})

const loading = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  let newUrl = url
  if(form.value.organizationId && newUrl.endsWith('/select')) {
    newUrl = `${url}?org=${form.value.organizationId}`
  }
  const res = await $fetch('/api/'+newUrl, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    getOptions.value[key] = res
    
    if(key === 'locations' && res?.records?.[0]) {
      //getOptions.value['bill_locations'] = getOptions.value['locations']
      getOptions.value['drop_shipment_locations'] = getOptions.value['locations']
      form.value.partnerLocationId = String(res.records[0].id || '')
      form.value.partnerLocation = res.records[0].Name || ''
      //form.value.billPartnerLocation = res.records?.[1]?.Name || form.value.partnerLocation || ''
      //form.value.billPartnerLocationId = String(res.records?.[1]?.id || form.value.partnerLocationId || '')
      form.value.dropShipPartnerLocation = form.value.partnerLocation || ''
      form.value.dropShipPartnerLocationId = form.value.partnerLocationId || ''
    }
    if(key === 'bill_locations' && res?.records?.[0]) {
      form.value.billPartnerLocationId = String(res.records[0].id || '')
      form.value.billPartnerLocation = res.records[0].Name || ''
    }
    if(key === 'drop_shipment_locations' && res?.records?.[0]) {
      form.value.dropShipPartnerLocationId = String(res.records[0].id || '')
      form.value.dropShipPartnerLocation = res.records[0].Name || ''
    }
    if(key === 'users' && res?.records?.[0]) {
      getOptions.value['bill_users'] = getOptions.value['users']
      getOptions.value['drop_shipment_users'] = getOptions.value['users']
      form.value.userId = String(res.records[0].id || '')
      form.value.user = res.records[0].Name || ''
      form.value.billUserId = form.value.userId || ''
      form.value.billUser = form.value.user || ''
      form.value.dropShipUserId = form.value.userId || ''
      form.value.dropShipUser = form.value.user || ''
    }
    if(key === 'bill_users' && res?.records?.[0]) {
      form.value.billUserId = String(res.records[0].id || '')
      form.value.billUser = res.records[0].Name || ''
    }
    if(key === 'drop_shipment_users' && res?.records?.[0]) {
      form.value.dropShipUserId = String(res.records[0].id || '')
      form.value.dropShipUser = res.records[0].Name || ''
    }
    if(key === 'locations' && form.value.partnerId && url !== 'partners/partners/'+form.value.partnerId+'/locations' && Number(res?.records?.length || 0) === 0) {
      setOptions('partners/partners/'+form.value.partnerId+'/locations', 'locations')
    }
    if(key === 'bill_locations' && form.value.billPartnerId && url !== 'partners/partners/'+form.value.billPartnerId+'/locations' && Number(res?.records?.length || 0) === 0) {
      setOptions('partners/partners/'+form.value.billPartnerId+'/locations', 'bill_locations')
    }
    if(key === 'drop_shipment_locations' && form.value.dropShipPartnerId && url !== 'partners/partners/'+form.value.dropShipPartnerId+'/locations' && Number(res?.records?.length || 0) === 0) {
      setOptions('partners/partners/'+form.value.dropShipPartnerId+'/locations', 'drop_shipment_locations')
    }
    if(key === 'warehouses' && res?.records?.[0]) {
      form.value.warehouseId = String(res.records[0].id || '')
      form.value.warehouse = res.records[0].Name || ''
    }
  }
  loading.value[key] = false
}

const populateByPartner = (val, opt) => {
  form.value.partner = opt.Name || ''
  form.value.partnerId = opt.id || ''
  form.value.billPartner = opt.Name || ''
  form.value.billPartnerId = opt.id || ''
  form.value.dropShipPartner = opt.Name || ''
  form.value.dropShipPartnerId = opt.id || ''
  setOptions('partners/partners/'+opt.id+'/locations/ship', 'locations')
  setOptions('partners/partners/'+opt.id+'/locations/bill', 'bill_locations')
  setOptions('partners/partners/'+opt.id+'/users', 'users')
  //setOptions('partners/partners/'+opt.id+'/users/ship', 'users')
  //setOptions('partners/partners/'+opt.id+'/users/bill', 'bill_users')
  form.value.isDropShip = true
}

const populateByBillPartner = (val, opt) => {
  form.value.billPartner = opt.Name || ''
  form.value.billPartnerId = opt.id || ''
  setOptions('partners/partners/'+opt.id+'/locations/bill', 'bill_locations')
  setOptions('partners/partners/'+opt.id+'/users', 'bill_users')
  //setOptions('partners/partners/'+opt.id+'/users/bill', 'bill_users')
}

const populateByDropShipPartner = (val, opt) => {
  form.value.dropShipPartner = opt.Name || ''
  form.value.dropShipPartnerId = opt.id || ''
  setOptions('partners/partners/'+opt.id+'/locations', 'drop_shipment_locations')
  setOptions('partners/partners/'+opt.id+'/users', 'drop_shipment_users')
  //setOptions('partners/partners/'+opt.id+'/users/ship', 'drop_shipment_users')
}

const populateByLocation = (val, opt) => {
  /*if(form.value.partnerId == form.value.billPartnerId) {
    form.value.billPartnerLocation = opt.Name || ''
    form.value.billPartnerLocationId = opt.id || ''
  }*/
  if(form.value.partnerId == form.value.dropShipPartnerId) {
    form.value.dropShipPartnerLocation = opt.Name || ''
    form.value.dropShipPartnerLocationId = opt.id || ''
  }
}

const populateByUser = (val, opt) => {
  if(form.value.partnerId == form.value.billPartnerId) {
    form.value.billUser = opt.Name || ''
    form.value.billUserId = opt.id || ''
  }
  if(form.value.partnerId == form.value.dropShipPartnerId) {
    form.value.dropShipUser = opt.Name || ''
    form.value.dropShipUserId = opt.id || ''
  }
}

const priceListHandler = (val, opt) => {
  form.value.currency = opt?.C_Currency_ID?.identifier || ''
  form.value.currencyId = opt?.C_Currency_ID?.id || ''
}

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

const debounce = (func, timeout = 300) => {
  let timer;
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => { func.apply(this, args); }, timeout)
  }
}

const save = debounce(() => {
  emit('update:modelValue', form.value)
  emit('save', form.value)
})

const changeOrganization = (val, opt) => {
  form.value.organization = opt.name
  form.value.partner = ''
  form.value.partnerId = ''
  form.value.billPartner = ''
  form.value.billPartnerId = ''
  form.value.dropShipPartner = ''
  form.value.dropShipPartnerId = ''
  form.value.partnerLocation = ''
  form.value.partnerLocationId = ''
  form.value.billPartnerLocation = ''
  form.value.billPartnerLocationId = ''
  form.value.dropShipPartnerLocation = ''
  form.value.dropShipPartnerLocationId = ''
  form.value.user = ''
  form.value.userId = ''
  form.value.billUser = ''
  form.value.billUserId = ''
  form.value.dropShipUser = ''
  form.value.dropShipUserId = ''
  setOptions('filters/m_warehouse/'+string.urlEncode(`ad_org_id eq ${opt.id}`), 'warehouses')
  save()
}
</script>

<template>
  <div @mouseleave.self="save">
    <div class="my-5 mx-5">
      <!--<AlertAction v-model='form.alert.status' :alert="form.alert" />-->

      <template v-if="tab === 'order'">
        
        <div class="columns is-one-thirds">

          <div class="column">
            <div class="legend">
              <label class="label">Document Number</label>
              <input type="text" v-model="form.documentNo" class="input" placeholder="<Automatically Generated>" :readonly="form.docStatusId === 'CO'" @keyup="save" />
            </div>

            <div class="legend mt-2">
              <label class="label">Target Document Type *</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.docTypeTarget" class="input" readonly />
              <ClientOnly v-else>
                <SelectBox v-model="form.docTypeTargetId" :options="getOptions?.['doc_type_targets']?.records || [{id: form.docTypeTargetId, Name: form.docTypeTarget}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('types/POO', 'doc_type_targets')" @change="save" :loading="loading?.['doc_type_targets'] ?? true" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Order Reference</label>
              <input type="text" v-model="form.poReference" class="input" :readonly="form.docStatusId === 'CO'" @keyup="save" />
            </div>

            <div class="legend mt-2">
              <label class="label">Description</label>
              <textarea v-model="form.description" class="input" :readonly="form.docStatusId === 'CO'" @keyup="save"></textarea>
            </div>
          </div>

          <div class="is-divider-vertical" data-content="+"></div>

          <div class="column">
<!--          <div class="column importantwrapper">-->
            <div class="legend">
              <label class="label d-block">Business Partner *</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.partner" class="input" readonly />
              <ClientOnly v-else>
                <ComboBox v-model="form.partnerId" :options="getOptions?.['partners']?.records || [{id: form.partnerId, Name: form.partner}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions(`partners/partners/select?org=${form.organizationId}&vendor=true`, 'partners')" :loading="loading?.['partners'] ?? true" @change="(val, opt) => {populateByPartner(val, opt); save();}" :select="true" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Partner Location *</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.partnerLocation" class="input" readonly />
              <ClientOnly v-else>
                <ComboBox v-model="form.partnerLocationId" :options="getOptions?.['locations']?.records || [{id: form.partnerLocationId, Name: form.partnerLocation}]" prop="Name" dataprop="id" datatype="string" :size="5" :loading="false" @click="setOptions((form.partnerId ? 'partners/partners/'+form.partnerId+'/locations/ship' : 'settings/locations'), 'locations')" @change="(val, opt) => {populateByLocation(val, opt); save();}" :select="true" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">User Contact</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.user" class="input" readonly />
              <ClientOnly v-else>
                <ComboBox v-model="form.userId" :options="getOptions?.['users']?.records || [{id: form.userId, Name: form.user}]" @click="setOptions((form.partnerId ? 'partners/partners/'+form.partnerId+'/users' : 'models/ad_user'), 'users')" prop="Name" dataprop="id" datatype="string" :size="5" :loading="loading?.['users'] ?? true" @change="(val, opt) => {populateByUser(val, opt); save();}" :select="true" />
              </ClientOnly>
            </div>
          </div>

          <div class="column">
            <div class="legend">
              <label class="label">Bill Partner</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.billPartner" class="input" readonly />
              <ClientOnly v-else>
                <ComboBox v-model="form.billPartnerId" :options="getOptions?.['bill_partners']?.records || [{id: form.billPartnerId, Name: form.billPartner}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions(`partners/partners/select?org=${form.organizationId}&vendor=true`, 'bill_partners')" :loading="loading?.['bill_partners'] ?? true" @change="(val, opt) => {populateByBillPartner(val, opt); save();}" :select="true" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Bill Location</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.billPartnerLocation" class="input" readonly />
              <ClientOnly v-else>
                <ComboBox v-model="form.billPartnerLocationId" :options="getOptions?.['bill_locations']?.records || [{id: form.billPartnerLocationId, Name: form.billPartnerLocation}]" prop="Name" dataprop="id" datatype="string" :size="5" :loading="false" @click="setOptions((form.billPartnerId ? 'partners/partners/'+form.billPartnerId+'/locations/bill' : 'settings/locations'), 'bill_locations')" @change="save" :select="true" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Bill Contact</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.billUser" class="input" readonly />
              <ClientOnly v-else>
                <ComboBox v-model="form.billUserId" :options="getOptions?.['bill_users']?.records || [{id: form.billUserId, Name: form.billUser}]" @click="setOptions((form.billPartnerId ? 'partners/partners/'+form.billPartnerId+'/users' : 'models/ad_user'), 'bill_users')" @change="save" prop="Name" dataprop="id" datatype="string" :size="5" :loading="loading?.['bill_users'] ?? true" :select="true" />
              </ClientOnly>
            </div>
          </div>

          <div class="is-divider-vertical" data-content="General"></div>

          <div class="column is-one-third">

            <div class="columns">
              <div class="column">
                <div class="legend">
                  <label class="label d-block">Date Ordered *</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.dateOrdered" class="input" readonly />
                  <DatePicker v-else class="pickerEnd" v-model="form.dateOrdered" :max="form.datePromised" @handler="save" />
                </div>
              </div>

              <div class="column">
                <div class="legend">
                  <label class="label d-block">Date Promised *</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.datePromised" class="input" readonly />
                  <DatePicker v-else class="pickerEnd" v-model="form.datePromised" :min="form.dateOrdered" :add="form.id ? 0 : 14" @handler="save" />
                </div>
              </div>
            </div>

            <div class="legend">
              <label class="label">Organization *</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.organization" class="input" readonly />
              <SelectBox v-else v-model="form.organizationId" :options="getOptions?.['orgs']?.records || [{id: form.organizationId, Name: form.organization}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_org', 'orgs')" @change="changeOrganization" :loading="loading?.['orgs'] ?? true" />
            </div>

            <div class="legend mt-2">
              <label class="label">Tenant *</label>
              <input type="text" :value="clientName" class="input" readonly />
            </div>

            <div class="columns mt-2">
              <div class="column">
                <div class="d-flex flexDirection-column">
                  <div class="check">
                    <input type="checkbox" v-model="form.isActive" class="checkInput" id="isActive" :checked="form.isActive" :disabled="form.docStatusId === 'CO'" @change="save">
                    <label class="checkLabel" for="isActive">Active</label>
                  </div>
                  <div class="check">
                    <input type="checkbox" v-model="form.isSelfService" class="checkInput" id="isSelfService" :checked="form.isSelfService" :disabled="form.docStatusId === 'CO'" @change="save">
                    <label class="checkLabel" for="isSelfService">Self-Service</label>
                  </div>
                  <div class="check">
                    <input type="checkbox" v-model="form.isDiscountPrinted" class="checkInput" id="isDiscountPrinted" :checked="form.isDiscountPrinted" :disabled="form.docStatusId === 'CO'" @change="save">
                    <label class="checkLabel" for="isDiscountPrinted">Discount Printed</label>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'delivery'">
        <div class="columns is-desktop">
          <div class="column is-half">
            <label class="label d-block">Warehouse *</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.warehouse" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-if="form.organizationId" v-model="form.warehouseId" :options="getOptions?.['warehouses']?.records || [{id: form.warehouseId, Name: form.warehouse}]" prop="Name" dataprop="id" datatype="string" :size="5" @load="setOptions('filters/m_warehouse/'+string.urlEncode(`ad_org_id eq ${form.organizationId}`), 'warehouses')" @change="save" :loading="loading?.['warehouses'] ?? true" />
              <SelectBox v-else v-model="form.warehouseId" :options="warehouses" @change="(val, opt) => {form.warehouse = opt.name; save();}" prop="name" dataprop="id" datatype="string" :size="5" />
            </ClientOnly>

            <label class="label d-block mt-2">Delivery Via *</label>
            <select v-model="form.deliveryViaRuleId" class="select" :disabled="form.docStatusId === 'CO'" @change="save">
              <option value="D">Delivery</option>
              <option value="P">Pickup</option>
              <option value="S">Shipper</option>
            </select>
          </div>
          <div class="column is-half">
            <label class="label d-block">Priority *</label>
            <select v-model="form.priorityRuleId" class="select" :disabled="form.docStatusId === 'CO'" @change="save">
              <option value="3">High</option>
              <option value="7">Low</option>
              <option value="5">Medium</option>
              <option value="9">Minor</option>
              <option value="1">Urgent</option>
            </select>
            
            <label class="label d-block mt-2">Delivery Status</label>
            <div class="check">
              <input type="checkbox" v-model="form.isDropShip" class="checkInput" id="isDropShip" :checked="form.isDropShip" :disabled="form.docStatusId === 'CO'" @change="save">
              <label class="checkLabel" for="isDropShip">Drop Shipment</label>
            </div>
          </div>
        </div>
        <div v-if="form.deliveryViaRuleId === 'S'" class="columns is-desktop">
          <div class="column is-half">
            <label class="label d-block mt-2">Shipper</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.shipper" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.shipperId" :options="getOptions?.['shippers']?.records || [{id: form.shipperId, Name: form.shipper}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_shipper', 'shippers')" @change="save" :loading="loading?.['shippers'] ?? true" />
            </ClientOnly>
          </div>
          <div class="column is-half">
            <label class="label d-block mt-2">Freight Category</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.freightCategory" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.freightCategoryId" :options="getOptions?.['freight_categories']?.records || [{id: form.freightCategoryId, Name: form.freightCategory}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_freightcategory', 'freight_categories')" @change="save" :loading="loading?.['freight_categories'] ?? true" />
            </ClientOnly>
          </div>
        </div>
        <div v-if="form.isDropShip" class="columns is-desktop">
          <div class="column is-one-third">
            <label class="label d-block mt-2">Drop Shipment Partner *</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.dropShipPartner" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.dropShipPartnerId" :options="getOptions?.['drop_shipment_partners']?.records || [{id: form.dropShipPartnerId, Name: form.dropShipPartner}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('partners/partners', 'drop_shipment_partners')" :loading="loading?.['drop_shipment_partners'] ?? true" @change="(val, opt) => {populateByDropShipPartner(val, opt); save();}" />
            </ClientOnly>
          </div>
          <div class="column is-one-third">
            <label class="label d-block mt-2">Drop Shipment Location *</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.dropShipPartnerLocation" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.dropShipPartnerLocationId" :options="getOptions?.['drop_shipment_locations']?.records || [{id: form.dropShipPartnerLocationId, Name: form.dropShipPartnerLocation}]" prop="Name" dataprop="id" datatype="string" :size="5" :loading="false" @click="setOptions((form.dropShipPartnerId ? 'partners/partners/'+form.dropShipPartnerId+'/locations' : 'settings/locations'), 'drop_shipment_locations')" @change="save" />
            </ClientOnly>
          </div>
          <div class="column is-one-third">
            <label class="label d-block mt-2">Drop Shipment Contact</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.dropShipUser" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.dropShipUserId" :options="getOptions?.['drop_shipment_users']?.records || [{id: form.dropShipUserId, Name: form.dropShipUser}]" @click="setOptions((form.dropShipPartnerId ? 'partners/partners/'+form.dropShipPartnerId+'/users/ship' : 'models/ad_user'), 'drop_shipment_users')" @change="save" prop="Name" dataprop="id" datatype="string" :size="5" :loading="loading?.['drop_shipment_users'] ?? true" />
            </ClientOnly>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'invoicing'">
        <div class="columns is-desktop">
          <div class="column is-half">
            <label class="label d-block">Price List *</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.priceList" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.priceListId" :options="getOptions?.['price_lists']?.records || [{id: form.priceListId, Name: form.priceList}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('materials/price-lists', 'price_lists')" @change="save" :loading="loading?.['price_lists'] ?? true" />
            </ClientOnly>

            <!---<label class="label d-block mt-2">Order Source</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.orderSource" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.orderSourceId" :options="getOptions?.['order_sources']?.records || [{id: form.orderSourceId, Name: form.orderSource}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_ordersource', 'order_sources')" @change="save" :loading="loading?.['order_sources'] ?? true" />
            </ClientOnly>-->

            <label class="label d-block mt-2">Company Agent *</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.salesRep" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.salesRepId" :options="getOptions?.['sales_reps']?.records || [{id: form.salesRepId, Name: form.salesRep}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('admin/users', 'sales_reps')" @change="save" :loading="loading?.['sales_reps'] ?? true" />
            </ClientOnly>

            <label class="label d-block mt-2">Payment Rule *</label>
            <select v-model="form.paymentRuleId" class="select" @change="save">
              <option value="B">Cash</option>
              <option value="S">Check</option>
              <option value="K">Credit Card</option>
              <option value="T">Direct Deposit</option>
              <option value="M">Mixed POS Payment</option>
              <option value="P">On Credit</option>
            </select>
          </div>
          <div class="column is-half">
            <label class="label d-block">Currency *</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.currency" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.currencyId" :options="getOptions?.['currencies']?.records || [{id: form.currencyId, ISO_Code: form.currency}]" prop="ISO_Code" dataprop="id" datatype="string" :size="5" @click="setOptions('settings/currencies', 'currencies')" @change="save" :loading="loading?.['currencies'] ?? true" />
            </ClientOnly>

            <label class="label d-block mt-2">Currency Type</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.conversionType" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.conversionTypeId" :options="getOptions?.['conversion_types']?.records || [{id: form.conversionTypeId, Name: form.conversionType}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_conversiontype', 'conversion_types')" @change="save" :loading="loading?.['conversion_types'] ?? true" />
            </ClientOnly>

            <!--<label class="label d-block mt-2">Payment Term *</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.paymentTerm" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.paymentTermId" :options="getOptions?.['payment_terms']?.records || [{id: form.paymentTermId, Name: form.paymentTerm}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('partners/payment-terms', 'payment_terms')" @change="save" :loading="loading?.['payment_terms'] ?? true" />
            </ClientOnly>
            
            <label class="label d-block mt-2">Promotion Code</label>
            <input type="text" v-model="form.promotionCode" class="input" :readonly="form.docStatusId === 'CO'" @keyup="save" />-->
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'reference'">
        <div class="columns is-desktop">
          <div class="column is-half">
            <label class="label d-block">Project</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.project" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.projectId" :options="getOptions?.['projects']?.records || [{id: form.projectId, Name: form.project}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('projects', 'projects')" @change="save" :loading="loading?.['projects'] ?? true" />
            </ClientOnly>
          </div>
          <div class="column is-half">
            <label class="label d-block">Campaign</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.campaign" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.campaignId" :options="getOptions?.['campaigns']?.records || [{id: form.campaignId, Name: form.campaign}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('marketings/campaigns', 'campaigns')" @change="save" :loading="loading?.['campaigns'] ?? true" />
            </ClientOnly>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'status'">
        <div class="columns is-desktop">
          <div class="column is-half">
            <label class="label d-block">Document Status</label>
            <select v-model="form.docStatusId" class="select" disabled>
              <option value="CO">Completed</option>
              <option value="DR">Drafted</option>
              <option value="VO">Void</option>
            </select>

            <label class="label d-block mt-2">Total Lines</label>
            <input type="text" :value="form.totalLines" class="input" readonly />

            <label class="label d-block mt-2">Cash Plan Line</label>
            <input v-if="form.docStatusId === 'CO'" type="text" :value="form.cashLine" class="input" readonly />
            <ClientOnly v-else>
              <SelectBox v-model="form.cashLineId" :options="getOptions?.['cash_lines']?.records || [{id: form.cashLineId, Line: form.cashLine}]" prop="Line" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_cashline', 'cash_lines')" @change="save" :loading="loading?.['cash_lines'] ?? true" />
            </ClientOnly>
          </div>
          <div class="column is-half">
            <label class="label d-block">Document Type</label>
            <select v-model="form.docTypeId" class="select" disabled>
              <option :value="0">** New **</option>
            </select>

            <label class="label d-block mt-2">Grand Total</label>
            <input type="text" :value="form.grandTotal" class="input" readonly />

            <label class="label d-block mt-2">Pay Schedule</label>
            <div class="check">
              <input type="checkbox" v-model="form.isPayScheduleValid" class="checkInput" id="isPayScheduleValid" :checked="form.isPayScheduleValid" :disabled="form.docStatusId === 'CO'" @change="save">
              <label class="checkLabel" for="isPayScheduleValid">Pay Schedule Valid</label>
            </div>
          </div>
        </div>

        <!--<div v-if="form.id !== '' && form.docStatusId !== 'CO'" class="mt-2">
          <button type="button" class="button" @click="showDocumentAction = true">Document Action</button>
        </div>-->
      </template>

    </div>
  </div>

  <!--<Teleport to="body">
    <ProcurementsOrderDocumentAction v-model="showDocumentAction" :id="form.id" v-model:docId="form.docStatusId"/>
  </Teleport>-->
</template>