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

const route = useRoute()
const config = useRuntimeConfig()
const organizationId = useCookie('logship_organization_id')
const warehouseId = useCookie('logship_warehouse_id')

const props = defineProps({
  modelValue: Array,
  action: String,
  info: Object
})

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

const entries = ref(props.modelValue || [])
watch(() => props.modelValue, () => {
  entries.value = props.modelValue
})

const lineNumber = computed(() => {
  let lineNum = 1
  if(Number(entries.value.length || 0) === 1) {
    lineNum = 2
  } else if(Number(entries.value.length || 0) >= 2) {
    lineNum = Number(array.math(entries.value, 'max', 'line')) + 1
  }
  return lineNum
})

const addLine = () => {
  entries.value.push({
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    invoice: props.info?.documentNo || '',
    invoiceId: props.info?.id || '',
    isActive: true,
    line: lineNumber.value,
    product: '',
    productId: '',
    gallery: {},
    galleries: [],
    qtyEntered: 1,
    qtyInvoiced: 0.0,
    uom: '',
    uomId: '',
    priceActual: 0,
    priceEntered: 0,
    priceList: 0,
    tax: '',
    taxId: '',
    lineNetAmt: 0,
    orderLine: '',
    orderLineId: '',
    inOutLine: '',
    inOutLineId: '',
    attributeSetInstance: '',
    attributeSetInstanceId: '',
    charge: '',
    chargeId: '',
    project: '',
    projectId: '',
    campaign: '',
    campaignId: '',
    show: false,
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  })
}

const loading = ref({})
const filtering = ref({})
const products = ref({})
const getOptions = 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 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.startsWith('products_')) {
      products.value[key] = res?.records || []
      const newProducts = []
      for(let item of res?.records || []) {
        if(item?.Strapi_Product_documentId) {
          const resp = await $fetch(`/api/materials/products/${item.Strapi_Product_documentId}/galleries`)
          if(resp?.data) {
            item.galleries = resp.data?.image ?? []
            item.gallery = filterProductGallery(item.galleries, resp.data)
          }
        }
        newProducts.push(item)
      }
      products.value[key] = newProducts
    }
    if(key.startsWith('order_lines') && Number(res?.records?.length) >= 1) {
      getOptions.value[key].records = res.records.map(item => {
        item.name = `${props.info?.documentNo || ''}_${props.info?.dateAcct || ''}_${item?.QtyEntered || ''}_${item?.LineNetAmt || ''}`
        return item
      })
    }
  }
  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 filterProducts = async (url, key, filter = '') => {
  const newOrganizationId = isNaN(props.info?.organizationId) === false ? props.info?.organizationId : organizationId.value
  const newWarehouseId = props.info?.warehouseId || warehouseId.value

  if(props.info?.priceListId) {
    const res = await $fetch(`/api/materials/products/price/version/${props.info.priceListId}`)
    if(res?.records?.length >= 1) {
      const newPriceListVersionId = res.records[0].id

      if(filter) {
        await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&m_pricelist_version_id=eq.${newPriceListVersionId}&name=fts.${filter}&org_id=${newOrganizationId}`, key)
        filtering.value[key] = filter
      } else {
        if(!filtering.value?.[key] || (filtering.value?.[key] ?? '') === '') {
          await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&m_pricelist_version_id=eq.${newPriceListVersionId}&org_id=${newOrganizationId}`, key)
        }
      }
    }
  } else {
    if(filter) {
      await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&name=fts.${filter}&org_id=${newOrganizationId}`, key)
      filtering.value[key] = filter
    } else {
      if(!filtering.value?.[key] || (filtering.value?.[key] ?? '') === '') {
        await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&org_id=${newOrganizationId}`, key)
      }
    }
  }
}

const retrieve = async () => {
  if(route.params?.id) {
    const res = await $fetch('/api/invoices/'+route.params.id+'/invoice-line', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: item?.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 || '',
          invoice: item?.C_Invoice_ID?.identifier || '',
          invoiceId: item?.C_Invoice_ID?.id || '',
          isActive: item?.IsActive ?? true,
          line: item?.Line || '',
          product: item?.M_Product_ID?.identifier || item?.M_Product_ID?.Name || '',
          productId: item?.M_Product_ID?.id || '',
          galleries: [],
          qtyEntered: item?.QtyEntered || 1,
          qtyInvoiced: item?.QtyInvoiced || 0.0,
          uom: item?.C_UOM_ID?.identifier || '',
          uomId: item?.C_UOM_ID?.id || '',
          priceActual: item?.PriceActual || 0,
          priceEntered: item?.PriceEntered || 0,
          priceList: item?.PriceList || 0,
          tax: item?.C_Tax_ID?.identifier || '',
          taxId: item?.C_Tax_ID?.id || '',
          lineNetAmt: item?.LineNetAmt || 0,
          orderLine: item?.C_OrderLine_ID?.identifier || '',
          orderLineId: item?.C_OrderLine_ID?.id || '',
          inOutLine: item?.M_InOutLine_ID?.identifier || '',
          inOutLineId: item?.M_InOutLine_ID?.id || '',
          attributeSetInstance: item?.M_AttributeSetInstance_ID?.identifier || '',
          attributeSetInstanceId: item?.M_AttributeSetInstance_ID?.id || '',
          charge: item?.C_Charge_ID?.identifier || '',
          chargeId: item?.C_Charge_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))
      
      const newEntries = []
      for(let item of entries.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)
      }
      entries.value = newEntries
    }
  }
}
onMounted(retrieve)

const destroy = async (entry, index) => {
  entries.value.splice(index, 1)

  if(entry.id) {
    await $fetch('/api/invoices/'+entry.id+'/invoice-line', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
  }
}

const chooseLineIndex = ref(NaN)
const chooseLineEntry = ref(null)
const showProductChooser = ref(false)
const hideProductCharge = ref(false)
const productChooserHandler = (prod) => {
  if(chooseLineIndex.value !== NaN && chooseLineEntry.value !== null) {
    const newEntry = chooseLineEntry.value
    newEntry.product = prod?.Name || ''
    newEntry.productId = prod?.id || ''
    newEntry.uom = prod?.uom_name || prod?.C_UOM_ID?.identifier || ''
    newEntry.uomId = prod?.c_uom_id || prod?.C_UOM_ID?.id || ''
    newEntry.priceActual = prod?.product_price || prod?.M_ProductPrice?.PriceStd || 0
    newEntry.priceEntered = prod?.product_price || prod?.M_ProductPrice?.PriceList || 0
    newEntry.priceList = prod?.product_price || prod?.M_ProductPrice?.PriceList || 0
    newEntry.charge = ''
    newEntry.chargeId = ''
    newEntry.lineNetAmt = Number(newEntry.qtyEntered) * Number(newEntry.priceEntered);
    newEntry.gallery = prod?.gallery ?? {}
  newEntry.galleries = prod?.galleries ?? []

    entries.value.splice(chooseLineIndex.value, 1, newEntry)

    chooseLineIndex.value = NaN
    chooseLineEntry.value = null
  }

  hideProductCharge.value = true
}

const productHandler = (newEntry, prod) => {
  newEntry.product = prod?.Name || ''
  newEntry.productId = prod?.id || ''
  newEntry.uom = prod?.uom_name || prod?.C_UOM_ID?.identifier || ''
  newEntry.uomId = prod?.c_uom_id || prod?.C_UOM_ID?.id || ''
  newEntry.priceActual = prod?.product_price || prod?.M_ProductPrice?.PriceStd || 0
  newEntry.priceEntered = prod?.product_price || prod?.M_ProductPrice?.PriceList || 0
  newEntry.priceList = prod?.product_price || prod?.M_ProductPrice?.PriceList || 0
  newEntry.charge = ''
  newEntry.chargeId = ''
  newEntry.lineNetAmt = Number(newEntry.qtyEntered) * Number(newEntry.priceEntered);
  newEntry.gallery = prod?.gallery ?? {}
  newEntry.galleries = prod?.galleries ?? []
  hideProductCharge.value = true
}

const enterProductHandler = (newEntry, key) => {
  const prod = products.value[key]
  if(prod.length == 1) {
    productHandler(newEntry, prod)
  }
}

const takeOrderLine = async (newEntry, opt) => {
  newEntry.product = opt?.M_Product_ID?.Name || ''
  newEntry.productId = opt?.M_Product_ID?.id || ''
  newEntry.gallery = {}
  newEntry.galleries = []
  newEntry.qtyEntered = opt?.QtyEntered || 1
  newEntry.orderLine = opt.name
  newEntry.orderLineId = opt?.id || ''
  newEntry.uom = opt?.C_UOM_ID?.identifier || ''
  newEntry.uomId = opt?.C_UOM_ID?.id || ''
  newEntry.priceActual = opt?.PriceActual || 0
  newEntry.priceEntered = opt?.PriceEntered || 0
  newEntry.priceList = opt?.PriceList || 0
  newEntry.charge = ''
  newEntry.chargeId = ''
  newEntry.lineNetAmt = Number(newEntry.qtyEntered) * Number(newEntry.priceEntered);
  newEntry.attributeSetInstance = opt?.M_AttributeSetInstance_ID?.identifier || ''
  newEntry.attributeSetInstanceId = opt?.M_AttributeSetInstance_ID?.id || ''
  newEntry.project = opt?.C_Project_ID?.identifier || ''
  newEntry.projectId = opt?.C_Project_ID?.id || ''
  newEntry.campaign = opt?.C_Campaign_ID?.identifier || ''
  newEntry.campaignId = opt?.C_Campaign_ID?.id || ''

  const response = await $fetch(`/api/materials/products/${newEntry.productId}`)
  if(response?.Strapi_Product_documentId) {
    const resp = await $fetch(`/api/materials/products/${response.Strapi_Product_documentId}/galleries`)
    if(resp?.data) {
      newEntry.galleries = resp.data?.image ?? []
      newEntry.gallery = filterProductGallery(newEntry.galleries, resp.data)
    }
  }
}

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

const showAttachmentViewer = ref(false)
const showAttachmentViewerData = ref({})
const viewAttachmentViewer = (fileData) => {
  showAttachmentViewer.value = true
  showAttachmentViewerData.value = fileData
}
watch(showAttachmentViewer, () => {
  if(!showAttachmentViewer.value) {
    showAttachmentViewerData.value = {}
  }
})
</script>

<template>
  <div class="lineTableResponsive card sd-none rd-0px bd-1px_solid_hexe4e3e6" @mouseleave="save">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th>Line</th>
            <th colspan="2">Product</th>
            <th>Unit</th>
            <th class="w-120px">Quantity</th>
            <th class="w-120px">Price</th>
            <th class="w-120px">Amount</th>
            <th class="w-100px">Active</th>
            <th v-if="action !== 'view'" class="w-100px">Action</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="Number(entries.length) === 0">
            <td :colspan="action !== 'view' ? 8 : 7" class="align-center">No detail record yet, please add a new one.</td>
          </tr>
          <template v-for="(entry, index) in entries" :key="index">
            <tr>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.line }}</span>
                <input v-else type="text" v-model="entry.line" class="input" />
              </td>
              <td>
                <div>
                  <div v-if="entry?.gallery?.id" @click="viewAttachmentViewer(entry?.gallery ?? {})">
                    <div class="productChooserBox" style="width: 40px; height: 40px;">
                      <img v-if="entry?.gallery?.formats?.small" :src="config.public.strapi+'/files-api/'+entry?.gallery?.formats?.small?.hash + entry?.gallery?.formats?.small?.ext" :alt="entry?.gallery?.name" />
                      <img v-else :src="config.public.strapi+'/files-api/'+entry?.gallery?.formats?.thumbnail?.hash + entry?.gallery?.formats?.thumbnail?.ext" :alt="entry?.gallery?.name" />
                    </div>
                  </div>
                  <div v-else class="productChooserBox" style="width: 40px; height: 40px;">
                    <img v-if="entry.productId" src="https://placehold.co/40x40" alt="Placeholder Image" />
                  </div>
                </div>
              </td>
              <td style="max-width: 400px;">
                <ContextMenu v-model="entry.productId" :items="[(entry.productId ? 'zoom' : 'clear')]" :info="{windowFrom: 'zoom', toPath: '/materials/products/'+entry.productId+'/edit', pathName: 'Product: '+entry.product}">
                  <div>
                    <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.product }}</span>
                    <ComboBox v-else v-model="entry.productId" :options="products?.['products_'+index] || [{id: entry.productId, Name: entry.product}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterProducts('materials/products/filter-elastic', 'products_'+index)" @search="(val) => filterProducts('materials/products/filter-elastic', 'products_'+index, string.urlEncode(val))" @change="(val, opt) => productHandler(entry, opt)" :loading="loading?.['products_'+index] ?? true" class="groupItem" :up="true" type="slot" :select="true" @enter="enterProductHandler(entry, 'products_'+index)">
                      <template v-slot:default="{option, selected}">
                        <div class="d-flex justify-between gap-0.75rem">
                          <div class="flexGrow-1">
                            {{ option.Name }}
                          </div>
                          <div>
                            <div v-if="option?.gallery?.id" class="productChooserBox" style="width: 32px; height: 32px;">
                              <img v-if="option?.gallery?.formats?.small" :src="config.public.strapi+'/files-api/'+option?.gallery?.formats?.small?.hash + option?.gallery?.formats?.small?.ext" :alt="option?.gallery?.name" />
                              <img v-else :src="config.public.strapi+'/files-api/'+option?.gallery?.formats?.thumbnail?.hash + option?.gallery?.formats?.thumbnail?.ext" :alt="option?.gallery?.name" />
                            </div>
                            <div v-else class="productChooserBox" style="width: 32px; height: 32px;">
                              <img src="https://placehold.co/32x32" alt="Placeholder Image" />
                            </div>
                          </div>
                        </div>
                      </template>
                    </ComboBox>
                  </div>
                </ContextMenu>
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.uom }}</span>
                <ClientOnly v-else>
                  <SelectBox v-model="entry.uomId" :options="getOptions?.['units_'+index]?.records || [{id: entry.uomId, Name: entry.uom}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_uom', 'units_'+index)" @search="(val) => filterOptions('c_uom', 'units_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['units_'+index] ?? true" :up="true" placeholder="----" />
                </ClientOnly>
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.qtyEntered }}</span>
                <input v-else type="text" v-model="entry.qtyEntered" @input="entry.lineNetAmt = Number(entry.qtyEntered) * Number(entry.priceEntered);" class="input" />
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.priceEntered }}</span>
                <input v-else type="text" v-model="entry.priceEntered" @input="entry.lineNetAmt = Number(entry.qtyEntered) * Number(entry.priceEntered);" class="input" />
              </td>
              <td>{{ entry.lineNetAmt || Number(entry.qtyEntered || 1) * Number(entry.priceEntered || 0) }}</td>
              <td>
                <div class="check">
                  <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+index" :checked="entry.isActive" :disabled="action === 'view'">
                  <label class="checkLabel" :for="'isActive_'+index">Active</label>
                </div>
              </td>
              <td v-if="action !== 'view'">
                <div class="d-flex justify-flexEnd gap-5px">
                  <span @click="entry.show = !entry.show;" class="cursor-pointer fg-warning">
                    <i v-if="entry?.show" class="menu-icon tf-icons ti ti-chevron-up"></i>
                    <i v-else class="menu-icon tf-icons ti ti-chevron-down"></i>
                  </span>
                  <span v-if="info.docStatusId !== 'CO'" @click="destroy(entry, index)" class="cursor-pointer fg-danger">
                    <i class="menu-icon tf-icons ti ti-trash"></i>
                  </span>
                </div>
              </td>
            </tr>
            <tr v-if="entry?.show">
              <td :colspan="action !== 'view' ? 8 : 7">
                <div class="my-5 mx-5">
                  <AlertAction v-model='entry.alert.status' :alert="entry.alert" />
                  <div class="columns">
                    <div class="column is-two-thirds">
                      <div class="columns">
                        <div class="column is-half">
                          <label class="label d-block">Line</label>
                          <input type="text" v-model="entry.line" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                          <label class="label d-block mt-2">Product</label>
                          <div class="d-flex gap-10px">
                            <input type="text" v-model="entry.product" class="input flexGrow-1" readonly />
                            <button v-if="action !== 'view' && info.docStatusId !== 'CO'" type="button" class="button" @click="chooseLineIndex = index; chooseLineEntry = entry; showProductChooser = true;">Choose</button>
                          </div>

                          <label class="label d-block mt-2">Attribute Set Instance</label>
                          <input type="text" class="input" readonly />
                        </div>
                        <div class="column is-half">
                          <label class="label d-block">Purchase Order Line</label>
                          <ClientOnly v-if="info.orderId">
                            <SelectBox v-model="entry.orderLineId" :options="getOptions?.['order_lines_'+index]?.records || [{id: entry.orderLineId, name: entry.orderLine}]" prop="name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_orderline', 'order_lines_'+index, string.urlEncode(`C_Order_ID eq ${info.orderId} AND isActive eq true&$expand=m_product_id`))" @change="(val, opt) => takeOrderLine(entry, opt)" :loading="loading?.['order_lines_'+index] ?? true" />
                          </ClientOnly>
                          <input v-else type="text" :value="entry.orderLine" class="input" readonly />

                          <div :class="(hideProductCharge || action === 'view' || entry.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                            <label class="label d-block mt-2">Charge</label>
                            <ClientOnly>
                              <SelectBox v-model="entry.chargeId" :options="getOptions?.['charges_'+index]?.records || [{id: entry.chargeId, Name: entry.charge}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_charge', 'charges_'+index)" @search="(val) => filterOptions('c_charge', 'charges_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['charges_'+index] ?? true" />
                            </ClientOnly>
                          </div>
                          
                          <label class="label d-block mt-2">Resource Assignment</label>
                          <input type="text" class="input" readonly />
                        </div>
                      </div>
                      
                      <label class="label d-block mt-2">Description</label>
                      <textarea v-model="entry.description" class="input" :disabled="action === 'view' || info.docStatusId === 'CO'"></textarea>

                      <div class="columns">
                        <div class="column is-half">
                          <label class="label d-block mt-2">Quantity *</label>
                          <input type="text" v-model="entry.qtyEntered" @input="entry.lineNetAmt = Number(entry.qtyEntered) * Number(entry.priceEntered);" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                          <label class="label d-block mt-2">Invoiced Quantity *</label>
                          <input type="text" v-model="entry.qtyInvoiced" class="input" readonly />
                        </div>
                        <div class="column is-half">
                          <div :class="(action === 'view' || info.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                            <label class="label d-block mt-2">UOM *</label>
                            <ClientOnly>
                              <SelectBox v-model="entry.uomId" :options="getOptions?.['units_'+index]?.records || [{id: entry.uomId, Name: entry.uom}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_uom', 'units_'+index)" @search="(val) => filterOptions('c_uom', 'units_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['units_'+index] ?? true" placeholder="----" />
                            </ClientOnly>
                          </div>

                          <label class="label d-block mt-2">Shipment/Receipt Line</label>
                          <input type="text" :value="entry.inOutLine" class="input" readonly />
                        </div>
                      </div>

                      <label class="label d-block mt-2">Price *</label>
                      <input type="text" v-model="entry.priceEntered" @input="entry.lineNetAmt = Number(entry.qtyEntered) * Number(entry.priceEntered);" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />
                        
                      <div class="columns">
                        <div class="column is-half">
                          <label class="label d-block mt-2">Unit Price *</label>
                          <input type="text" v-model="entry.priceActual" class="input" readonly />
                            
                          <div :class="(action === 'view' || info.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                            <label class="label d-block mt-2">Tax *</label>
                            <ClientOnly>
                              <SelectBox v-model="entry.taxId" :options="getOptions?.['taxes_'+index]?.records || [{id: entry.taxId, Name: entry.tax}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_tax', 'taxes_'+index)" @search="(val) => filterOptions('c_tax', 'taxes_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['taxes_'+index] ?? true" placeholder="----" />
                            </ClientOnly>
                          </div>
                            
                          <div :class="(action === 'view' || info.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                            <label class="label d-block mt-2">Project</label>
                            <ClientOnly>
                              <SelectBox v-model="entry.projectId" :options="getOptions?.['projects_'+index]?.records || [{id: entry.projectId, Name: entry.project}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_project', 'projects_'+index)" @search="(val) => filterOptions('c_project', 'projects_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['projects_'+index] ?? true" placeholder="----" :up="true" />
                            </ClientOnly>
                          </div>
                        </div>
                        <div class="column is-half">
                          <label class="label d-block mt-2">List Price *</label>
                          <input type="text" v-model="entry.priceList" class="input" readonly />
                          
                          <div :class="(action === 'view' || info.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                            <label class="label d-block mt-2">Campaign</label>
                            <ClientOnly>
                              <SelectBox v-model="entry.campaignId" :options="getOptions?.['campaigns_'+index]?.records || [{id: entry.campaignId, Name: entry.campaign}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_campaign', 'campaigns_'+index)" @search="(val) => filterOptions('c_campaign', 'campaigns_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['campaigns_'+index] ?? true" placeholder="----" :up="true" />
                            </ClientOnly>
                          </div>
                        </div>
                      </div>

                      <label class="label d-block mt-2">Line Amount</label>
                      <input type="text" v-model="entry.lineNetAmt" class="input" readonly />
                    </div>
                    <div class="column is-one-third">
                      <label class="label d-block">Tenant</label>
                      <input type="text" :value="entry.client" class="input" readonly />

                      <label class="label d-block">Organization</label>
                      <input type="text" :value="entry.organization" class="input" readonly />

                      <label class="label d-block">Warehouse</label>
                      <input type="text" :value="entry.warehouse" class="input" readonly />

                      <label class="label d-block">Status</label>
                      <div class="d-flex flexDirection-column">
                        <div class="check">
                          <input type="checkbox" v-model="entry.isActive" class="checkInput" id="isActive" :checked="entry.isActive" :disabled="action === 'view' || info.docStatusId === 'CO'">
                          <label class="checkLabel" for="isActive">Active</label>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          </template>
          <tr v-if="action !== 'view'">
            <td colspan="5">
              <button type="button" @click="addLine" class="button">Add Line</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <Teleport to="body">
    <POProductChooser v-model="showProductChooser" :info="info" @handler="productChooserHandler" />
    <AttachmentViewer v-model="showAttachmentViewer" :type="showAttachmentViewerData?.mime ?? ''" :source="(showAttachmentViewerData?.formats?.large?.url ?? showAttachmentViewerData?.url) ? config.public.strapi+'/files-api/'+(showAttachmentViewerData?.formats?.large?.url ?? showAttachmentViewerData?.url).replace('/uploads/', '') : ''" :title="showAttachmentViewerData?.name ?? ''" :width="showAttachmentViewerData?.width ?? 1366" :height="showAttachmentViewerData?.height ?? 768" />
  </Teleport>
</template>