<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({
  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 || '',
  rma: props.info?.documentNo || '',
  rmaId: props.info?.id || '',
  isActive: true,
  line: lineNumber.value,
  product: '',
  productId: '',
  gallery: {},
  galleries: [],
  qty: 1,
  amt: 0,
  lineNetAmt: 0,
  processed: false,
  tax: '',
  taxId: '',
  inOutLine: '',
  inOutLineId: '',
  charge: '',
  chargeId: '',
  show: false,
  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.rma = props.info?.documentNo || ''
  form.value.rmaId = props.info?.id || ''
})

const addLine = () => {
  entries.value.push({
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    rma: props.info?.documentNo || '',
    rmaId: props.info?.id || '',
    isActive: true,
    line: lineNumber.value,
    product: '',
    productId: '',
    gallery: {},
    galleries: [],
    qty: 1,
    amt: 0,
    lineNetAmt: 0,
    processed: false,
    tax: '',
    taxId: '',
    inOutLine: '',
    inOutLineId: '',
    charge: '',
    chargeId: '',
    show: false,
    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 || '',
    rma: props.info?.documentNo || '',
    rmaId: props.info?.id || '',
    isActive: true,
    line: lineNumber.value,
    product: '',
    productId: '',
    gallery: {},
    galleries: [],
    qty: 1,
    amt: 0,
    lineNetAmt: 0,
    processed: false,
    tax: '',
    taxId: '',
    inOutLine: '',
    inOutLineId: '',
    charge: '',
    chargeId: '',
    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_') && Number(res?.records?.length) >= 1) {
      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('inoutlines') && Number(res?.records?.length) >= 1) {
      getOptions.value[key].records = res.records.map(item => {
        item.name = `${item.Line}_${item.M_Product_ID.identifier}_${item.QtyEntered}`
        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 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}`, 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}`, key)
        }
      }
    }
  } else {
    if(filter) {
      await setOptions(`${url}?name=fts.${filter}`, key)
      filtering.value[key] = filter
    } else {
      if(!filtering.value?.[key] || filtering.value?.[key] === '') {
        await setOptions(`${url}`, key)
      }
    }
  }
}

const retrieve = async () => {
  if(route.params?.id) {
    const res = await $fetch('/api/rma/'+route.params.id+'/rma-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 || '',
          rma: item?.M_RMA_ID?.identifier || '',
          rmaId: item?.M_RMA_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: [],
          qty: item?.Qty || 1,
          amt: item?.Amt || 0,
          lineNetAmt: item?.LineNetAmt || 0,
          processed: item?.Processed ?? false,
          tax: item?.C_Tax_ID?.identifier || '',
          taxId: item?.C_Tax_ID?.id || '',
          inOutLine: item?.M_InOutLine_ID?.identifier || '',
          inOutLineId: item?.M_InOutLine_ID?.id || '',
          charge: item?.C_Charge_ID?.identifier || '',
          chargeId: item?.C_Charge_ID?.id || '',
          alert: {
            status: '',
            message: '',
            processing: false,
          }
        }
      })
      
      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/rma/'+entry.id+'/rma-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.amt = prod?.M_ProductPrice?.PriceList || prod?.M_ProductPrice?.PriceStd || 0
    newEntry.charge = ''
    newEntry.chargeId = ''
    newEntry.lineNetAmt = Number(newEntry.qty) * Number(newEntry.amtd);
    newEntry.gallery = prod?.gallery ?? {}
  newEntry.galleries = prod?.galleries ?? []

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

    chooseLineIndex.value = NaN
    chooseLineEntry.value = null
  } else {
    form.value.product = prod?.Name || ''
    form.value.productId = prod?.id || ''
    form.value.amt = prod?.M_ProductPrice?.PriceList || prod?.M_ProductPrice?.PriceStd || 0
    form.value.charge = ''
    form.value.chargeId = ''
    form.value.gallery = prod?.gallery ?? {}
    form.value.galleries = prod?.galleries ?? []
  }
  hideProductCharge.value = true
}

const productHandler = (newEntry, prod) => {
  newEntry.product = prod?.Name || ''
  newEntry.productId = prod?.id || ''
  newEntry.amt = prod?.M_ProductPrice?.PriceList || prod?.M_ProductPrice?.PriceStd || 0
  newEntry.charge = ''
  newEntry.chargeId = ''
  newEntry.lineNetAmt = Number(newEntry.qty) * Number(newEntry.amt);
  newEntry.gallery = prod?.gallery ?? {}
  newEntry.galleries = prod?.galleries ?? []
  hideProductCharge.value = true
}

const entryInOutLine = async (entry, opt) => {
  entry.product = opt?.M_Product_ID?.identifier || ''
  entry.productId = opt?.M_Product_ID?.id || ''
  entry.charge = ''
  entry.chargeId = ''
  entry.galleries = []
  if(entry.productId) {
    const response = await $fetch(`/api/materials/products/${entry.productId}`)
    if(response?.Strapi_Product_documentId) {
      const resp = await $fetch(`/api/materials/products/${response.Strapi_Product_documentId}/galleries/images`)
      if(resp) {
        entry.galleries = resp
      }
    }
  }
  hideProductCharge.value = true
}

const handleInOutLine = async (val, opt) => {
  form.value.product = opt?.M_Product_ID?.identifier || ''
  form.value.productId = opt?.M_Product_ID?.id || ''
  form.value.charge = ''
  form.value.chargeId = ''
  form.value.galleries = []
  if(form.value.productId) {
    const response = await $fetch(`/api/materials/products/${form.value.productId}`)
    if(response?.Strapi_Product_documentId) {
      const resp = await $fetch(`/api/materials/products/${response.Strapi_Product_documentId}/galleries/images`)
      if(resp) {
        form.value.galleries = resp
      }
    }
  }
  hideProductCharge.value = true
}

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)

  if(newEntry.id !== '') {
    const res = await $fetch('/api/rma/'+route.params.id+'/rma-line', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: newEntry.id,
        isActive: newEntry.isActive,
        line: newEntry.line,
        productId: newEntry.productId,
        qty: newEntry.qty,
        amt: newEntry.amt,
        lineNetAmt: newEntry.lineNetAmt,
        processed: newEntry.processed,
        taxId: newEntry.taxId,
        inOutLineId: newEntry.inOutLineId,
        chargeId: newEntry.chargeId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      if(saveOnlyOne) {
        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/rma/'+route.params.id+'/rma-line', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: newEntry.organizationId || organizationId.value,
        rmaId: route.params.id,
        isActive: newEntry.isActive,
        line: newEntry.line,
        productId: newEntry.productId,
        qty: newEntry.qty,
        amt: newEntry.amt,
        lineNetAmt: newEntry.lineNetAmt,
        processed: newEntry.processed,
        taxId: newEntry.taxId,
        inOutLineId: newEntry.inOutLineId,
        chargeId: newEntry.chargeId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      if(saveOnlyOne) {
        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
      })
    }
  }
}
</script>

<template>
  <div class="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th>Line</th>
            <th colspan="2">Product</th>
            <th>Tax</th>
            <th class="w-120px">Qty</th>
            <th class="w-120px">Amt</th>
            <th class="w-120px">Line Amt</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 !== 'DR'">{{ entry.line }}</span>
                <input v-else type="text" v-model="entry.line" class="input" />
              </td>
              <td>
                <div>
                  <div v-if="(entry?.galleries?.length || 0) >= 1" class="productChooserBox" style="width: 40px; height: 40px;">
                    <img v-if="entry?.galleries[0]?.formats?.small" :src="config.public.strapi+'/files-api/'+entry?.galleries[0]?.formats?.small?.hash + entry?.galleries[0]?.formats?.small?.ext" :alt="entry?.galleries[0]?.name" />
                    <img v-else :src="config.public.strapi+'/files-api/'+entry?.galleries[0]?.formats?.thumbnail?.hash + entry?.galleries[0]?.formats?.thumbnail?.ext" :alt="entry?.galleries[0]?.name" />
                  </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;">
                <span v-if="action === 'view' || info.docStatusId !== 'DR' || entry.id !== ''">{{ entry.product }}</span>
                <span v-else-if="entry.inOutLineId !== ''">{{ entry.product }}</span>
                <ClientOnly v-else>
                  <ComboBox 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', 'products_'+index)" @search="(val) => filterProducts('materials/products/filter', 'products_'+index, string.urlEncode(val))" @change="(val, opt) => productHandler(entry, opt)" :loading="loading?.['products_'+index] ?? true" class="groupItem" :up="true" type="slot" :select="true">
                    <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?.galleries?.length || 0) >= 1" class="productChooserBox" style="width: 32px; height: 32px;">
                            <img v-if="option?.galleries[0]?.formats?.small" :src="config.public.strapi+'/files-api/'+option?.galleries[0]?.formats?.small?.hash + option?.galleries[0]?.formats?.small?.ext" :alt="option?.galleries[0]?.name" />
                            <img v-else :src="config.public.strapi+'/files-api/'+option?.galleries[0]?.formats?.thumbnail?.hash + option?.galleries[0]?.formats?.thumbnail?.ext" :alt="option?.galleries[0]?.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>
                </ClientOnly>
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId !== 'DR'">{{ entry.tax }}</span>
                <ClientOnly v-else>
                  <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" :up="true" placeholder="----" />
                </ClientOnly>
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId !== 'DR'">{{ entry.qty }}</span>
                <input v-else type="text" v-model="entry.qty" @input="entry.lineNetAmt = Number(entry.qty) * Number(entry.amt);" class="input" />
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId !== 'DR'">{{ entry.amt }}</span>
                <input v-else type="text" v-model="entry.amt" @input="entry.lineNetAmt = Number(entry.qty) * Number(entry.amt);" class="input" />
              </td>
              <td>{{ entry.lineNetAmt }}</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 !== 'DR'">
                  <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 === 'DR'" @click="save(entry)" class="cursor-pointer fg-success">
                    <i class="menu-icon tf-icons ti ti-device-floppy" :class="{redIcon: entry.id === ''}"></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 !== 'DR'" 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 === 'DR'" @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">
                  <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 !== 'DR'" />

                          <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 />
                            <template v-if="entry.inOutLineId === ''">
                              <button v-if="action !== 'view' && info.docStatusId === 'DR' && entry.id === ''" type="button" class="button" @click="chooseLineIndex = index; chooseLineEntry = entry; showProductChooser = true;">Choose</button>
                            </template>
                          </div>

                          <label class="label d-block mt-2">Quantity *</label>
                          <input type="text" v-model="entry.qty" @input="entry.lineNetAmt = Number(entry.qty) * Number(entry.amt);" class="input" :readonly="action === 'view' || info.docStatusId !== 'DR'" />
                        </div>
                        <div class="column is-half">
                          <div :class="(action === 'view' || info.docStatusId !== 'DR') ? 'pointerEvents-none opacity-0.6' : ''">
                            <label class="label d-block">Shipment/Receipt Line</label>
                            <ClientOnly>
                              <SelectBox v-model="entry.inOutLineId" :options="getOptions?.['inoutlines_'+index]?.records || [{id: entry.inOutLineId, name: entry.inOutLine}]" prop="name" dataprop="id" datatype="string" :size="5" @click="filterOptions('m_inoutline', 'inoutlines_'+index, string.urlEncode(`M_InOut_ID eq ${info.inOutId} AND isActive eq true`))" @search="(val) => filterOptions('m_inoutline', 'inoutlines_'+index, string.urlEncode(`M_InOut_ID eq ${info.inOutId} AND isActive eq true AND contains(Line,'${val}')`))" @change="(val, opt) => entryInOutLine(entry, opt)" :loading="loading?.['inoutlines_'+index] ?? true" placeholder="----" />
                            </ClientOnly>
                          </div>

                          <div :class="(hideProductCharge || action === 'view' || info.docStatusId !== 'DR' || entry.id !== '') ? '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">Amount</label>
                          <input type="text" v-model="entry.amt" @input="entry.lineNetAmt = Number(entry.qty) * Number(entry.amt);" class="input" :readonly="action === 'view' || info.docStatusId !== 'DR'" />
                        </div>
                      </div>
                      
                      <div class="columns">
                        <div class="column is-half">
                          <div :class="(action === 'view' || info.docStatusId !== 'DR') ? '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>
                        <div class="column is-half">
                          <label class="label d-block mt-2">Line Amount</label>
                          <input type="text" :value="entry.lineNetAmt" 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 !== 'DR'"></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">Customer RMA</label>
                      <input type="text" :value="entry.rma" 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 !== 'DR'">
                          <label class="checkLabel" for="isActive">Active</label>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          </template>
          <tr v-if="action !== 'view' && info.docStatusId === 'DR'">
            <td colspan="5">
              <div class="d-flex gap-10px">
                <button type="button" @click="addLine" class="button">Add Record</button>
                <button type="button" @click="showDetailRecordModal = true; form.line = lineNumber;" class="button">Advanced ADD</button>
                <button type="button" @click="saveAll" class="button" :class="{redButton: entries.filter(i => i.id === '').length >= 1}">Save ALL</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">RMA 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">
                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block">Line</label>
                      <input type="text" v-model="form.line" class="input" :readonly="action === 'view' || info.docStatusId !== 'DR'" />
                    </div>
                    <div class="column is-half">
                      <div :class="(action === 'view' || info.docStatusId !== 'DR') ? 'pointerEvents-none opacity-0.6' : ''">
                        <label class="label d-block">Shipment/Receipt Line</label>
                        <ClientOnly>
                          <SelectBox v-model="form.inOutLineId" :options="getOptions?.['inoutlines']?.records || [{id: form.inOutLineId, name: form.inOutLine}]" prop="name" dataprop="id" datatype="string" :size="5" @click="filterOptions('m_inoutline', 'inoutlines', string.urlEncode(`M_InOut_ID eq ${info.inOutId} AND isActive eq true`))" @search="(val) => filterOptions('m_inoutline', 'inoutlines', string.urlEncode(`M_InOut_ID eq ${info.inOutId} AND isActive eq true AND contains(Line,'${val}')`))" :loading="loading?.['inoutlines'] ?? true" placeholder="----" @change="handleInOutLine" />
                        </ClientOnly>
                      </div>
                    </div>
                  </div>

                  <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="form.product" class="input flexGrow-1" readonly />
                        <template v-if="form.inOutLineId === ''">
                          <button v-if="action !== 'view' && info.docStatusId === 'DR' && form.id === ''" type="button" class="button" @click="showProductChooser = true">Choose</button>
                        </template>
                      </div>

                      <label class="label d-block mt-2">Quantity *</label>
                      <input type="text" v-model="form.qty" @input="form.lineNetAmt = Number(form.qty) * Number(form.amt);" class="input" :readonly="action === 'view' || info.docStatusId !== 'DR'" />
                    </div>
                    <div class="column is-half">
                      <div :class="(hideProductCharge || action === 'view' || info.docStatusId !== 'DR' || form.id !== '') ? 'pointerEvents-none opacity-0.6' : ''">
                        <label class="label d-block mt-2">Charge</label>
                        <ClientOnly>
                          <SelectBox v-model="form.chargeId" :options="getOptions?.['charges']?.records || [{id: form.chargeId, Name: form.charge}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_charge', 'charges')" :loading="loading?.['charges'] ?? true" />
                        </ClientOnly>
                      </div>
                      
                      <label class="label d-block mt-2">Amount</label>
                      <input type="text" v-model="form.amt" @input="form.lineNetAmt = Number(form.amt) * Number(form.amt);" class="input" :readonly="action === 'view' || info.docStatusId !== 'DR'" />
                    </div>
                  </div>

                  <div class="columns">
                    <div class="column is-half">
                      <div :class="(action === 'view' || info.docStatusId !== 'DR') ? 'pointerEvents-none opacity-0.6' : ''">
                        <label class="label d-block mt-2">Tax *</label>
                        <ClientOnly>
                          <SelectBox v-model="form.taxId" :options="getOptions?.['taxes']?.records || [{id: form.taxId, Name: form.tax}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_tax', 'taxes')" :loading="loading?.['taxes'] ?? true" placeholder="----" />
                        </ClientOnly>
                      </div>
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Line Amount</label>
                      <input type="text" v-model="form.lineNetAmt" class="input" readonly />
                    </div>
                  </div>

                  <label class="label d-block mt-2">Description</label>
                  <textarea v-model="form.description" class="input" :disabled="action === 'view' || info.docStatusId !== 'DR'"></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">Customer RMA</label>
                  <input type="text" :value="form.rma" 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 !== 'DR'">
                      <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 === 'DR'" type="button" class="button" @click="(null)" :class="(form.productId === '' || form.qty === '' || form.taxId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <ProductChooser v-model="showProductChooser" :info="info" @handler="productChooserHandler" />
  </Teleport>
</template>