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

const windowFrom = useWindowFrom()

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

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

const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')

const clientName = ref('')
onMounted(async () => {
  const getClient = localStorage.getItem('logship_clients')
  if(getClient) {
    const clientObj = JSON.parse(getClient)
    clientName.value = clientObj[0].name
  }

  // Load Document Type and RMA Type options on mount
  await setOptions('types/MCR', 'doc_types')
  await filterOptions('m_rmatype', 'rma_types', string.urlEncode(`isActive eq true`))

  // Auto-generate Name if empty
  if(!form.value.name) {
    const now = new Date()
    const dateStr = date.now('date')
    const timeStr = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
    const orgName = form.value.organization || organization.value?.Name || ''
    form.value.name = `RMA-${dateStr}-${timeStr}-${orgName}`
  }
})

const form = ref({
  id: props.modelValue.id || '',
  uid: props.modelValue?.uid || '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  isActive: props.modelValue.isActive ?? true,
  documentNo: props.modelValue.documentNo || '',
  isApproved: props.modelValue.isApproved ?? false,
  processed: props.modelValue.processed ?? false,
  isSOTrx: true,
  isPrinted: props.modelValue.isPrinted ?? false,
  dateAcct: props.modelValue.dateAcct || date.now('date'),
  movementDate: props.modelValue.movementDate || date.now('date'),
  poReference: props.modelValue.poReference || '',
  freightAmt: props.modelValue.freightAmt || 0,
  chargeAmt: props.modelValue.chargeAmt || 0,
  dateOrdered: props.modelValue.dateOrdered || date.now('date'),
  sendEMail: props.modelValue.sendEMail ?? false,
  noPackages: props.modelValue.noPackages || 0,
  isInTransit: props.modelValue.isInTransit ?? false,
  isInDispute: props.modelValue.isInDispute ?? false,
  volume: props.modelValue.volume || 0,
  weight: props.modelValue.weight || 0,
  isDropShip: props.modelValue.isDropShip ?? false,
  processedOn: props.modelValue.processedOn || 0,
  isAlternateReturnAddress: props.modelValue.isAlternateReturnAddress ?? false,
  movementType: props.modelValue.movementType || 'Customer Returns',
  movementTypeId: props.modelValue.movementTypeId || 'C+',
  docType: props.modelValue.docType || '',
  docTypeId: props.modelValue.docTypeId || '',
  partner: props.modelValue.partner || '',
  partnerId: props.modelValue.partnerId || '',
  partnerLocation: props.modelValue.partnerLocation || '',
  partnerLocationId: props.modelValue.partnerLocationId || '',
  user: props.modelValue.user || '',
  userId: props.modelValue.userId || '',
  dropShipPartner: props.modelValue.dropShipPartner || '',
  dropShipPartnerId: props.modelValue.dropShipPartnerId || '',
  dropShipPartnerLocation: props.modelValue.dropShipPartnerLocation || '',
  dropShipPartnerLocationId: props.modelValue.dropShipPartnerLocationId || '',
  dropShipUser: props.modelValue.dropShipUser || '',
  dropShipUserId: props.modelValue.dropShipUserId || '',
  returnPartner: props.modelValue.returnPartner || '',
  returnPartnerId: props.modelValue.returnPartnerId || '',
  returnPartnerLocation: props.modelValue.returnPartnerLocation || '',
  returnPartnerLocationId: props.modelValue.returnPartnerLocationId || '',
  returnUser: props.modelValue.returnUser || '',
  returnUserId: props.modelValue.returnUserId || '',
  warehouse: props.modelValue.warehouse || '',
  warehouseId: props.modelValue.warehouseId || '',
  deliveryRule: props.modelValue.deliveryRule || '',
  deliveryRuleId: props.modelValue.deliveryRuleId || '',
  freightCostRule: props.modelValue.freightCostRule || '',
  freightCostRuleId: props.modelValue.freightCostRuleId || '',
  deliveryViaRule: props.modelValue.deliveryViaRule || '',
  deliveryViaRuleId: props.modelValue.deliveryViaRuleId || '',
  priorityRule: props.modelValue.priorityRule || '',
  priorityRuleId: props.modelValue.priorityRuleId || '',
  order: props.modelValue.order || '',
  orderId: props.modelValue.orderId || '',
  docStatus: props.modelValue.docStatus || 'Draft',
  docStatusId: props.modelValue.docStatusId || 'DR',
  salesRep: props.modelValue.salesRep || '',
  salesRepId: props.modelValue.salesRepId || '',
  project: props.modelValue.project || '',
  projectId: props.modelValue.projectId || '',
  campaign: props.modelValue.campaign || '',
  campaignId: props.modelValue.campaignId || '',
  name: props.modelValue.name || '',
  inOut: props.modelValue.inOut || '',
  inOutId: props.modelValue.inOutId || '',
  rmaType: props.modelValue.rmaType || '',
  rmaTypeId: props.modelValue.rmaTypeId || '',
  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 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 === 'inouts' && Number(res?.records?.length) >= 1) {
      getOptions.value[key].records = res.records.map(item => {
        item.name = `${item.DocumentNo}_${item.DateAcct}`
        return item
      })
    }
    if(key === 'locations' && res?.records?.[0]) {
      getOptions.value['return_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.returnPartnerLocation = res.records?.[1]?.Name || form.value.partnerLocation || ''
      form.value.returnPartnerLocationId = String(res.records?.[1]?.id || form.value.partnerLocationId || '')
      form.value.dropShipPartnerLocation = form.value.partnerLocation || ''
      form.value.dropShipPartnerLocationId = form.value.partnerLocationId || ''
    }
    if(key === 'return_locations' && res?.records?.[0]) {
      form.value.returnPartnerLocationId = String(res.records[0].id || '')
      form.value.returnPartnerLocation = 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['return_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.returnUserId = form.value.userId || ''
      form.value.returnUser = form.value.user || ''
      form.value.dropShipUserId = form.value.userId || ''
      form.value.dropShipUser = form.value.user || ''
    }
    if(key === 'return_users' && res?.records?.[0]) {
      form.value.returnUserId = String(res.records[0].id || '')
      form.value.returnUser = 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 === 'orders' && Number(res?.records?.length) >= 1) {
      getOptions.value[key].records = res.records.map(item => {
        item.name = `${item.DocumentNo}_${item.C_BPartner_ID.identifier}_${item.DateAcct}`
        return item
      })
    }
    if(key === 'doc_types' && res?.records?.[0] && !form.value.docTypeId) {
      form.value.docTypeId = String(res.records[0].id || '')
      form.value.docType = res.records[0].Name || ''
    }
    if(key === 'rma_types' && res?.records?.[0] && !form.value.rmaTypeId) {
      form.value.rmaTypeId = String(res.records[0].id || '')
      form.value.rmaType = res.records[0].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)
    }
  }
}

const inOutLines = ref([])
const filterProductGallery = (galleries, strapiProduct) => {
  let newGallery = galleries?.[0] ?? {}
  if(strapiProduct?.Main_Image && strapiProduct?.Main_Image != 0) {
    newGallery = galleries.filter(i => i.id == strapiProduct.Main_Image)?.[0] ?? {}
  }
  return newGallery
}
/*const takeSalesOrder = async (opt) => {
  form.value.client = opt?.AD_Client_ID?.identifier || ''
  form.value.clientId = opt?.AD_Client_ID?.id || ''
  form.value.organization = opt?.AD_Org_ID?.identifier || ''
  form.value.organizationId = opt?.AD_Org_ID?.id || ''
  form.value.poReference = opt?.DocumentNo || ''
  form.value.dateOrdered = opt?.DateOrdered || date.now('date')
  form.value.partner = opt?.C_BPartner_ID?.identifier  || ''
  form.value.partnerId = opt?.C_BPartner_ID?.id || ''
  form.value.partnerLocation = opt?.C_BPartner_Location_ID?.identifier || ''
  form.value.partnerLocationId = opt?.C_BPartner_Location_ID?.id || ''
  form.value.user = opt?.AD_User_ID?.identifier || ''
  form.value.userId = opt?.AD_User_ID?.id || ''
  form.value.warehouse = opt?.M_Warehouse_ID?.identifier || ''
  form.value.warehouseId = opt?.M_Warehouse_ID?.id || ''
  form.value.salesRep = opt?.SalesRep_ID?.identifier || ''
  form.value.salesRepId = opt?.SalesRep_ID?.id || ''
  form.value.freightCostRule = opt?.FreightCostRule?.identifier || ''
  form.value.freightCostRuleId = opt?.FreightCostRule?.id || ''
  form.value.deliveryRule = opt?.DeliveryRule?.identifier || ''
  form.value.deliveryRuleId = opt?.DeliveryRule?.id || ''
  form.value.deliveryViaRule = opt?.DeliveryViaRule?.identifier || ''
  form.value.deliveryViaRuleId = opt?.DeliveryViaRule?.id || ''
  form.value.priorityRule = opt?.PriorityRule?.identifier || ''
  form.value.priorityRuleId = opt?.PriorityRule?.id || ''
  if(opt?.c_orderline) {
    inOutLines.value = opt.c_orderline.map(item => {
      return {
        id: '',
        client: item?.AD_Client_ID?.identifier || '',
        clientId: item?.AD_Client_ID?.id || '',
        organization: item?.AD_Org_ID?.identifier || '',
        organizationId: item?.AD_Org_ID?.id || '',
        warehouse: item?.M_Warehouse_ID?.identifier || '',
        warehouseId: item?.M_Warehouse_ID?.id || '',
        inOut: item?.M_InOut_ID?.identifier || '',
        inOutId: item?.M_InOut_ID?.id || '',
        locator: item?.M_Locator_ID?.identifier || item?.M_Locator_ID?.Value || '',
        locatorId: item?.M_Locator_ID?.id || '',
        product: item?.M_Product_ID?.Name || '',
        productId: item?.M_Product_ID?.id || '',
        galleries: [],
        isActive: item?.IsActive ?? true,
        line: item?.Line || '',
        isAutoProduce: item?.IsAutoProduce ?? false,
        qtyEntered: item?.QtyEntered || 1,
        processed: item?.Processed ?? false,
        targetQty: item?.TargetQty || 0,
        scrappedQty: item?.ScrappedQty || 0,
        pickedQty: item?.PickedQty || 0,
        confirmedQty: item?.ConfirmedQty || 0,
        isDescription: item?.IsDescription ?? false,
        isInvoiced: item?.IsInvoiced ?? false,
        description: item?.Description || '',
        movementQty: item?.MovementQty || 1,
        orderLine: item?.id ? `${opt?.DocumentNo || ''}_${opt?.DateAcct || ''}_${item?.QtyEntered || ''}_${item?.LineNetAmt || ''}` : '',
        orderLineId: item?.id || '',
        uom: item?.C_UOM_ID?.identifier || '',
        uomId: item?.C_UOM_ID?.id || '',
        attributeSetInstance: item?.M_AttributeSetInstance_ID?.identifier || '',
        attributeSetInstanceId: item?.M_AttributeSetInstance_ID?.id || '',
        project: item?.C_Project_ID?.identifier || '',
        projectId: item?.C_Project_ID?.id || '',
        campaign: item?.C_Campaign_ID?.identifier || '',
        campaignId: item?.C_Campaign_ID?.id || '',
        show: false,
        alert: {
          status: '',
          message: '',
          processing: false,
        }
      }
    }).sort((a, b) => Number(a.line) - Number(b.line))
    emit('update:lines', inOutLines.value)
    
    const newEntries = []
    for(let item of inOutLines.value) {
      const response = await $fetch(`/api/materials/products/${item.productId}`)
      if(response?.Strapi_Product_documentId) {
        const resp = await $fetch(`/api/materials/products/${response.Strapi_Product_documentId}/galleries`)
        if(resp?.data) {
          item.galleries = resp.data?.image ?? []
          item.gallery = filterProductGallery(item.galleries, resp.data)
        }
      }
      newEntries.push(item)
    }
    inOutLines.value = newEntries
    emit('update:lines', inOutLines.value)
  }
}*/
const takeInOut = async (opt) => {
  form.value.client = opt?.AD_Client_ID?.identifier || ''
  form.value.clientId = opt?.AD_Client_ID?.id || ''
  form.value.organization = opt?.AD_Org_ID?.identifier || ''
  form.value.organizationId = opt?.AD_Org_ID?.id || ''
  form.value.poReference = opt?.DocumentNo || ''
  form.value.dateOrdered = opt?.DateOrdered || date.now('date')
  form.value.partner = opt?.C_BPartner_ID?.identifier  || ''
  form.value.partnerId = opt?.C_BPartner_ID?.id || ''
  form.value.partnerLocation = opt?.C_BPartner_Location_ID?.identifier || ''
  form.value.partnerLocationId = opt?.C_BPartner_Location_ID?.id || ''
  form.value.user = opt?.AD_User_ID?.identifier || ''
  form.value.userId = opt?.AD_User_ID?.id || ''
  form.value.warehouse = opt?.M_Warehouse_ID?.identifier || ''
  form.value.warehouseId = opt?.M_Warehouse_ID?.id || ''
  form.value.salesRep = opt?.SalesRep_ID?.identifier || ''
  form.value.salesRepId = opt?.SalesRep_ID?.id || ''
  form.value.freightCostRule = opt?.FreightCostRule?.identifier || ''
  form.value.freightCostRuleId = opt?.FreightCostRule?.id || ''
  form.value.deliveryRule = opt?.DeliveryRule?.identifier || ''
  form.value.deliveryRuleId = opt?.DeliveryRule?.id || ''
  form.value.deliveryViaRule = opt?.DeliveryViaRule?.identifier || ''
  form.value.deliveryViaRuleId = opt?.DeliveryViaRule?.id || ''
  form.value.priorityRule = opt?.PriorityRule?.identifier || ''
  form.value.priorityRuleId = opt?.PriorityRule?.id || ''
  form.value.order = opt?.C_Order_ID?.identifier  || ''
  form.value.orderId = opt?.C_Order_ID?.id || ''
  if(opt?.m_inoutline) {
    inOutLines.value = opt.m_inoutline.map(item => {
      return {
        id: '',
        client: item?.AD_Client_ID?.identifier || '',
        clientId: item?.AD_Client_ID?.id || '',
        organization: item?.AD_Org_ID?.identifier || '',
        organizationId: item?.AD_Org_ID?.id || '',
        warehouse: item?.M_Warehouse_ID?.identifier || '',
        warehouseId: item?.M_Warehouse_ID?.id || '',
        //orderLine: item?.id ? `${opt?.DocumentNo || ''}_${opt?.DateAcct || ''}_${item?.QtyEntered || ''}_${item?.LineNetAmt || ''}` : '',
        //orderLineId: item?.id || '',
        orderLine: item?.C_OrderLine_ID?.identifier || '',
        orderLineId: item?.C_OrderLine_ID?.id || '',
        inOut: item?.M_InOut_ID?.identifier || '',
        inOutId: item?.M_InOut_ID?.id || '',
        locator: item?.M_Locator_ID?.identifier || item?.M_Locator_ID?.Value || '',
        locatorId: item?.M_Locator_ID?.id || '',
        product: item?.M_Product_ID?.Name || '',
        productId: item?.M_Product_ID?.id || '',
        galleries: [],
        isActive: item?.IsActive ?? true,
        line: item?.Line || '',
        isAutoProduce: item?.IsAutoProduce ?? false,
        qtyEntered: item?.QtyEntered || 1,
        processed: item?.Processed ?? false,
        targetQty: item?.TargetQty || 0,
        scrappedQty: item?.ScrappedQty || 0,
        pickedQty: item?.PickedQty || 0,
        confirmedQty: item?.ConfirmedQty || 0,
        isDescription: item?.IsDescription ?? false,
        isInvoiced: item?.IsInvoiced ?? false,
        description: item?.Description || '',
        movementQty: item?.MovementQty || 1,
        uom: item?.C_UOM_ID?.identifier || '',
        uomId: item?.C_UOM_ID?.id || '',
        attributeSetInstance: item?.M_AttributeSetInstance_ID?.identifier || '',
        attributeSetInstanceId: item?.M_AttributeSetInstance_ID?.id || '',
        project: item?.C_Project_ID?.identifier || '',
        projectId: item?.C_Project_ID?.id || '',
        campaign: item?.C_Campaign_ID?.identifier || '',
        campaignId: item?.C_Campaign_ID?.id || '',
        show: false,
        alert: {
          status: '',
          message: '',
          processing: false,
        }
      }
    }).sort((a, b) => Number(a.line) - Number(b.line))
    emit('update:lines', inOutLines.value)
    
    const newEntries = []
    for(let item of inOutLines.value) {
      const response = await $fetch(`/api/materials/products/${item.productId}`)
      if(response?.Strapi_Product_documentId) {
        const resp = await $fetch(`/api/materials/products/${response.Strapi_Product_documentId}/galleries`)
        if(resp?.data) {
          item.galleries = resp.data?.image ?? []
          item.gallery = filterProductGallery(item.galleries, resp.data)
        }
      }
      newEntries.push(item)
    }
    inOutLines.value = newEntries
    emit('update:lines', inOutLines.value)
  }
}

const populateByPartner = (val, opt) => {
  form.value.partner = opt.Name || ''
  form.value.partnerId = opt.id || ''
  form.value.returnPartner = opt.Name || ''
  form.value.returnPartnerId = opt.id || ''
  form.value.dropShipPartner = opt.Name || ''
  form.value.dropShipPartnerId = opt.id || ''
  setOptions('partners/partners/'+opt.id+'/locations', 'locations')
  setOptions('partners/partners/'+opt.id+'/users', 'users')
}

const populateByReturnPartner = (val, opt) => {
  form.value.returnPartner = opt.Name || ''
  form.value.returnPartnerId = opt.id || ''
  setOptions('partners/partners/'+opt.id+'/locations', 'return_locations')
  setOptions('partners/partners/'+opt.id+'/users', 'return_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')
}

const populateByLocation = (val, opt) => {
  if(form.value.partnerId == form.value.returnPartnerId) {
    form.value.returnPartnerLocation = opt.Name || ''
    form.value.returnPartnerLocationId = 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.returnPartnerId) {
    form.value.returnUser = opt.Name || ''
    form.value.returnUserId = opt.id || ''
  }
  if(form.value.partnerId == form.value.dropShipPartnerId) {
    form.value.dropShipUser = opt.Name || ''
    form.value.dropShipUserId = opt.id || ''
  }
}

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

  if(form.value.partnerId !== '' && form.value.docStatusId !== 'CO' && windowFrom.value === 'partners') {
    populateByPartner('', {id: form.value.partnerId, Name: form.value.partner})
  }
})

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)
})
</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 === 'basic'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            
            <div class="columns is-desktop">
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Name *</label>
                  <input type="text" v-model="form.name" class="input" @keyup="save" />
                </div>
              </div>
              <div class="column is-half">
                <div class="legend">
                  <label class="label">RMA Type *</label>
                  <ClientOnly>
                    <SelectBox v-model="form.rmaTypeId" :options="getOptions?.['rma_types']?.records || [{id: form.rmaTypeId, Name: form.rmaType}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('m_rmatype', 'rma_types', string.urlEncode(`isActive eq true`))" @search="(val) => filterOptions('m_rmatype', 'rma_types', string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['rma_types'] ?? true" @change="save" />
                  </ClientOnly>
                </div>
              </div>
            </div>

            <div class="columns is-desktop">
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">Document Number</label>
                  <input type="text" v-model="form.documentNo" class="input" :readonly="form.docStatusId === 'CO'" @keyup="save" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Document Type *</label>
                  <input v-if="form.docStatusId === 'CO' || form.id !== ''" type="text" :value="form.docType" class="input" readonly />
                  <ClientOnly v-else>
                    <SelectBox v-model="form.docTypeId" :options="getOptions?.['doc_types']?.records || [{id: form.docTypeId, Name: form.docType}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('types/MCR', 'doc_types')" @change="save" :loading="loading?.['doc_types'] ?? true" />
                  </ClientOnly>
                </div>
              </div>
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <!--<label class="label">Order *</label>
                  <input v-if="form.docStatusId === 'CO' || form.id !== ''" type="text" :value="form.order" class="input" readonly />
                  <ClientOnly v-else>
                    <SelectBox v-model="form.orderId" :options="getOptions?.['orders']?.records || [{id: form.orderId, name: form.order}]" prop="name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_order', 'orders', string.urlEncode(`isSOTrx eq true AND isActive eq true&$expand=c_orderline($expand=m_product_id)`))" @search="(val) => filterOptions('c_order', 'orders', string.urlEncode(`isSOTrx eq true AND isActive eq true AND contains(DocumentNo,'${val}')&$expand=c_orderline($expand=m_product_id)`))" @change="(val, opt) => {takeSalesOrder(opt); save();}" :loading="loading?.['orders'] ?? true" />
                  </ClientOnly>-->
                  <label class="label">Shipment *</label>
                  <ClientOnly>
                    <SelectBox 
                      v-model="form.inOutId" 
                      :options="getOptions?.['inouts']?.records || [{id: form.inOutId, name: form.inOut}]" 
                      prop="name" 
                      dataprop="id" 
                      datatype="string" 
                      :size="5" 
                      @load="filterOptions('m_inout', 'inouts', string.urlEncode(`startswith(MovementType,'C-') AND isActive eq true AND isSOTrx eq true AND C_Order_ID neq null`)+'&$expand=m_inoutline($expand=m_product_id)&$top=5&$orderby='+string.urlEncode('m_inout_id desc'))" 
                      @search="(val) => filterOptions('m_inout', 'inouts', string.urlEncode(`startswith(MovementType,'C-') AND isActive eq true AND isSOTrx eq true AND contains(DocumentNo,'${val}') AND C_Order_ID neq null`)+'&$expand=m_inoutline($expand=m_product_id)&$top=5&$orderby='+string.urlEncode('m_inout_id desc'))" 
                      :loading="loading?.['inouts'] ?? true" 
                      @change="(val, opt) => {takeInOut(opt); save();}" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">Order Date</label>
                  <input type="text" :value="form.dateOrdered" class="input" readonly />
                </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>
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">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}&customer=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' : '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}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_user', 'users')" :loading="loading?.['users'] ?? true" @change="(val, opt) => {populateByUser(val, opt); save();}" :select="true" />
                  </ClientOnly>
                </div>
              </div>
            </div>

            <div class="legend mt-2">
              <label class="label">Description</label>
              <textarea v-model="form.description" class="input" :disabled="form.docStatusId === 'CO'" @keyup="save"></textarea>
            </div>
          </div>
          <div class="column is-one-third">
            <div class="columns is-desktop">
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Movement Date *</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.movementDate" class="input" readonly />
                  <DatePicker v-else v-model="form.movementDate" class="pickerEnd" @handler="save" />
                </div>
              </div>
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Date Accounted *</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.dateAcct" class="input" readonly />
                  <DatePicker v-else v-model="form.dateAcct" class="pickerEnd" @handler="save" />
                </div>
              </div>
            </div>

            <div class="legend mt-2">
              <label class="label">Organization *</label>
              <input v-if="form.docStatusId === 'CO' || form.orderId !== ''" 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="(val, opt) => {form.organization = opt.name; setOptions('filters/m_warehouse/'+string.urlEncode(`ad_org_id eq ${opt.id}`), 'warehouses'); save();}" :loading="loading?.['orgs'] ?? true" />
            </div>

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

            <label class="label d-block mt-2">Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <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>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'warehouse'">
        <div class="columns is-desktop">
          <div class="column is-half">
            <div class="legend">
              <label class="label">Warehouse *</label>
              <input v-if="form.docStatusId === 'CO' || form.id !== ''" 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>
            </div>

            <div class="legend mt-2">
              <label class="label">Delivery Rule *</label>
              <select v-model="form.deliveryRuleId" class="select" :disabled="form.docStatusId === 'CO'" @change="save">
                <option value="R">After Payment</option>
                <option value="A">Availability</option>
                <option value="L">Complete Line</option>
                <option value="O">Complete Order</option>
                <option value="F">Force</option>
                <option value="M">Manual</option>
              </select>
            </div>

            <div class="legend mt-2">
              <label class="label">Sales Representative</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>
            </div>
          </div>
          <div class="column is-half">
            <div class="legend">
              <label class="label">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>
            </div>

            <div class="legend mt-2">
              <label class="label">Pick Date</label>
              <input type="text" class="input" readonly />
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'shipment'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Freight Cost Rule *</label>
                  <select v-model="form.freightCostRuleId" class="select" :disabled="form.docStatusId === 'CO'" @change="save">
                    <option value="C">Calculated</option>
                    <option value="U">Customer Account</option>
                    <option value="F">Fix price</option>
                    <option value="I">Freight included</option>
                  </select>
                </div>

                <div v-if="form.freightCostRuleId === 'F'" class="legend mt-2">
                  <label class="label">Freight Amount</label>
                  <input type="text" v-model="form.freightAmt" class="input" :readonly="form.docStatusId === 'CO'" @keyup="save" />
                </div>
              </div>
              <div class="column is-half">
                <div class="legend">
                  <label class="label">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 v-if="form.deliveryViaRuleId === 'S'" class="legend mt-2">
                  <label class="label">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>
            </div>

            <div v-if="form.deliveryViaRuleId === 'S'" class="columns is-desktop">
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">Ship Date</label>
                  <input type="text" class="input" readonly />
                </div>

                <div class="legend mt-2">
                  <label class="label">Freight Charges</label>
                  <input type="text" class="input" readonly />
                </div>

                <div class="legend mt-2">
                  <label class="label">Shipper Account Number</label>
                  <input type="text" class="input" readonly />
                </div>
              </div>
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">No Packages</label>
                  <input type="text" v-model="form.noPackages" class="input" :readonly="form.docStatusId === 'CO'" @keyup="save" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Freight Terms</label>
                  <input type="text" class="input" readonly />
                </div>
              </div>
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">Tracking No</label>
                  <input type="text" class="input" readonly />
                </div>
                
                <div class="legend mt-2">
                  <label class="label">Insurance</label>
                  <input type="text" class="input" readonly />
                </div>
              </div>
            </div>

            <div v-if="form.isDropShip" class="columns is-desktop">
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">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>
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">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>
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">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' : '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>
            </div>
            
            <div v-if="form.isAlternateReturnAddress" class="columns is-desktop">
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">Return Partner *</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.returnPartner" class="input" readonly />
                  <ClientOnly v-else>
                    <SelectBox v-model="form.returnPartnerId" :options="getOptions?.['return_partners']?.records || [{id: form.returnPartnerId, Name: form.returnPartner}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('partners/partners', 'return_partners')" :loading="loading?.['return_partners'] ?? true" @change="(val, opt) => {populateByReturnPartner(val, opt); save();}" />
                  </ClientOnly>
                </div>
              </div>
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">Return Location *</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.returnPartnerLocation" class="input" readonly />
                  <ClientOnly v-else>
                    <SelectBox v-model="form.returnPartnerLocationId" :options="getOptions?.['return_locations']?.records || [{id: form.returnPartnerLocationId, Name: form.returnPartnerLocation}]" prop="Name" dataprop="id" datatype="string" :size="5" :loading="false" @click="setOptions((form.dropShipPartnerId ? 'partners/partners/'+form.returnPartnerId+'/locations' : 'settings/locations'), 'return_locations')" @change="save" />
                  </ClientOnly>
                </div>
              </div>
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">Return User/Contact</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.returnUser" class="input" readonly />
                  <ClientOnly v-else>
                    <SelectBox v-model="form.returnUserId" :options="getOptions?.['return_users']?.records || [{id: form.returnUserId, Name: form.returnUser}]" @click="setOptions((form.returnPartnerId ? 'partners/partners/'+form.returnPartnerId+'/users' : 'models/ad_user'), 'return_users')" prop="Name" dataprop="id" datatype="string" :size="5" :loading="loading?.['return_users'] ?? true" @change="save" />
                  </ClientOnly>
                </div>
              </div>
            </div>
          </div>
          <div class="column is-one-third">
            <label class="label d-block mt-2">Shipment Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <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 class="check">
                <input type="checkbox" v-model="form.isAlternateReturnAddress" class="checkInput" id="isAlternateReturnAddress" :checked="form.isAlternateReturnAddress" :disabled="form.docStatusId === 'CO'" @change="save">
                <label class="checkLabel" for="isAlternateReturnAddress">Alternate Return Address</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'reference'">
        <div class="columns is-desktop">
          <div class="column is-half">
            <div class="legend">
              <label class="label">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>
          <div class="column is-half">
            <div class="legend">
              <label class="label">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>
        </div>
      </template>
      <template v-else-if="tab === 'status'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Movement Type *</label>
                  <select v-model="form.movementTypeId" class="select" disabled>
                    <option value="C+">Customer Returns</option>
                  </select>
                </div>

                <div class="legend mt-2">
                  <label class="label">Date Received</label>
                  <input type="text" class="input" readonly />
                </div>
              </div>
              <div class="column is-half">
                <div class="legend">
                  <label class="label">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>
                </div>
              </div>
            </div>
          </div>
          <div class="column is-one-third">
            <label class="label d-block mt-2">Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isInTransit" class="checkInput" id="isInTransit" :checked="form.isInTransit" disabled>
                <label class="checkLabel" for="isInTransit">In Transit</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isInDispute" class="checkInput" id="isInDispute" :checked="form.isInDispute" :disabled="form.docStatusId === 'CO'" @change="save">
                <label class="checkLabel" for="isInDispute">In Dispute</label>
              </div>
            </div>
          </div>
        </div>
      </template>

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