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


const { getMenuType } = useRoleMenu()

// This will be set using the composable method
const defaultSideBarMenu = ref('Menu')


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

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

const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
const user = useCookie('logship_user')
const userId = useCookie('logship_user_id')
const config = useRuntimeConfig()

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

})


const form = ref({
  id: props.modelValue.id || '',
  uid: props.modelValue.uid || '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  strapiProductId: props.modelValue.strapiProductId || '',
  strapiProductDocumentId: props.modelValue.strapiProductDocumentId || '',
  name: props.modelValue.name || '',
  sku: props.modelValue.sku || '',
  upc: props.modelValue.upc || '',
  isActive: props.modelValue.isActive ?? true,
  value: props.modelValue.value || '',
  versionNo: props.modelValue.versionNo || '',
  description: props.modelValue.description || '',
  help: props.modelValue.help || '',
  documentNote: props.modelValue.documentNote || '',
  isSummary: props.modelValue.isSummary ?? false,
  isStocked: props.modelValue.isStocked ?? true,
  isPurchased: props.modelValue.isPurchased ?? true,
  isSold: props.modelValue.isSold ?? true,
  volume: props.modelValue.volume || 0,
  weight: props.modelValue.weight || 0,
  width: props.modelValue.width || 0,
  length: props.modelValue.length || 0, 
  height: props.modelValue.height || 0,
  discontinued: props.modelValue.discontinued ?? false,
  isBOM: props.modelValue.isBOM ?? false,
  isInvoicePrintDetails: props.modelValue.isInvoicePrintDetails ?? false,
  isPickListPrintDetails: props.modelValue.isPickListPrintDetails ?? false,
  isVerified: props.modelValue.isVerified ?? false,
  guaranteeDaysMin: props.modelValue.guaranteeDaysMin || 0,
  isWebStoreFeatured: props.modelValue.isWebStoreFeatured ?? false,
  isSelfService: props.modelValue.isSelfService ?? false,
  isDropShip: props.modelValue.isDropShip ?? false,
  isExcludeAutoDelivery: props.modelValue.isExcludeAutoDelivery ?? false,
  unitsPerPack: props.modelValue.unitsPerPack || 0,
  lowLevel: props.modelValue.lowLevel || 0,
  isKanban: props.modelValue.isKanban ?? false,
  isManufactured: props.modelValue.isManufactured ?? false,
  isPhantom: props.modelValue.isPhantom ?? false,
  isOwnBox: props.modelValue.isOwnBox ?? false,
  isAutoProduce: props.modelValue.isAutoProduce ?? false,
  shelfWidth: props.modelValue.shelfWidth || 0,
  shelfHeight: props.modelValue.shelfHeight || 0,
  shelfDepth: props.modelValue.shelfDepth || 0,
  unitsPerPallet: props.modelValue.unitsPerPallet || 0,
  classification: props.modelValue.classification || '',
  customsTariffNumber: props.modelValue.customsTariffNumber || 0,
  group1: props.modelValue.group1 || '',
  group2: props.modelValue.group2 || '',
  asin: props.modelValue.asin || '',
  mpn: props.modelValue.mpn || '',
  uomId: props.modelValue.uomId || '',
  productCategoryId: props.modelValue.productCategoryId || '',
  taxCategoryId: props.modelValue.taxCategoryId || '',
  productTypeId: props.modelValue.productTypeId || 'I',
  attributeSetId: props.modelValue.attributeSetId || '',
  attributeSetInstanceId: props.modelValue.attributeSetInstanceId || '',
  revenueRecognitionId: props.modelValue.revenueRecognitionId || '',
  salesRep: props.modelValue.salesRep || user.value?.Name || '',
  salesRepId: props.modelValue.salesRepId || user.value?.id || userId.value || '',
  mailText: props.modelValue.mailText || '',
  mailTextId: props.modelValue.mailTextId || '',
  labelPrinter: props.modelValue.labelPrinter || 'labelprinter-2',
  labelPrinterId: props.modelValue.labelPrinterId || 'b',
  qtyonhand: props.modelValue.qtyonhand || 0, 
  qtyreserved: props.modelValue.qtyreserved || 0, 
  qtyavilable: props.modelValue.qtyavilable || 0, 
  qtypurchased: props.modelValue.qtypurchased || 0,
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || '',
    processing: props.modelValue.alert.processing ?? false
  }
})

const loading = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    /*if(key === 'locations' && res?.records?.[0]) {
      form.value.partnerLocationId = String(res.records[0].id || '')
      form.value.partnerLocation = res.records[0].Name || ''
    }*/
    
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

const strapiProduct = ref({})
const getStrapiProduct = async () => {
  strapiProduct.value = {}
  if(form.value.strapiProductDocumentId) {
    const res = await $fetch(`/api/materials/products/${form.value.strapiProductDocumentId}/galleries`)
    if(res?.data) {
      strapiProduct.value = res.data
    }
  }
}
onMounted(getStrapiProduct)

const productGalleries = ref([])
const getProductGalleries = async () => {
  productGalleries.value = []
  if(form.value.strapiProductDocumentId) {
    const res = await $fetch(`/api/materials/products/${form.value.strapiProductDocumentId}/galleries/images`)
    if(res) {
      productGalleries.value = res
    }
  }
}
onMounted(getProductGalleries)

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

const productGalleryFiles = ref([])
const productGalleryHandler = async (files) => {
  //console.log(files)
  if(form.value.id && form.value.strapiProductId) {
    files.forEach(async (file) => {
      const formData = new FormData()
      formData.append('field', 'image')
      formData.append('ref', 'api::m-product.m-product')
      formData.append('refId', form.value.strapiProductId)
      formData.append('files', file)
      formData.append('fileInfo', JSON.stringify({
        caption: String(form.value.id), 
        alternativeText: String(form.value.uid), 
        //name: file.name
      }))
      const res = await fetch(config.public.strapi+'/media-api/upload', {
        method: 'POST',
        headers: {
          Authorization: 'Bearer '+config.public.strapitoken
        },
        body: formData
      })

      /*const res = await $fetch(`/api/materials/products/${form.value.id}/galleries`, {
        method: 'POST',
        headers: { 'Content-Type': 'multipart/form-data' },
        body: formData
      })*/
      if(res) {
        getProductGalleries()
        getStrapiProduct()
      }
    })
  }
  setTimeout(() => {
    productGalleryFiles.value = []
  }, 700)
}

const defaultGallery = computed(() => {
  let newGallery = productGalleries.value?.[0] ?? {}
  if(strapiProduct.value?.Main_Image && strapiProduct.value?.Main_Image != 0) {
    newGallery = productGalleries.value.filter(i => i.id == strapiProduct.value.Main_Image)?.[0] ?? {}
  }
  return newGallery
})

const confirmGallery = ref({
  show: false,
  title: 'Delete Confirmation',
  subTitle: 'Are you sure, do you want to delete this image?',
  id: ''
})
const confirmDestroyGallery = async (item) => {
  if(item.id) {
    confirmGallery.value.show = true
    confirmGallery.value.id = item.id
  }
}
const destroyGallery = async (targetId) => {
  //productGalleries.value.splice(index, 1)
  if(targetId) {
    const res = await $fetch(`/api/materials/products/${targetId}/galleries`, {
      method: 'DELETE'
    })
    if(res) {
      confirmGallery.value.id = ''
      getProductGalleries()
      getStrapiProduct()
    }
  }
}

const selectedGallery = async (gallery) => {
  if(strapiProduct.value?.documentId) {
    const res = await $fetch(`/api/materials/products/${strapiProduct.value.documentId}/galleries`, {
      method: 'PUT',
      body: {
        imageId: gallery.id
      }
    })
    if(res) {
      //getProductGalleries()
      getStrapiProduct()
    }
  } else {
    toast({
      message: 'Currently Strapi Product is not being synced yet!',
      type: 'is-warning',
      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 = {}
  }
})

const debounce = (func, timeout = 300) => {
  let timer;
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => { func.apply(this, args); }, timeout)
  }
}

const convertDecimal = (value) => {
  if (typeof value === 'string') {
    // Replace comma with dot for decimal separator
    return value.replace(',', '.')
  }
  return value
}

const handleDecimalInput = (field, event) => {
  const value = event.target.value
  const convertedValue = convertDecimal(value)
  form.value[field] = convertedValue
  save()
}

const save = debounce(() => {
  // Ensure all decimal fields are properly formatted before saving
  const formattedForm = {
    ...form.value,
    volume: convertDecimal(form.value.volume),
    weight: convertDecimal(form.value.weight),
    width: convertDecimal(form.value.width),
    length: convertDecimal(form.value.length),
    height: convertDecimal(form.value.height)
  }
  emit('update:modelValue', formattedForm)
  emit('save', formattedForm)
})

const createStrapi = async () => {
  const res = await $fetch('/api/materials/products/create-strapi', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      name: form.value.name,
      value: form.value.value
    }
  })
  if(res) {
    form.value.strapiProductId = res.id
    form.value.strapiProductDocumentId = res.documentId
  }
}

const openOtherTab = () => {
  if(props.tab === 'basic') {
    emit('update:tab', 'classification')
  } else if(props.tab === 'classification') {
    emit('update:tab', 'gallery')
  } else if(props.tab === 'gallery') {
    emit('update:tab', 'reference')
  } else if(props.tab === 'reference') {
    emit('update:tab', 'status')
  }
}
</script>

<template>
  <div>
    <div class="my-5 mx-5">
      <!--<AlertAction v-model='form.alert.status' :alert="form.alert" />-->

      <template v-if="tab === 'basic'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">

            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">Name *</label>
                <input type="text" v-model="form.name" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block">Search Key</label>
                <input type="text" v-model="form.value" :readonly="defaultSideBarMenu === 'c'" class="input" @keyup="save" />
              </div>
            </div>

            <div class="columns is-desktop">
              <div class="column is-one-third">
                <label class="label d-block">SKU</label>
                <input type="text" v-model="form.sku" :readonly="defaultSideBarMenu === 'c'" class="input" @keyup="save"/>
              </div>
              <div class="column is-one-third">
                <label class="label d-block">Barcode (UPC/EAN)</label>
                <input type="text" v-model="form.upc" :readonly="defaultSideBarMenu === 'c'" class="input" @keyup="save" />
              </div>
              <div class="column is-one-third">
                <label class="label d-block">ASIN</label>
                <input type="text" v-model="form.asin" class="input" @keyup="save" />
              </div>
            </div>

            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">Manufacturer Product Number</label>
                <input type="text" v-model="form.mpn" class="input" @keyup="save" />
              </div>
              <div v-if="defaultSideBarMenu !== 'c'"class="column is-half">
                <label class="label d-block">Label Printer</label>
                <ClientOnly>
                  <SelectBox v-model="form.labelPrinterId" :options="getOptions?.['label_printers']?.reflist || [{value: form.labelPrinterId, name: form.labelPrinter}]" prop="name" dataprop="value" datatype="string" :size="5" @load="setOptions('references/labelprinter', 'label_printers')" @change="save" :loading="loading?.['label_printers'] ?? true" />
                </ClientOnly>
              </div>
            </div>

            <label class="label d-block mt-2">Description</label>
            <textarea v-model="form.description" class="input" @keyup="save"></textarea>

            <div class="columns is-desktop mt-2">
              <div class="column is-half">
                <label class="label d-block mt-2">Qty on Hand</label>
                <input type="text" v-model="form.qtyonhand" readonly class="input" />
                
                <label class="label d-block mt-2">Qty Reserved</label>
                <input type="text" v-model="form.qtyreserved" readonly class="input" />
              </div>
              <div class="column is-half">
                <label class="label d-block mt-2">Qty Avilable</label>
                <input type="text" v-model="form.qtyavilable" readonly class="input" />
                
                <label class="label d-block mt-2">Qty Purchased</label>
                <input type="text" v-model="form.qtypurchased" readonly class="input" />
              </div>
            </div>

          </div>
          <div class="column is-one-third">
            <div v-if="defaultGallery?.id" class="thumbnailBox">
              <img v-if="defaultGallery?.formats?.small" :src="config.public.strapi+'/files-api/'+defaultGallery?.formats?.small?.hash + defaultGallery?.formats?.small?.ext" :alt="defaultGallery?.name ?? ''" />
              <img v-else :src="config.public.strapi+'/files-api/'+defaultGallery?.formats?.thumbnail?.hash + defaultGallery?.formats?.thumbnail?.ext" :alt="defaultGallery?.name ?? ''" />
            </div>

            <label class="label d-block" :class="{'mt-2': defaultGallery?.id}">Organization *</label>
            <SelectBox v-model="form.organizationId" :options="getOptions?.['orgs']?.records || [{id: form.organizationId, Name: form.organization}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_org', 'orgs')" @change="(val, opt) => {form.organization = opt.Name; save();}" :loading="loading?.['orgs'] ?? true" />

            <label v-if="defaultSideBarMenu !== 'c'" class="label d-block mt-2">Tenant *</label>
            <input v-if="defaultSideBarMenu !== 'c'" type="text" :value="clientName" class="input" readonly />

            <label v-if="defaultSideBarMenu !== 'c'" class="label d-block mt-2">Status</label>
            <div v-if="defaultSideBarMenu !== 'c'" class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isActive" class="checkInput" id="isActive" :checked="form.isActive" @change="save">
                <label class="checkLabel" for="isActive">Active</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isSummary" class="checkInput" id="isSummary" :checked="form.isSummary" @change="save">
                <label class="checkLabel" for="isSummary">Summary Level</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'classification'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">Product Type *</label>
                <select v-model="form.productTypeId" class="select" @change="save">
                  <option value="A">Asset</option>
                  <option value="E">Expense type</option>
                  <option value="I">Item</option>
                  <option value="R">Resource</option>
                  <option value="S">Service</option>
                </select>

                <label class="label d-block mt-2">Stock Unit *</label>
                <ClientOnly>
                  <SelectBox v-model="form.uomId" :options="getOptions?.['uoms']?.records || [{id: form.uomId, Name: form.uom}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_uom', 'uoms')" @change="save" :loading="loading?.['uoms'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Revenue Recognition</label>
                <ClientOnly>
                  <SelectBox v-model="form.revenueRecognitionId" :options="getOptions?.['revenue_recognitions']?.records || [{id: form.revenueRecognitionId, Name: form.revenueRecognition}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_revenuerecognition', 'revenue_recognitions')" @change="save" :loading="loading?.['revenue_recognitions'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Customs Tariff Number</label>
                <input type="text" v-model="form.customsTariffNumber" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block">Product Category *</label>
                <ClientOnly>
                  <SelectBox v-model="form.productCategoryId" :options="getOptions?.['product_categories']?.records || [{id: form.productCategoryId, Name: form.productCategory}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_product_category', 'product_categories')" @change="save" :loading="loading?.['product_categories'] ?? true" />
                </ClientOnly>

                <template v-if="!form.isSummary">
                  <label class="label d-block mt-2">Tax Category *</label>
                  <ClientOnly>
                    <SelectBox v-model="form.taxCategoryId" :options="getOptions?.['tax_categories']?.records || [{id: form.taxCategoryId, Name: form.taxCategory}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_taxcategory', 'tax_categories')" @change="save" :loading="loading?.['tax_categories'] ?? true" />
                  </ClientOnly>
                </template>

                <label class="label d-block mt-2">Mail Template</label>
                <ClientOnly>
                  <SelectBox v-model="form.mailTextId" :options="getOptions?.['mail_texts']?.records || [{id: form.mailTextId, Name: form.mailText}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/r_mailtext', 'mail_texts')" @change="save" :loading="loading?.['mail_texts'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Classification</label>
                <input type="text" v-model="form.classification" class="input" @keyup="save" />
              </div>
            </div>
              <label class="label d-block">Version Number</label>
              <input type="text" v-model="form.versionNo" class="input" @keyup="save" />
          </div>


          <div class="column is-one-third">
            <label class="label d-block">Classification Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isStocked" class="checkInput" id="isStocked" :checked="form.isStocked" @change="save">
                <label class="checkLabel" for="isStocked">Stocked</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isSold" class="checkInput" id="isSold" :checked="form.isSold" @change="save">
                <label class="checkLabel" for="isSold">Sold</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isPurchased" class="checkInput" id="isPurchased" :checked="form.isPurchased" @change="save">
                <label class="checkLabel" for="isPurchased">Purchased</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isOwnBox" class="checkInput" id="isOwnBox" :checked="form.isOwnBox" @change="save">
                <label class="checkLabel" for="isOwnBox">Own Box</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'gallery'">
        <div class="productGallery">
          <div v-for="(gallery, index) in productGalleries" :key="index">
            <div v-if="gallery?.formats?.thumbnail" class="galleryBox" @click.self="viewAttachmentViewer(gallery)">
<!--          <img :src="config.public.strapi+'/files-api/'+gallery.url.replace('/uploads/', '')" :alt="gallery.name" />-->
              <img :src="config.public.strapi+'/files-api/'+gallery?.formats?.thumbnail?.hash + gallery?.formats?.thumbnail?.ext" :alt="gallery.name" style="pointer-events: none;" />
              <span v-if="strapiProduct?.Main_Image == gallery.id" class="selectedGalleryBox tf-icon ti ti-square-rounded-check-filled ti-sm"></span>
              <span v-else class="chooseGalleryBox tf-icon ti ti-square-rounded ti-sm" @click="selectedGallery(gallery)"></span>
              <span class="destroyGalleryBox tf-icon ti ti-trash-x-filled ti-sm" @click="confirmDestroyGallery(gallery)"></span>
            </div>
          </div>
          <div v-if="Number(productGalleries.length || 0) === 0 && form.id !== '' && form.strapiProductId === ''">
            <button type="button" class="button" @click="createStrapi">Show Gallery Upload</button>
          </div>
          <AttachBox v-if="form.strapiProductId" v-model="productGalleryFiles" @handler="productGalleryHandler" accept="image/*">
            <div class="addGalleryBox">
              <span class="tf-icon ti ti-photo-plus ti-xl"></span>
            </div>
          </AttachBox>
        </div>
      </template>
      <template v-else-if="tab === 'reference'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-half">
                <template v-if="!form.isSummary">
                  <label class="label d-block">Weight</label>
                  <input type="text" v-model="form.weight" class="input" @input="handleDecimalInput('weight', $event)" />

                  <label class="label d-block mt-2">Width</label>
                  <input type="text" v-model="form.width" class="input" @input="handleDecimalInput('width', $event)" />

                  <label class="label d-block mt-2">Height</label>
                  <input type="text" v-model="form.height" class="input" @input="handleDecimalInput('height', $event)" />
                </template>

                <label class="label d-block mt-2">Sales Representative</label>
                <ClientOnly>
                  <SelectBox v-model="form.salesRepId" :options="getOptions?.['sales_reps']?.records || [{id: form.salesRepId, Name: form.salesRep}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_user', 'sales_reps')" @change="save" :loading="loading?.['sales_reps'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Part Type</label>
                <ClientOnly>
                  <SelectBox v-model="form.partTypeId" :options="getOptions?.['part_types']?.records || [{id: form.partTypeId, Name: form.partType}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_parttype', 'part_types')" @change="save" :loading="loading?.['part_types'] ?? true" />
                </ClientOnly>
              </div>
              <div class="column is-half">
                <template v-if="!form.isSummary">
                  <label class="label d-block">Volume</label>
                  <input type="text" v-model="form.volume" class="input" @input="handleDecimalInput('volume', $event)" />

                  <label class="label d-block mt-2">Length</label>
                  <input type="text" v-model="form.length" class="input" @input="handleDecimalInput('length', $event)" />

                  <label class="label d-block mt-2">Freight Category</label>
                  <ClientOnly>
                    <SelectBox v-model="form.freightCategoryId" :options="getOptions?.['freight_categories']?.records || [{id: form.freightCategoryId, Name: form.freightCategory}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_freightcategory', 'freight_categories')" @change="save" :loading="loading?.['freight_categories'] ?? true" />
                  </ClientOnly>
                </template>

                <template v-if="!form.isSummary && form.isStocked">
                  <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('models/m_locator', 'locators')" @change="save" :loading="loading?.['locators'] ?? true" />
                  </ClientOnly>
                </template>
              </div>
            </div>

            <div v-if="!form.isSummary && form.isStocked" class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">Shelf Width</label>
                <input type="text" v-model="form.shelfWidth" class="input" @keyup="save" />
                
                <label class="label d-block mt-2">Shelf Depth</label>
                <input type="text" v-model="form.shelfDepth" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block">Shelf Height</label>
                <input type="text" v-model="form.shelfHeight" class="input" @keyup="save" />
                
                <label class="label d-block mt-2">Units Per Pallet</label>
                <input type="text" v-model="form.unitsPerPack" class="input" @keyup="save" />
              </div>
            </div>

            <label class="label d-block mt-2">Help/Comment</label>
            <textarea v-model="form.help" class="input"></textarea>
          </div>
          <div class="column is-one-third">
            <label class="label d-block">Reference Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isStocked" class="checkInput" id="isStocked" :checked="form.isStocked" @change="save">
                <label class="checkLabel" for="isStocked">Stocked</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isDropShip" class="checkInput" id="isDropShip" :checked="form.isDropShip" @change="save">
                <label class="checkLabel" for="isDropShip">Drop Shipment</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'status'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div v-if="!form.isSummary" class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">Attribute Set</label>
                <ClientOnly>
                  <SelectBox v-model="form.attributeSetId" :options="getOptions?.['attribute_sets']?.records || [{id: form.attributeSetId, Name: form.attributeSet}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_attributeset', 'attribute_sets')" @change="save" :loading="loading?.['attribute_sets'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Image URL</label>
                <input type="text" v-model="form.imageURL" class="input" @keyup="save" />
                
                <label class="label d-block mt-2">Guarantee Days</label>
                <input type="text" v-model="form.guaranteeDays" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block">Attribute Set Instance</label>
                <ClientOnly>
                  <SelectBox v-model="form.attributeSetInstanceId" :options="getOptions?.['attribute_set_instances']?.records || [{id: form.attributeSetInstanceId, Name: form.attributeSetInstance}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_attributesetinstance', 'attribute_set_instances')" @change="save" :loading="loading?.['attribute_set_instances'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Description URL</label>
                <input type="text" v-model="form.descriptionURL" class="input" @keyup="save" />
                
                <label class="label d-block mt-2">Min Guarantee Days</label>
                <input type="text" v-model="form.guaranteeDaysMin" class="input" @keyup="save" />
              </div>
            </div>

            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block mt-2">Group 1</label>
                <input type="text" v-model="form.group1" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block mt-2">Group 2</label>
                <input type="text" v-model="form.group2" class="input" @keyup="save" />
              </div>
            </div>

            <label class="label d-block mt-2">Document Note</label>
            <textarea v-model="form.documentNote" class="input" @keyup="save"></textarea>
          </div>
          <div class="column is-one-third">
            <label class="label d-block">Document Status</label>
            <div class="d-flex flexDirection-column">
              <template v-if="!form.isSummary">
                <div class="check">
                  <input type="checkbox" v-model="form.discontinued" class="checkInput" id="discontinued" :checked="form.discontinued" @change="save">
                  <label class="checkLabel" for="discontinued">Discontinued</label>
                </div>
                <div class="check">
                  <input type="checkbox" v-model="form.isSelfService" class="checkInput" id="isSelfService" :checked="form.isSelfService" @change="save">
                  <label class="checkLabel" for="isSelfService">Self Service</label>
                </div>
                <div class="check">
                  <input type="checkbox" v-model="form.isExcludeAutoDelivery" class="checkInput" id="isExcludeAutoDelivery" :checked="form.isExcludeAutoDelivery" @change="save">
                  <label class="checkLabel" for="isExcludeAutoDelivery">Exclude Auto Delivery</label>
                </div>
                <div class="check">
                  <input type="checkbox" v-model="form.isWebStoreFeatured" class="checkInput" id="isWebStoreFeatured" :checked="form.isWebStoreFeatured" @change="save">
                  <label class="checkLabel" for="isWebStoreFeatured">Featured in Web Store</label>
                </div>
              </template>
              <div class="check">
                <input type="checkbox" v-model="form.isManufactured" class="checkInput" id="isManufactured" :checked="form.isManufactured" @change="save">
                <label class="checkLabel" for="isManufactured">Manufactured</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isPhantom" class="checkInput" id="isPhantom" :checked="form.isPhantom" @change="save">
                <label class="checkLabel" for="isPhantom">Phantom</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isKanban" class="checkInput" id="isKanban" :checked="form.isKanban" @change="save">
                <label class="checkLabel" for="isKanban">Kanban Controlled</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isAutoProduce" class="checkInput" id="isAutoProduce" :checked="form.isAutoProduce" @change="save">
                <label class="checkLabel" for="isAutoProduce">Auto Produce</label>
              </div>
            </div>
          </div>
        </div>
      </template>

    </div>
  </div>

  <Teleport to="body">
    <ConfirmBox v-model="confirmGallery.show" :title="confirmGallery.title" :subTitle="confirmGallery.subTitle" :targetId="confirmGallery.id" @handler="destroyGallery" />
    <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>