<script setup>
import { date, array, string } from 'alga-js'
import { DatePicker } from 'tedir-calendar'
import { SelectBox } from 'tedir-select'
import { toast } from 'bulma-toast'
import { jsPDF } from 'jspdf'
import DOMPurify from 'dompurify'
import JsBarcode from 'jsbarcode'
import { createCanvas } from 'canvas'

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

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

const entries = ref([])
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 form = ref({
  id: '',
  client: props.info?.client || '',
  clientId: props.info?.clientId || '',
  organization: props.info?.organization || '',
  organizationId: props.info?.organizationId || organizationId.value || '',
  warehouse: props.info?.warehouse || '',
  warehouseId: props.info?.warehouseId || '',
  inOut: props.info?.documentNo || '',
  inOutId: props.info?.id || '',
  locator: '',
  locatorId: '',
  locatorX: '0',
  locatorY: '0',
  locatorZ: '0',
  product: '',
  productId: '',
  productValue: '',
  productSKU: '',
  productASIN: '',
  productUPC: '',
  galleries: [],
  labelPrinter: '',
  labelPrinterId: '',
  isActive: true,
  line: '',
  isAutoProduce: false,
  qtyEntered: 1,
  movementQty: 1,
  processed: false,
  targetQty: 0,
  scrappedQty: 0,
  pickedQty: 0,
  confirmedQty: 0,
  isDescription: false,
  isInvoiced: false,
  description: '',
  orderLine: '',
  orderLineId: '',
  uom: '',
  uomId: '',
  attributeSetInstance: '',
  attributeSetInstanceId: '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

watch(() => props.info, () => {
  form.value.client = props.info?.client || ''
  form.value.clientId = props.info?.clientId || ''
  form.value.organization = props.info?.organization || ''
  form.value.organizationId = props.info?.organizationId || organizationId.value || ''
  form.value.warehouse = props.info?.warehouse || ''
  form.value.warehouseId = props.info?.warehouseId || ''
  form.value.inOut = props.info?.documentNo || ''
  form.value.inOutId = props.info?.id || ''
  if(form.value.warehouseId) {
    setOptions('materials/locators/'+form.value.warehouseId, 'locators')
  }
})

const addLine = () => {
  if(props.info?.warehouseId) {
    setOptions('materials/locators/'+props.info.warehouseId, 'locators')
  }

  entries.value.push({
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    warehouse: props.info?.warehouse || '',
    warehouseId: props.info?.warehouseId || '',
    inOut: props.info?.documentNo || '',
    inOutId: props.info?.id || '',
    locator: form.value.locator || '',
    locatorId: form.value.locatorId || '',
    locatorX: form.value.locatorX ?? '0',
    locatorY: form.value.locatorY ?? '0',
    locatorZ: form.value.locatorZ ?? '0',
    product: '',
    productId: '',
    productValue: '',
    productSKU: '',
    productASIN: '',
    productUPC: '',
    galleries: [],
    labelPrinter: '',
    labelPrinterId: '',
    isActive: true,
    line: lineNumber.value,
    isAutoProduce: false,
    qtyEntered: 1,
    movementQty: 1,
    processed: false,
    targetQty: 0,
    scrappedQty: 0,
    pickedQty: 0,
    confirmedQty: 0,
    isDescription: false,
    isInvoiced: false,
    description: '',
    orderLine: '',
    orderLineId: '',
    uom: '',
    uomId: '',
    attributeSetInstance: '',
    attributeSetInstanceId: '',
    project: '',
    projectId: '',
    campaign: '',
    campaignId: '',
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  })
}

const showDetailRecordModal = ref(false)
const closeDetailRecordModal = () => {
  showDetailRecordModal.value = false

  form.value = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    warehouse: props.info?.warehouse || '',
    warehouseId: props.info?.warehouseId || '',
    inOut: props.info?.documentNo || '',
    inOutId: props.info?.id || '',
    locator: '',
    locatorId: '',
    locatorX: '0',
    locatorY: '0',
    locatorZ: '0',
    product: '',
    productId: '',
    productValue: '',
    productSKU: '',
    productASIN: '',
    productUPC: '',
    galleries: [],
    labelPrinter: '',
    labelPrinterId: '',
    isActive: true,
    line: '',
    isAutoProduce: false,
    qtyEntered: 1,
    movementQty: 1,
    processed: false,
    targetQty: 0,
    scrappedQty: 0,
    pickedQty: 0,
    confirmedQty: 0,
    isDescription: false,
    isInvoiced: false,
    description: '',
    orderLine: '',
    orderLineId: '',
    uom: '',
    uomId: '',
    attributeSetInstance: '',
    attributeSetInstanceId: '',
    project: '',
    projectId: '',
    campaign: '',
    campaignId: '',
    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 === 'locators' && Number(getOptions.value[key]?.records?.length || 0) >= 1) {
      form.value.locator = getOptions.value[key]?.records?.[0]?.Value ?? ''
      form.value.locatorId = getOptions.value[key]?.records?.[0]?.id ?? ''
      form.value.locatorX = getOptions.value[key]?.records?.[0]?.X ?? '0'
      form.value.locatorY = getOptions.value[key]?.records?.[0]?.Y ?? '0'
      form.value.locatorZ = getOptions.value[key]?.records?.[0]?.Z ?? '0'
    }
    
    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}&excludeBom=true`, 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}&excludeBom=true`, key)
        }
      }
    }
  } else {
    if(filter) {
      await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&name=fts.${filter}&org_id=${newOrganizationId}&excludeBom=true`, key)
      filtering.value[key] = filter
    } else {
      if(!filtering.value?.[key] || (filtering.value?.[key] ?? '') === '') {
        await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&org_id=${newOrganizationId}&excludeBom=true`, key)
      }
    }
  }
}

const checkLineChanged = ref({})
const retrieve = async () => {
  if(route.params?.id) {
    const res = await $fetch('/api/inouts/'+route.params.id+'/inout-line', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: item?.id || item?.uid || '',
          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?.Value || '',
          locatorId: item?.M_Locator_ID?.id || '',
          locatorX: item?.M_Locator_ID?.X || '0',
          locatorY: item?.M_Locator_ID?.Y || '0',
          locatorZ: item?.M_Locator_ID?.Z || '0',
          product: item?.M_Product_ID?.Name || '',
          productId: item?.M_Product_ID?.id || '',
          productValue: item?.M_Product_ID?.Value || '',
          productSKU: item?.M_Product_ID?.SKU || '',
          productASIN: item?.M_Product_ID?.asin || '',
          productUPC: item?.M_Product_ID?.UPC || '',
          productMPN: item?.M_Product_ID?.mpn || '',
          galleries: [],
          labelPrinter: item?.M_Product_ID?.labelprinter?.identifier || 'labelprinter-2',
          labelPrinterId: item?.M_Product_ID?.labelprinter?.id || 'b',
          isActive: item?.IsActive ?? true,
          line: item?.Line || '',
          isAutoProduce: item?.IsAutoProduce ?? false,
          qtyEntered: item?.QtyEntered || 1,
          movementQty: item?.MovementQty || 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 || '',
          orderLine: item?.C_OrderLine_ID?.identifier || '',
          orderLineId: item?.C_OrderLine_ID?.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 || '',
          alert: {
            status: '',
            message: '',
            processing: false,
          }
        }
      }).sort((a, b) => Number(a.line) - Number(b.line))

      const newEntries = []
      for(let item of entries.value) {
        checkLineChanged.value[item.id] = item.qtyEntered
        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) {
    const res = await $fetch('/api/inouts/'+entry.id+'/inout-line', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      retrieve()
    }
  }
}

const chooseLineIndex = ref(NaN)
const chooseLineEntry = ref(null)
const showProductChooser = ref(false)
const hideProductCharge = ref(false)
const showScanProduct = ref(false)

const productChooserHandler = async (prod) => {
  const res = await $fetch(`/api/materials/storages/higher-on-hand?m_product_id=${prod?.id ?? ''}&warehouse_id=${form.value.warehouseId}&exclude_return_locators=1`)

  if(chooseLineIndex.value !== NaN && chooseLineEntry.value !== null) {
    const newEntry = chooseLineEntry.value
    newEntry.product = prod?.Name || ''
    newEntry.productId = prod?.id || ''
    newEntry.productValue = prod?.Value || ''
    newEntry.productSKU = prod?.SKU || ''
    newEntry.productUPC = prod?.UPC || ''
    newEntry.labelPrinter = prod?.labelprinter?.identifier || 'labelprinter-2'
    newEntry.labelPrinterId = prod?.labelprinter?.id || 'b'
    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 ?? []

    if(res?.record) {
      newEntry.locator = res.record?.M_Locator_ID?.Value || ''
      newEntry.locatorId = res.record?.M_Locator_ID?.id || ''
      newEntry.locatorX = res.record?.M_Locator_ID?.X || '0'
      newEntry.locatorY = res.record?.M_Locator_ID?.Y || '0'
      newEntry.locatorZ = res.record?.M_Locator_ID?.Z || '0'
    }

    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.productValue = prod?.Value || ''
  newEntry.productSKU = prod?.SKU || ''
  newEntry.productUPC = prod?.UPC || ''
  newEntry.productASIN = prod?.ASIN || ''
  newEntry.labelPrinter = prod?.labelprinter?.identifier || 'labelprinter-2'
  newEntry.labelPrinterId = prod?.labelprinter?.id || 'b'
  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 locatorHandler = (newEntry, loc) => {
  newEntry.locatorX = loc?.X || '0'
  newEntry.locatorY = loc?.Y || '0'
  newEntry.locatorZ = loc?.Z || '0'
}

const takeOrderLine = async (newEntry, opt) => {
  newEntry.locator = opt?.M_Locator_ID?.identifier || newEntry.locator || ''
  newEntry.locatorId = opt?.M_Locator_ID?.id || newEntry.locatorId || ''
  newEntry.product = opt?.M_Product_ID?.Name || ''
  newEntry.productId = opt?.M_Product_ID?.id || ''
  newEntry.productValue = opt?.M_Product_ID?.Value || ''
  newEntry.productSKU = opt?.M_Product_ID?.SKU || ''
  newEntry.productUPC = opt?.M_Product_ID?.UPC || ''
  newEntry.productASIN = opt?.M_Product_ID?.asin || ''
  newEntry.galleries = []
  newEntry.labelPrinter = opt?.M_Product_ID?.labelprinter?.identifier || 'labelprinter-2'
  newEntry.labelPrinterId = opt?.M_Product_ID?.labelprinter?.id || 'b'
  newEntry.isAutoProduce = opt?.IsAutoProduce ?? false
  newEntry.qtyEntered = opt?.QtyEntered || 1
  newEntry.movementQty = opt?.MovementQty || 1
  newEntry.processed = opt?.Processed ?? false
  newEntry.targetQty = opt?.TargetQty || 0
  newEntry.scrappedQty = opt?.ScrappedQty || 0
  newEntry.pickedQty = opt?.PickedQty || 0
  newEntry.confirmedQty = opt?.ConfirmedQty || 0
  newEntry.isDescription = opt?.IsDescription ?? false
  newEntry.isInvoiced = opt?.IsInvoiced ?? false
  newEntry.description = opt?.Description || ''
  newEntry.orderLine = opt.name
  newEntry.orderLineId = opt?.id || ''
  newEntry.uom = opt?.C_UOM_ID?.identifier || ''
  newEntry.uomId = opt?.C_UOM_ID?.id || ''
  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 scanProduct = () => {
  showScanProduct.value = true
}

const productScanHandler = (prod) => {
  const newIndex = entries.value.findIndex(i => i.productId == prod.id)
  if(newIndex >= 0) {
    const newEntry = entries.value[newIndex]
    newEntry.qtyEntered = Number(newEntry.qtyEntered) + 1
    newEntry.movementQty = Number(newEntry.movementQty) + 1

    entries.value.splice(newIndex, 1, newEntry)
  } else {
    addLine()
    chooseLineIndex.value = Number(entries.value.length) - 1
    chooseLineEntry.value = entries.value[chooseLineIndex.value]
    productChooserHandler(prod)
  }
}

const serverSidePrinting = async (content) => {
  const labelPrinters = {
    a: 'labelprinter-2',
    b: 'labelprinter-2',
    c: 'labelprinter-3',
    d: 'labelprinter-4',
    e: 'labelprinter-5',
    f: 'labelprinter-6',
  }
  let labelPrinter = 'labelprinter-2'
  if(labelPrinters[content.labelPrinterId]) {
    labelPrinter = labelPrinters[content.labelPrinterId]
  }
  const res = await $fetch(`/api/print/${labelPrinter}/product2`, {
    method: 'POST',
    body: content
  })
  if(res) {
    if(res?.stdout) {
      toast({
        message: `The labels has been printed via server side printing!`,
        type: 'is-success',
        duration: 2000
      })
    }
  }
}

const generateLabel = (code = '', format = 'CODE128') => {
  const canvasElem = createCanvas()
  JsBarcode(canvasElem, code, {
    format: format,
    lineColor: "#000",
    displayValue: false
  })
  return canvasElem.toDataURL()
}

const labelByPrinter = (doc, no, entry) => {
  if(entry.labelPrinterId === 'b') {
    doc.addPage()
    doc.setPage(no)
    doc.setFontSize(18)
    doc.text(String(entry.product.replace("FOREVER ", "")), 2, 8, { maxWidth: 70 })
    doc.setFontSize(14)
    doc.text(String( 'SKU:'+ entry.productSKU + '|VAL:' + entry.productValue+ '|ORG:'+ entry.organizationId?.toString().slice(-2)), 0, 17)
    // doc.setFontSize(12)
    // doc.text(`${entry.locatorX ?? 0},${entry.locatorY ?? 0},${entry.locatorZ ?? 0}`, 4, 46)
    doc.addImage(generateLabel(String(entry.productValue ?? '0000')), 'image/png', 9, 20, 60, 28)
  } else if(entry.labelPrinterId === 'c') {
    doc.addPage()
    doc.setPage(no)
    // doc.setFontSize(14)
    // doc.text(String(entry.product.replace("FOREVER ", "")), 30, 3)
    // doc.text(String(entry.product), 4, 8)
    // // doc.setFontSize(12)
    // // doc.text(String(entry.organizationId), 4, 40)
    doc.setFontSize(12)
    doc.text(String( 'SKU:'+ entry?.productSKU + '|VAL:' + entry?.productValue+ '|ORG:'+ entry?.organization?.toString().slice(-2)), 0, 10)
    // doc.text(`${entry.locatorX ?? 0},${entry.locatorY ?? 0},${entry.locatorZ ?? 0}`, 4, 46)
    doc.addImage(generateLabel(String(entry?.productValue ?? '0000')), 'image/png', 50, 50, 30, 26)
  } else if(entry.labelPrinterId === 'd') {
    doc.addPage()
    doc.setPage(no)
    doc.setFontSize(14)
    doc.text(String(entry.product), 4, 8)
    doc.setFontSize(12)
    doc.text(String(entry.organizationId), 4, 40)
    doc.setFontSize(12)
    // doc.text(`${entry.locatorX ?? 0},${entry.locatorY ?? 0},${entry.locatorZ ?? 0}`, 4, 46)
    doc.addImage(generateLabel(String(entry.productValue ?? '0000')), 'image/png', 30, 25, 40, 26)
  } else if(entry.labelPrinterId === 'e') {
    doc.addPage()
    doc.setPage(no)
    doc.setFontSize(14)
    doc.text(String(entry.product), 4, 8)
    doc.setFontSize(12)
    doc.text(String(entry.organizationId), 4, 40)
    doc.setFontSize(12)
    // doc.text(`${entry.locatorX ?? 0},${entry.locatorY ?? 0},${entry.locatorZ ?? 0}`, 4, 46)
    doc.addImage(generateLabel(String(entry.productValue ?? '0000')), 'image/png', 30, 25, 40, 26)
  } else if(entry.labelPrinterId === 'f') {
    doc.addPage()
    doc.setPage(no)
    doc.setFontSize(14)
    doc.text(String(entry.product), 4, 8)
    doc.setFontSize(12)
    doc.text(String(entry.organizationId), 4, 40)
    doc.setFontSize(12)
    // doc.text(`${entry.locatorX ?? 0},${entry.locatorY ?? 0},${entry.locatorZ ?? 0}`, 4, 46)
    doc.addImage(generateLabel(String(entry.productValue ?? '0000')), 'image/png', 30, 25, 40, 26)
  } else {
    doc.addPage()
    doc.setPage(no)
    doc.setFontSize(18)
    doc.text(String(entry.product.replace("FOREVER ", "")), 0, 8)
    doc.setFontSize(14)
    doc.text(String( 'SKU: '+ entry.productSKU + ' | VAL: ' + entry.productValue+ ' | ORG: '+ entry.organizationId?.toString().slice(-2)), 0, 17)
    // doc.setFontSize(12)
    // doc.text(`${entry.locatorX ?? 0},${entry.locatorY ?? 0},${entry.locatorZ ?? 0}`, 4, 46)
    doc.addImage(generateLabel(String(entry.productValue ?? '0000')), 'image/png', 9, 20, 60, 28)
  }
}

const printLabels = async (type = 'server') => {
  const groupedByLabelPrinterId = entries.value.reduce((acc, prod) => {
    const { labelPrinterId } = prod
    if (!acc[labelPrinterId]) {
      acc[labelPrinterId] = []
    }
    acc[labelPrinterId].push({
      qtyEntered: prod.qtyEntered,
      labelPrinter: prod.labelPrinter,
      labelPrinterId: prod.labelPrinterId,
      product: prod.product,
      productId: prod.productId,
      productSKU: prod.productSKU,
      productASIN: prod.productASIN,
      productUPC: prod.productUPC,
      productValue: prod.productValue,
      organization: prod.organization,
      organizationId: prod.organizationId,
      locatorX: prod.locatorX,
      locatorY: prod.locatorY,
      locatorZ: prod.locatorZ,
      labelBarcode: generateLabel(String(prod.productValue ?? '0000'), prod.labelPrinterId === 'b' ? 'CODE128' : 'CODE128')
    })
    return acc
  }, {})

  if(type === 'server' || type === 'server-download' || type === 'download') {
    // 'download' = server renders the PDF (with proper per-printer page
    // formats) and returns it; the physical printer is NOT invoked.
    const downloadOnly = type === 'download'
    const res = await $fetch(`/api/print/product`, {
      method: 'POST',
      body: {
        pathName: `inout-labels/${new Date().getFullYear()}`,
        fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-LABELS-')}.pdf`,
        labelEntries: Object.entries(groupedByLabelPrinterId),
        downloadOnly
      }
    })
    if(res) {
      console.log(res)
      if(Number(res?.contents?.length ?? 0) >= 1) {
        toast({
          message: downloadOnly
            ? `${res?.contents?.length ?? 0} label PDF(s) downloaded.`
            : `${res?.contents?.length ?? 0} of the labels have been printed via server side printing!`,
          type: 'is-success',
          duration: 2000
        })
        if(type === 'server-download' || downloadOnly) {
          for(const base64Content of res.contents) {
            const base64Response = await fetch(`data:application/pdf;base64,${base64Content.content}`)
            const blob = await base64Response.blob()
            const blobUrl = URL.createObjectURL(blob)
            open(blobUrl, '_blank')
          }
        }
      } else {
        toast({
          message: downloadOnly
            ? `Failed to generate the label PDFs.`
            : `The labels are not been printed via server side printing!`,
          type: 'is-danger',
          duration: 2000
        })
      }
    }
    return;
  }

  for(const values of Object.values(groupedByLabelPrinterId)) {
    const doc = new jsPDF({
      orientation: 'l',
      unit: 'mm',
      format: 'a8',
      putOnlyUsedFonts: true,
      compress: true
    })
    doc.html(DOMPurify.sanitize('<div></div>'), {
      callback: (doc) => {
        doc.addPage()

        let no = 2;
        for(let entry of values.flat()) {
          for(let i = 0; i < Number(entry.qtyEntered || 0); i++) {
            labelByPrinter(doc, no, entry)

            no++
          }
        }

        doc.deletePage(1)
        doc.deletePage(Number(no) - 1)
        if(entries.value.length >= 1) {
          if(type === 'server') {
            serverSidePrinting({
              pathName: `inout-labels/${new Date().getFullYear()}`,
              fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-LABELS-')}.pdf`,
              fileContent: doc.output('dataurlstring')?.replace('data:application/pdf;filename=generated.pdf;base64,', ''),
              labelPrinterId: values.flat()?.[0]?.labelPrinterId ?? 'a',
            })
          } else {
            doc.save(`${date.now().replace(/\-|\:/g, '_').replace(' ', '-LABELS-')}.pdf`)
          }
        } else {
          toast({
            message: 'Please add at least one line first before pressing print labels button!',
            type: 'is-warning',
            duration: 2000
          })
        }
      },
      width: 263,
      windowWidth: 263,
      //margin: 4,
      x: 0,
      y: 0,
      autoPaging: 'text',
    })
  }
}

const saveAll = async () => {
  entries.value.forEach(async (item) => {
    await save(item, false)
  })
  setTimeout(() => {
    retrieve()
  }, 1000)
}

const save = async (entry = null, saveOnlyOne = true) => {
  const newEntry = entry ?? unref(form.value)
  //console.log(newEntry)

  if(newEntry.id !== '') {
    const res = await $fetch('/api/inouts/'+route.params.id+'/inout-line', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: newEntry.id,
        isActive: newEntry.isActive,
        line: newEntry.line,
        isAutoProduce: newEntry.isAutoProduce,
        qtyEntered: newEntry.qtyEntered,
        processed: newEntry.processed,
        targetQty: newEntry.targetQty,
        scrappedQty: newEntry.scrappedQty,
        pickedQty: newEntry.pickedQty,
        confirmedQty: newEntry.confirmedQty,
        isDescription: newEntry.isDescription,
        isInvoiced: newEntry.isInvoiced,
        description: newEntry.description,
        movementQty: newEntry.movementQty,
        orderLineId: newEntry.orderLineId,
        uomId: newEntry.uomId,
        attributeSetInstanceId: newEntry.attributeSetInstanceId,
        projectId: newEntry.projectId,
        campaignId: newEntry.campaignId,
        productId: newEntry.productId,
        locatorId: newEntry.locatorId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record saved!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  } else {
    const res = await $fetch('/api/inouts/'+route.params.id+'/inout-line', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: newEntry.organizationId || organizationId.value,
        isActive: newEntry.isActive,
        line: newEntry.line,
        isAutoProduce: newEntry.isAutoProduce,
        qtyEntered: newEntry.qtyEntered,
        processed: newEntry.processed,
        targetQty: newEntry.targetQty,
        scrappedQty: newEntry.scrappedQty,
        pickedQty: newEntry.pickedQty,
        confirmedQty: newEntry.confirmedQty,
        isDescription: newEntry.isDescription,
        isInvoiced: newEntry.isInvoiced,
        description: newEntry.description,
        movementQty: newEntry.movementQty,
        orderLineId: newEntry.orderLineId,
        uomId: newEntry.uomId,
        attributeSetInstanceId: newEntry.attributeSetInstanceId,
        projectId: newEntry.projectId,
        campaignId: newEntry.campaignId,
        productId: newEntry.productId,
        inOutId: route.params.id,
        locatorId: newEntry.locatorId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record created!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  }
}

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="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr v-if="action !== 'view'">
            <td colspan="12" style="text-align: right;">
              <div class="d-flex justifyContent-flexEnd gap-10px">
                <button v-if="info.docStatusId !== 'CO'" type="button" @click="addLine" class="button">Add Line</button>
                <button v-if="info.docStatusId !== 'CO'" type="button" @click="scanProduct" class="button">Scan Product</button>
                <button type="button" @click="printLabels('server')" class="button">Print Labels (Server Only)</button>
                <button type="button" @click="printLabels('download')" class="button">Download Labels</button>
                <button v-if="info.docStatusId !== 'CO'" type="button" @click="showDetailRecordModal = true; form.line = lineNumber;" class="button">Advanced ADD</button>
                <button v-if="info.docStatusId !== 'CO'" type="button" @click="saveAll" class="button" :class="{redButton: entries.filter(i => i.id === '' || checkLineChanged[i.id] !== i.qtyEntered).length >= 1}">Save ALL</button>
              </div>
            </td>
          </tr>
          <tr>
            <th>Line</th>
            <th colspan="2">Product *</th>
            <th>SKU</th>
            <th>Value</th>
            <th>UPC</th>
            <th>MPN</th>
            <th>Unit *</th>
            <th class="w-120px">Qty *</th>
            <th class="w-120px">Locator *</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' ? 12 : 11" 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="vertical-align: middle; 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.id !== ''">{{ 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>{{ entry.productSKU }}</td>
              <td>{{ entry.productValue }}</td>
              <td>{{ entry.productUPC }}</td>
              <td>{{ entry.productMPN }}</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.movementQty = entry.qtyEntered;" class="input" />
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.locator }}</span>
                <ClientOnly v-else>
                  <SelectBox v-model="entry.locatorId" :options="getOptions?.['locators_'+index]?.records || [{id: entry.locatorId, Value: entry.locator}]" prop="Value" dataprop="id" datatype="string" :size="5" @click="filterOptions('m_locator', 'locators_'+index, string.urlEncode(`isActive eq true AND M_Warehouse_ID eq ${info.warehouseId}`))" @search="(val) => filterOptions('m_locator', 'locators_'+index, string.urlEncode(`isActive eq true AND M_Warehouse_ID eq ${info.warehouseId} AND contains(Name,'${val}')`))" @change="(val, opt) => locatorHandler(entry, opt)" :loading="loading?.['locators_'+index] ?? true" :up="true" placeholder="----" />
                </ClientOnly>
              </td>
              <td>
                <div class="check">
                  <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+index" :checked="entry.isActive" :disabled="action === 'view' || info.docStatusId === 'CO'">
                  <label class="checkLabel" :for="'isActive_'+index">Active</label>
                </div>
              </td>
              <td v-if="action !== 'view'">
                <div class="d-flex justify-flexEnd gap-5px">
                  <span v-if="info.docStatusId !== 'CO'" @click="save(entry)" class="cursor-pointer fg-success">
                    <i class="menu-icon tf-icons ti ti-device-floppy" :class="{redIcon: entry.id === '' || checkLineChanged[entry.id] !== entry.qtyEntered}"></i>
                  </span>
                  <span @click="entry.show = !entry.show" class="cursor-pointer fg-success">
                    <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 @click="form = entry; showDetailRecordModal = true;" class="cursor-pointer fg-warning">
                    <i v-if="info.docStatusId === 'CO'" class="menu-icon tf-icons ti ti-eye"></i>
                    <i v-else class="menu-icon tf-icons ti ti-pencil"></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' ? 12 : 11">
                <div class="my-5 mx-5">
                  <AlertAction v-model='entry.alert.status' :alert="entry.alert" />
                  <div class="columns">
                    <div class="column is-two-thirds">
                      <label class="label d-block">Line</label>
                      <input type="text" v-model="entry.line" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                      <div class="columns">
                        <div class="column is-half">
                          <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">
                          <div :class="(form.id !== '' || action === 'view' || entry.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                            <label class="label d-block mt-2">Locator *</label>
                            <ClientOnly>
                              <SelectBox v-model="entry.locatorId" :options="getOptions?.['locators']?.records || [{id: entry.locatorId, Value: entry.locator}]" prop="Value" dataprop="id" datatype="string" :size="5" @click="setOptions('materials/locators/'+info.warehouseId, 'locators')" @change="(val, opt) => locatorHandler(entry, opt)" :loading="loading?.['locators'] ?? true" />
                            </ClientOnly>
                          </div>
                          
                          <label class="label d-block mt-2">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>
                      </div>
                      
                      <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.movementQty = entry.qtyEntered;" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                          <label class="label d-block mt-2">Movement Quantity</label>
                          <input type="text" :value="entry.movementQty" class="input" readonly />

                          <label class="label d-block mt-2">Picked Quantity</label>
                          <input type="text" :value="entry.pickedQty" class="input" readonly />

                          <label class="label d-block mt-2">Confirmed Quantity</label>
                          <input type="text" :value="entry.confirmedQty" 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">Target Quantity</label>
                          <input type="text" :value="entry.targetQty" class="input" readonly />
                          
                          <label class="label d-block mt-2">Scrapped Quantity</label>
                          <input type="text" :value="entry.scrappedQty" class="input" readonly />
                        </div>
                      </div>

                      <div class="columns">
                        <div class="column is-half">
                          <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">
                          <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">Description</label>
                      <textarea v-model="entry.description" class="input" :disabled="action === 'view' || info.docStatusId === 'CO'"></textarea>
                    </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="info.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' && info.docStatusId !== 'CO'">
            <td colspan="12" style="text-align: right;">
              <div class="d-flex justifyContent-flexEnd gap-10px">
                <button type="button" @click="addLine" class="button">Add Line</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <Teleport to="body">
    <div class="modal" :class="{'active': showDetailRecordModal}" :style="{display: showDetailRecordModal ? 'block' : 'none'}">
      <div class="modalDialog modalCenter modalPrintPreview" @click.self="closeDetailRecordModal">
        <div class="modalContent">
          <div class="modalHeader">
            <h3 class="modalTitle">Receipt Line</h3>
            <div class="cursor-pointer" @click="closeDetailRecordModal">
              <span class="tf-icon ti ti-x ti-sm me-1"></span>
            </div>
          </div>
          <div class="modalBody">
            <div class="my-5 mx-5">
              <AlertAction v-model='form.alert.status' :alert="form.alert" />
              <div class="columns">
                <div class="column is-two-thirds">
                  <label class="label d-block">Line</label>
                  <input type="text" v-model="form.line" class="input" :readonly="form.id !== '' || action === 'view' || info.docStatusId === 'CO'" />

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Product</label>
                      <!--<ClientOnly>
                        <SelectBox v-model="form.productId" :options="getOptions?.['products']?.records || [{id: form.productId, Name: form.product}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_product', 'products')" @change="productHandler" :loading="loading?.['products'] ?? true" class="groupItem" />
                      </ClientOnly>-->
                      <div class="d-flex gap-10px">
                        <input type="text" v-model="form.product" class="input flexGrow-1" readonly />
                        <button v-if="action !== 'view' && info.docStatusId !== 'CO'" type="button" class="button" @click="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">
                      <div :class="(form.id !== '' || action === 'view' || info.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                        <label class="label d-block mt-2">Locator *</label>
                        <ClientOnly>
                          <SelectBox v-model="form.locatorId" :options="getOptions?.['locators']?.records || [{id: form.locatorId, Value: form.locator}]" prop="Value" dataprop="id" datatype="string" :size="5" @click="setOptions('materials/locators/'+info.warehouseId, 'locators')" :loading="loading?.['locators'] ?? true" />
                        </ClientOnly>
                      </div>
                      
                      <label class="label d-block mt-2">Purchase Order Line</label>
                      <ClientOnly v-if="info.orderId">
                        <SelectBox v-model="form.orderLineId" :options="getOptions?.['order_lines_'+index]?.records || [{id: form.orderLineId, name: form.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(form, opt)" :loading="loading?.['order_lines_'+index] ?? true" />
                      </ClientOnly>
                      <input v-else type="text" :value="form.orderLine" class="input" readonly />
                    </div>
                  </div>

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

                      <label class="label d-block mt-2">Movement Quantity</label>
                      <input type="text" :value="form.movementQty" class="input" readonly />

                      <label class="label d-block mt-2">Picked Quantity</label>
                      <input type="text" :value="form.pickedQty" class="input" readonly />

                      <label class="label d-block mt-2">Confirmed Quantity</label>
                      <input type="text" :value="form.confirmedQty" class="input" readonly />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">UOM *</label>
                      <input v-if="info.docStatusId === 'CO'" type="text" :value="form.uom" class="input" readonly />
                      <ClientOnly v-else>
                        <SelectBox v-model="form.uomId" :options="getOptions?.['units']?.records || [{id: form.uomId, Name: form.uom}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_uom', 'units')" :loading="loading?.['units'] ?? true" placeholder="----" />
                      </ClientOnly>
                      
                      <label class="label d-block mt-2">Target Quantity</label>
                      <input type="text" :value="form.targetQty" class="input" readonly />
                      
                      <label class="label d-block mt-2">Scrapped Quantity</label>
                      <input type="text" :value="form.scrappedQty" class="input" readonly />
                    </div>
                  </div>

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Project</label>
                      <input v-if="info.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('models/c_project', 'projects')" :loading="loading?.['projects'] ?? true" placeholder="----" :up="true" />
                      </ClientOnly>
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Campaign</label>
                      <input v-if="info.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('models/c_campaign', 'campaigns')" :loading="loading?.['campaigns'] ?? true" placeholder="----" :up="true" />
                      </ClientOnly>
                    </div>
                  </div>

                  <label class="label d-block mt-2">Description</label>
                  <textarea v-model="form.description" class="input" :disabled="action === 'view' || info.docStatusId === 'CO'"></textarea>

                </div>
                <div class="column is-one-third">
                  <label class="label d-block">Tenant</label>
                  <input type="text" :value="form.client" class="input" readonly />

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

                  <label class="label d-block">Warehouse</label>
                  <input type="text" :value="info.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="form.isActive" class="checkInput" id="isActive" :checked="form.isActive" :disabled="action === 'view' || info.docStatusId === 'CO'">
                      <label class="checkLabel" for="isActive">Active</label>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="modalFooter">
            <div></div>
            <div class="d-flex gap-10px">
              <button type="button" class="button" @click="closeDetailRecordModal">Close</button>
              <button v-if="action !== 'view' && info.docStatusId !== 'CO'" type="button" class="button" @click="save(null)" :class="(form.name === '' || form.locatorId === '' || form.productId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <ProductChooser v-model="showProductChooser" :info="info" @handler="productChooserHandler" />
    <POScanProduct v-model="showScanProduct" :info="info" :lines="entries" @handler="productScanHandler" />
    <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>