<script setup>
import { SelectBox } from 'tedir-select'

const config = useRuntimeConfig()

definePageMeta({
  middleware: ['auth', 'org']
})

const warehouses = useCookie('logship_warehouses')
const warehouse = useCookie('logship_warehouse')
const warehouseId = useCookie('logship_warehouse_id')

const form = ref({
  Value: '',
  Name: '',
  UPC: '',
  SKU: '',
  warehouse: warehouse.value?.Name || '',
  m_warehouse_id: warehouseId.value || '',
  product_category: '',
  m_product_category_id: '',
  price_list_version: '',
  m_pricelist_version_id: '',
  attributeset: '',
  m_attributeset_id: '',
  salesrep: '',
  salesrep_id: ''
})

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) {
    getOptions.value[key] = res

    if(getOptions.value[key]?.records) {
      getOptions.value[key].records.unshift({
        id: '',
        Name: '-- Select Option --',
        ISO_Code: '-- Select Option --',
        Address1: '-- Select Option --'
      })
    }
  }
  loading.value[key] = false
}

const getWarehouses = computed(() => {
  const newWarehoues = unref(warehouses)
  if(Number(newWarehoues.filter(i => i.id === '').length) === 0) {
    newWarehoues.unshift({
      id: '',
      name: '-- Select Option --'
    })
  }
  return newWarehoues
})

const product = ref({})
const productPrices = ref([])
const products = ref([])
const filterProductChooser = async () => {
  products.value = []
  const queries = ['Value', 'Name', 'UPC', 'SKU', 'm_product_category_id', 'salesrep_id', 'm_attributeset_id', 'issold', 'm_pricelist_version_id', 'm_warehouse_id']
  const defaultUrl = '/api/materials/products/info'
  let newUrl = defaultUrl
  for(let query of queries) {
    if(form.value[query]) {
      if(newUrl === defaultUrl) {
        newUrl += `?${query}=${form.value[query]}`
      } else {
        newUrl += `&${query}=${form.value[query]}`
      }
    }
  }
  const res = await $fetch(newUrl)
  if(res) {
    console.log(res)
    products.value = 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/images`)
        if(resp) {
          item.galleries = resp
        }
      }
      newProducts.push(item)
    }
    products.value = newProducts
    product.value = newProducts?.[0] || {}
    productPrices.value = newProducts?.[0]?.M_ProductPrice || []
  }
}
onMounted(filterProductChooser)
const chooseProduct = (prod) => {
  product.value = prod
  productPrices.value = prod?.M_ProductPrice || []
}

const breadCrumb = computed(() => ([
  { link: '#', text: 'Materials'},
  { link: '/materials/products', text: 'Products'},
  { link: '#', text: 'Product Info', active: true}
]))

const tab = ref('storage')
const tabs = computed(() => ([
  { value: 'storage', text: 'Item Availability in other Warehouses'},
  { value: 'description', text: 'Description'},
  { value: 'substitute', text: 'Substitute'},
  { value: 'related', text: 'Related Product'},
  { value: 'promise', text: 'Available to Promise'},
  { value: 'price', text: 'Price'}
]))
const openTab = (val) => {
  if(tab.value !== val) {
    tab.value = val
  }
}
</script>

<template>
  <Head>
    <Title>Product Info</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    
    <div class="bannercontrol">
      <div class="d-flex gap-10px">
        <button type="button" class="button">Refresh</button>
      </div>
    </div>
    
    <div class="banner">
      <div class="p-1.5rem">
        <div class="d-flex justify-between flexWrap-wrap p-1.5rem gap-1.5rem">
          <div class="legend w-250px">
            <label class="label">Search Key</label>
            <input type="text" v-model="form.Value" class="input" />
          </div>
          <div class="legend w-250px">
            <label class="label">Name</label>
            <input type="text" v-model="form.Name" class="input" />
          </div>
          <div class="legend w-250px">
            <label class="label">UPC/EAN</label>
            <input type="text" v-model="form.UPC" class="input" />
          </div>
          <div class="legend w-250px">
            <label class="label">SKU</label>
            <input type="text" v-model="form.SKU" class="input" />
          </div>
          <div class="legend w-250px">
            <label class="label">Warehouse</label>
            <ClientOnly>
              <SelectBox v-model="form.m_warehouse_id" :options="getWarehouses" @change="(val, opt) => form.warehouse = opt.name" prop="name" dataprop="id" datatype="string" :size="5" />
            </ClientOnly>
          </div>
          <div class="legend w-250px">
            <label class="label">Company Agent</label>
            <ClientOnly>
              <SelectBox v-model="form.salesrep_id" :options="getOptions?.['sales_reps']?.records || [{id: form.salesrep_id, Name: form.salesrep}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_user', 'sales_reps')" :loading="loading?.['sales_reps'] ?? true" placeholder="----" />
            </ClientOnly>
          </div>
          <div class="legend w-250px">
            <label class="label">Product Category</label>
            <ClientOnly>
              <SelectBox v-model="form.m_product_category_id" :options="getOptions?.['product_categories']?.records || [{id: form.m_product_category_id, Name: form.product_category}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_product_category', 'product_categories')" :loading="loading?.['product_categories'] ?? true" placeholder="----" />
            </ClientOnly>
          </div>
          <!--<div class="legend w-250px">
            <label class="label">Price List Version</label>
            <ClientOnly>
              <SelectBox v-model="form.m_pricelist_version_id" :options="getOptions?.['price_list_versions']?.records || [{id: form.m_pricelist_version_id, Name: form.pricelist_version}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_pricelist_version', 'price_list_versions')" :loading="loading?.['price_list_versions'] ?? true" placeholder="----" />
            </ClientOnly>
          </div>
          <div class="legend w-250px">
            <label class="label">Attribute Set</label>
            <ClientOnly>
              <SelectBox v-model="form.m_attributeset_id" :options="getOptions?.['attribute_sets']?.records || [{id: form.m_attributeset_id, Name: form.attributeset}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_attributeset', 'attribute_sets')" :loading="loading?.['attribute_sets'] ?? true" placeholder="----" />
            </ClientOnly>
          </div>-->
          <div>
            <button type="button" class="button" @click="filterProductChooser">Filter</button>
          </div>
        </div>
        <div class="tableResponsive h-450px overflowY-auto p-1.5rem">
          <table class="table tableBorder">
            <thead>
              <tr>
                <th>Search Key</th>
                <th colspan="2">Name</th>
                <th>Type</th>
                <th>Volume</th>
                <th>Weight</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(entry, index) in products" :key="index">
                <td :class="{columnProductInfo: product?.id === entry.id}" @click.self="chooseProduct(entry)">
                  <div class="check">
                    <input type="radio" name="productInfo" :value="entry.id" class="checkInput" :id="'productInfo_'+index" :checked="product?.id === entry.id" @change="chooseProduct(entry)">
                    <label class="checkLabel" :for="'productInfo_'+index">{{ entry.Value }}</label>
                  </div>
                </td>
                <td :class="{columnProductInfo: product?.id === entry.id}" @click="chooseProduct(entry)">
                  <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.id" src="https://placehold.co/40x40" alt="Placeholder Image" />
                    </div>
                  </div>
                </td>
                <td :class="{columnProductInfo: product?.id === entry.id}" @click="chooseProduct(entry)">{{ entry.Name }}</td>
                <td :class="{columnProductInfo: product?.id === entry.id}" @click="chooseProduct(entry)">{{ entry?.ProductType?.identifier || '' }}</td>
                <td :class="{columnProductInfo: product?.id === entry.id}" @click="chooseProduct(entry)">{{ entry?.Volume || 0 }}</td>
                <td :class="{columnProductInfo: product?.id === entry.id}" @click="chooseProduct(entry)">{{ entry?.Weight || 0 }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="bt-2px_dashed_hexe2e2e2 p-1.5rem mt-1.5rem">
          <ProductInfoTab v-model="tab" :tabs="tabs" @handler="(val) => openTab(val.value)" />
          <ProductinfoStorage v-if="tab === 'storage'" :info="product" />
          <textarea v-else-if="tab === 'description'" :value="product?.Description || ''" class="input" disabled></textarea>
          <ProductinfoSubstitute v-else-if="tab === 'substitute'" :info="product" />
          <ProductinfoRelated v-else-if="tab === 'related'" :info="product" />
          <ProductinfoPrice v-else-if="tab === 'price'" :info="product" :items="productPrices" />
        </div>
      </div>
    </div>
  </NuxtLayout>
</template>