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

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

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

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

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

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

const addLine = () => {
  entries.value.push({
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    warehouse: props.info?.warehouse || '',
    warehouseId: props.info?.warehouseId || '',
    warehouseTo: props.info?.warehouseTo || '',
    warehouseToId: props.info?.warehouseToId || '',
    movement: props.info?.documentNo || '',
    movementId: props.info?.id || '',
    product: '',
    productId: '',
    gallery: {},
    galleries: [],
    isActive: true,
    line: lineNumber.value,
    description: '',
    movementQty: 1,
    confirmedQty: 0,
    targetQty: 0,
    scrappedQty: 0,
    qtyOnHand: 0,
    locator: '',
    locatorId: '',
    locatorTo: '',
    locatorToId: '',
    attributeSetInstance: '',
    attributeSetInstanceId: '',
    attributeSetInstanceTo: '',
    attributeSetInstanceToId: '',
    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 === 'locators' && form.value.locatorId === '' && 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 || ''
    }
    if(key === 'to_locators' && form.value.locatorToId === '' && Number(getOptions.value[key]?.records?.length || 0) >= 1) {
      form.value.locatorTo = getOptions.value[key]?.records?.[0]?.Value || ''
      form.value.locatorToId = getOptions.value[key]?.records?.[0]?.id || ''
    }
  }
  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}&filter=${filter}&org_id=${newOrganizationId}`, key)
        filtering.value[key] = filter
      } else {
        if(!filtering.value?.[key] || filtering.value?.[key] === '') {
          await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&m_pricelist_version_id=eq.${newPriceListVersionId}&org_id=${newOrganizationId}`, key)
        }
      }
    }
  } else {
    if(filter) {
      await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&filter=${filter}&org_id=${newOrganizationId}`, key)
      filtering.value[key] = filter
    } else {
      if(!filtering.value?.[key] || filtering.value?.[key] === '') {
        await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&org_id=${newOrganizationId}`, key)
      }
    }
  }
}

const retrieve = async () => {
  if(route.params?.id) {
    const res = await $fetch('/api/materials/stock-transfers/'+route.params.id+'/move-line', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: '',
          client: item?.AD_Client_ID?.identifier || '',
          clientId: item?.AD_Client_ID?.id || '',
          organization: item?.AD_Org_ID?.identifier || '',
          organizationId: item?.AD_Org_ID?.id || '',
          warehouse: props.info?.warehouse || '',
          warehouseId: props.info?.warehouseId || '',
          warehouseTo: props.info?.warehouseTo || '',
          warehouseToId: props.info?.warehouseToId || '',
          movement: props.info?.documentNo || '',
          movementId: props.info?.id || '',
          product: item?.M_Product_ID?.identifier || item?.M_Product_ID?.Name || '',
          productId: item?.M_Product_ID?.id || '',
          galleries: [],
          isActive: item?.IsActive ?? true,
          line: item?.Line || '',
          description: item?.Description || '',
          movementQty: item?.MovementQty || 1,
          confirmedQty: item?.ConfirmedQty || 0,
          targetQty: item?.TargetQty || 0,
          scrappedQty: item?.ScrappedQty || 0,
          qtyOnHand: 0,
          locator: item?.M_Locator_ID?.identifier || item?.M_Locator_ID?.Value || '',
          locatorId: item?.M_Locator_ID?.id || '',
          locatorTo: item?.M_LocatorTo_ID?.identifier || '',
          locatorToId: item?.M_LocatorTo_ID?.id || '',
          product: item?.M_Product_ID?.identifier || item?.M_Product_ID?.Name || '',
          productId: item?.M_Product_ID?.id || '',
          attributeSetInstance: item?.M_AttributeSetInstance_ID?.identifier || '',
          attributeSetInstanceId: item?.M_AttributeSetInstance_ID?.id || '',
          attributeSetInstanceTo: item?.M_AttributeSetInstanceTo_ID?.identifier || '',
          attributeSetInstanceToId: item?.M_AttributeSetInstanceTo_ID?.id || '',
          show: false,
          alert: {
            status: '',
            message: '',
            processing: false,
          }
        }
      }).sort((a, b) => Number(a.line) - Number(b.line))
      
      const newEntries = []
      for(let item of entries.value) {
        const response = await $fetch(`/api/materials/products/${item.productId}`)
        if(response?.Strapi_Product_documentId) {
          const resp = await $fetch(`/api/materials/products/${response.Strapi_Product_documentId}/galleries`)
          if(resp?.data) {
            item.galleries = resp.data?.image ?? []
            item.gallery = filterProductGallery(item.galleries, resp.data)
          }
        }
        newEntries.push(item)
      }
      entries.value = newEntries
      save()
    }
  }
}
onMounted(retrieve)

const destroy = async (entry, index) => {
  if(entry.id) {
    await $fetch('/api/materials/stock-transfers/'+entry.id+'/move-line', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
  } else {
    entries.value.splice(index, 1)
  }
}

const chooseLineIndex = ref(NaN)
const chooseLineEntry = ref(null)
const showProductChooser = ref(false)
const hideProductCharge = ref(false)
const productChooserHandler = (prod) => {
  if(chooseLineIndex.value !== NaN && chooseLineEntry.value !== null) {
    const newEntry = chooseLineEntry.value
    newEntry.product = prod?.Name || ''
    newEntry.productId = prod?.id || ''
    /*newEntry.uom = prod?.uom_name || prod?.C_UOM_ID?.identifier || ''
    newEntry.uomId = prod?.c_uom_id || prod?.C_UOM_ID?.id || ''
    newEntry.priceActual = prod?.product_price || prod?.M_ProductPrice?.PriceStd || 0
    newEntry.priceEntered = prod?.product_price || prod?.M_ProductPrice?.PriceList || 0
    newEntry.priceList = prod?.product_price || prod?.M_ProductPrice?.PriceList || 0
    newEntry.charge = ''
    newEntry.chargeId = ''
    newEntry.lineNetAmt = Number(newEntry.qtyEntered) * Number(newEntry.priceEntered);*/
    newEntry.gallery = prod?.gallery ?? {}
    newEntry.galleries = prod?.galleries ?? []
    newEntry.qtyOnHand = (prod?.M_Storage ?? []).map(item => Number(item.QtyOnHand ?? 0)).reduce((acc, cur) => Number(acc) + Number(cur), 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.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 ?? []
  newEntry.qtyOnHand = (prod?.M_Storage ?? []).reduce((acc, cur) => Number(acc.QtyOnHand ?? 0) + Number(cur.QtyOnHand ?? 0), 0) || 0
  hideProductCharge.value = true
}

const locatorHandler = async (newEntry, loc) => {
  const res = await $fetch(`/api/materials/storages?product_id=${newEntry.productId}&locator_id=${loc.id}`, {
    method: 'GET',
    headers: useRequestHeaders(['cookie'])
  })
  newEntry.qtyOnHand = (res?.records ?? []).map(i => i.QtyOnHand).reduce((acc, cur) => Number(acc) + Number(cur), 0) || 0
  newEntry.qtyBook = newEntry.qtyOnHand
}

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

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

<template>
  <div class="lineTableResponsive card sd-none rd-0px bd-1px_solid_hexe4e3e6" @mouseleave="save">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th>Line</th>
            <th colspan="2">Product *</th>
            <th>Movement Qty *</th>
            <th>Qty OnHand</th>
            <th>From Locator *</th>
            <th>To 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' ? 10 : 9" class="align-center">No detail record yet, please add a new one.</td>
          </tr>
          <template v-for="(entry, index) in entries" :key="index">
            <tr>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.line }}</span>
                <input v-else type="text" v-model="entry.line" class="input" />
              </td>
              <td>
                <div>
                  <div v-if="entry?.gallery?.id" @click="viewAttachmentViewer(entry?.gallery ?? {})">
                    <div class="productChooserBox" style="width: 40px; height: 40px;">
                      <img v-if="entry?.gallery?.formats?.small" :src="config.public.strapi+'/files-api/'+entry?.gallery?.formats?.small?.hash + entry?.gallery?.formats?.small?.ext" :alt="entry?.gallery?.name" />
                      <img v-else :src="config.public.strapi+'/files-api/'+entry?.gallery?.formats?.thumbnail?.hash + entry?.gallery?.formats?.thumbnail?.ext" :alt="entry?.gallery?.name" />
                    </div>
                  </div>
                  <div v-else class="productChooserBox" style="width: 40px; height: 40px;">
                    <img v-if="entry.productId" src="https://placehold.co/40x40" alt="Placeholder Image" />
                  </div>
                </div>
              </td>
              <td style="max-width: 400px;">
                <ContextMenu v-model="entry.productId" :items="[(entry.productId ? 'zoom' : 'clear')]" :info="{windowFrom: 'zoom', toPath: '/materials/products/'+entry.productId+'/edit', pathName: 'Product: '+entry.product}">
                  <div>
                    <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.product }}</span>
                    <SelectBox 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">
                      <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>
                    </SelectBox>
                  </div>
                </ContextMenu>
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.movementQty }}</span>
                <input v-else type="text" v-model="entry.movementQty" class="input" />
              </td>
              <td>{{ entry.qtyOnHand }}</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}')`))" :loading="loading?.['locators_'+index] ?? true" :up="true" placeholder="----" @change="(val, opt) => locatorHandler(entry, opt)" />
                </ClientOnly>
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.locator }}</span>
                <ClientOnly v-else>
                  <SelectBox v-model="entry.locatorToId" :options="getOptions?.['to_locators_'+index]?.records || [{id: entry.locatorToId, Value: entry.locatorTo}]" prop="Value" dataprop="id" datatype="string" :size="5" @click="filterOptions('m_locator', 'to_locators_'+index, string.urlEncode(`isActive eq true AND M_Warehouse_ID eq ${info.warehouseToId}`))" @search="(val) => filterOptions('m_locator', 'to_locators_'+index, string.urlEncode(`isActive eq true AND M_Warehouse_ID eq ${info.warehouseToId} AND contains(Name,'${val}')`))" :loading="loading?.['to_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 @click="entry.show = !entry.show;" class="cursor-pointer fg-warning">
                    <i v-if="entry?.show" class="menu-icon tf-icons ti ti-chevron-up"></i>
                    <i v-else class="menu-icon tf-icons ti ti-chevron-down"></i>
                  </span>
                  <span v-if="info.docStatusId !== 'CO'" @click="destroy(entry, index)" class="cursor-pointer fg-danger">
                    <i class="menu-icon tf-icons ti ti-trash"></i>
                  </span>
                </div>
              </td>
            </tr>
            <tr v-if="entry?.show">
              <td :colspan="action !== 'view' ? 8 : 7">
                <div class="my-5 mx-5">
                  <AlertAction v-model='entry.alert.status' :alert="entry.alert" />
                  <div class="columns">
                    <div class="column is-two-thirds">
                      <div class="columns">
                        <div class="column is-half">
                          <label class="label d-block 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>

                          <div :class="(entry.id !== '' || action === 'view' || entry.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                            <label class="label d-block mt-2">From Locator *</label>
                            <ClientOnly>
                              <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="setOptions('materials/locators/'+info.warehouseId, 'locators_'+index)" :loading="loading?.['locators_'+index] ?? true" />
                            </ClientOnly>
                          </div>

                          <label class="label d-block mt-2">From Attribute Set Instance</label>
                          <input type="text" :value="entry.attributeSetInstance" class="input" readonly />

                          <label class="label d-block mt-2">Movement Quantity *</label>
                          <input type="text" v-model="entry.movementQty" class="input" />

                          <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">
                          <label class="label d-block">Line</label>
                          <input type="text" v-model="entry.line" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                          <div :class="(entry.id !== '' || action === 'view' || entry.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                            <label class="label d-block mt-2">To Locator *</label>
                            <ClientOnly>
                              <SelectBox v-model="entry.locatorToId" :options="getOptions?.['to_locators_'+index]?.records || [{id: entry.locatorToId, Value: entry.locatorTo}]" prop="Value" dataprop="id" datatype="string" :size="5" @click="setOptions('materials/locators/'+info.warehouseToId, 'to_locators_'+index)" :loading="loading?.['to_locators_'+index] ?? true" />
                            </ClientOnly>
                          </div>
                          
                          <label class="label d-block mt-2">To Attribute Set Instance</label>
                          <input type="text" :value="entry.attributeSetInstanceTo" class="input" readonly />

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

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