<script>
import ProductAction from '../../../components/materials/ProductAction.vue'
import ProductThumbnail from '../../../components/materials/ProductThumbnail.vue'
import AgCustomLink from '../../../components/AgGrid/Products/AgCustomLink.vue'
import AgCustomLinkValue from '../../../components/AgGrid/Products/AgCustomLinkValue.vue'

export default {
  components: {
    ProductAction,
    ProductThumbnail,
    AgCustomLink,
    AgCustomLinkValue
  }
}
</script>

<script setup>
const router = useRouter()
const tabs = useTabs()

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

const isDeletable = ref(false)
const searchQuery = ref('')
const selectedRows = ref([])

const { data, pending, error, refresh } = await useFetch('/api/materials/products', {
  headers: useRequestHeaders(['cookie'])
})

const storageCount = (storages, key) => {
  const newStorage = storages.map(i => i[key]).reduce((acc, prev) => Number(acc) + Number(prev), 0)
  return newStorage
}

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    name: item.Name,
    value: item.Value,
    sku: item.SKU,
    mpn: item.mpn,
    upc: item.UPC,
    description: item.Description,
    help: item.Help,
    isStocked: item.IsStocked,
    isPurchased: item.IsPurchased,
    isSold: item.IsSold,
    volume: item.Volume,
    weight: item.Weight,
    discontinued: item.Discontinued,
    isBOM: item.IsBOM,
    isInvoicePrintDetails: item.IsInvoicePrintDetails,
    isPickListPrintDetails: item.IsPickListPrintDetails,
    isVerified: item.IsVerified,
    guaranteeDaysMin: item.GuaranteeDaysMin,
    isWebStoreFeatured: item.IsWebStoreFeatured,
    isSelfService: item.IsSelfService,
    isDropShip: item.IsDropShip,
    isExcludeAutoDelivery: item.IsExcludeAutoDelivery,
    unitsPerPack: item.UnitsPerPack,
    lowLevel: item.LowLevel,
    isKanban: item.IsKanban,
    isManufactured: item.IsManufactured,
    isPhantom: item.IsPhantom,
    isOwnBox: item.IsOwnBox,
    isAutoProduce: item.IsAutoProduce,
    strapiProductId: item.Strapi_Product_documentId,
    uom: item.C_UOM_ID?.identifier || '',
    uomId: item.C_UOM_ID?.id || '',
    productCategory: item.M_Product_Category_ID?.identifier || '',
    productCategoryId: item.M_Product_Category_ID?.id || '',
    taxCategory: item.C_TaxCategory_ID?.identifier || '',
    taxCategoryId: item.C_TaxCategory_ID?.id || '',
    productType: item.ProductType?.identifier || '',
    productTypeId: item.ProductType?.id || '',
    attributeSet: item.M_AttributeSet_ID?.identifier || '',
    attributeSetId: item.M_AttributeSet_ID?.id || '',
    attributeSetInstance: item.M_AttributeSetInstance_ID?.identifier || '',
    attributeSetInstanceId: item.M_AttributeSetInstance_ID?.id || '',
    organization: item.AD_Org_ID?.identifier || '',
    organizationId: item.AD_Org_ID?.id || '',
    qtyonhand: storageCount(item?.M_Storage ?? [], 'QtyOnHand')
  }
}) || []);

const forcingLogout = async () => {
  await $fetch('/api/idempiere-auth/logout', {
    method: 'POST',
    headers: useRequestHeaders(['cookie'])
  })

  tabs.value = [{link: '/', text: 'Home', active: true}]
  localStorage.setItem('tabs', JSON.stringify(tabs.value))

  console.info('Session expired and it will auto redirected toward login page.')
  location.href = '/signin'
}
const alert = ref({
  status: data.value?.status || 200,
  message: data.value?.message || ''
});
onBeforeMount(() => {
  if(Number(data.value?.status || 200) === 401) {
    forcingLogout()
  }
})
watch(data, () => {
  alert.value.status = data.value?.status || 200
  alert.value.message = data.value?.message || ''
  if(Number(data.value?.status || 200) === 401) {
    forcingLogout()
  }
})

const checkboxSelection = (params) => {
  return params.api.getRowGroupColumns().length === 0;
};
const headerCheckboxSelection = (params) => {
  return params.api.getRowGroupColumns().length === 0;
};

const colDefs = ref([
  { 
    width: 50,
    checkboxSelection: checkboxSelection,
    headerCheckboxSelection: headerCheckboxSelection,
    maxWidth: 30
  },
  // {
  //   field: 'id',
  //   //hide: true,
  //   sort: 'desc'
  // },
  {
    headerName: 'Org',
    field: 'organization',
    type: 'nonEditableColumn',
    maxWidth: 100,
    filter: true,
    floatingFilter: true,
    suppressHeaderMenuButton: true,
    suppressHeaderFilterButton: true,
    suppressHeaderContextMenu: true
  },
  { 
    field: 'value',
    cellRenderer: AgCustomLinkValue,
    maxWidth: 110,
    filter: true,
    floatingFilter: true,
    suppressHeaderMenuButton: true,
    suppressHeaderFilterButton: true,
    suppressHeaderContextMenu: true
  },
  {
    field: 'sku',
    headerName: 'SKU',
    flex: 1,
    filter: true,
    floatingFilter: true,
    suppressHeaderMenuButton: true,
    suppressHeaderFilterButton: true,
    suppressHeaderContextMenu: true
  },
  {
    field: 'mpn',
    headerName: 'MPN',
    flex: 1,
    filter: true,
    floatingFilter: true,
    suppressHeaderMenuButton: true,
    suppressHeaderFilterButton: true,
    suppressHeaderContextMenu: true
  },
  {
    field: 'upc',
    headerName: 'EAN',
    flex: 1,
    filter: true,
    floatingFilter: true,
    suppressHeaderMenuButton: true,
    suppressHeaderFilterButton: true,
    suppressHeaderContextMenu: true
  },
  {
    field: 'weight',
    headerName: 'weight',
    minWidth: 70,
    filter: true,
    floatingFilter: true,
    suppressHeaderMenuButton: true,
    suppressHeaderFilterButton: true,
    suppressHeaderContextMenu: true
  },
  {
    field: 'isBOM',
    headerName: 'BOM',
    maxWidth: 70,
    filter: true,
    floatingFilter: true,
    suppressHeaderMenuButton: true,
    suppressHeaderFilterButton: true,
    suppressHeaderContextMenu: true
  },
  {
    headerName: '',
    cellRenderer: ProductThumbnail,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
    maxWidth: 40
  },
  {
    field: 'name',
    cellRenderer: AgCustomLink,
    maxWidth: 400,
    filter: true,
    floatingFilter: true,
    suppressHeaderMenuButton: true,
    suppressHeaderFilterButton: true,
    suppressHeaderContextMenu: true
  },
  {
    field: 'qtyonhand',
    headerName: 'Lagerbestand',
    maxWidth: 120,
    filter: true,
    floatingFilter: true,
    suppressHeaderMenuButton: true,
    suppressHeaderFilterButton: true,
    suppressHeaderContextMenu: true,
    type: 'numericColumn'
  },
  // {
  //   field: 'uom',
  //   headerName: 'Stock Unit',
  //   type: 'nonEditableColumn'
  // },
  // {
  //   field: 'productCategory',
  //   headerName: 'Product Category',
  //   type: 'nonEditableColumn'
  // },
  // {
  //   field: 'taxCategory',
  //   headerName: 'Tax Category',
  //   type: 'nonEditableColumn'
  // },
  // {
  //   field: 'productType',
  //   headerName: 'Product Type',
  //   type: 'nonEditableColumn'
  // },
  {
    headerName: 'Action',
    width: 100,
    pinned: 'right',
    cellRenderer: ProductAction
  }
]);

const cellClick = (event, gridApi) => {
  selectedRows.value = gridApi.getSelectedRows()

  if(event.source === 'checkboxSelected') {
    isDeletable.value = false
    if(selectedRows.value.length >= 1) {
      isDeletable.value = true
    }
  }
}

const cellChange = async (event) => {
  const res = await $fetch('/api/materials/products/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      name: event.data.name,
      isActive: event.data.isActive,
    }
  })

  if(Number(res.status) >= 400) {
    alert.value.status = res.status
    alert.value.message = res.message
  }
}

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

const create = () => {
  router.push('/materials/products/create')
}

const destroy = async () => {
  if(selectedRows.value.length >= 1) {
    isDeletable.value = false

    const res = await $fetch('/api/materials/products/destroy', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie']),
      body: {
        ids: selectedRows.value.map(i => i.id)
      }
    })

    if(Number(res.status) >= 400) {
      alert.value.status = res.status
      alert.value.message = res.message
    }

    refresh()
  }
}
</script>

<template>
  <Head>
    <Title>Products</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <div class="banner datatable-wrapper">
      <HeaderAction :isDeletable="isDeletable" @create="create" @destroy="destroy" />
      <div>
        <div>
          <AlertBox :alert="alert" />
          <div class="mb-3">
            <AgGrid :entries="rowData" :columns="colDefs" @cellClick="cellClick" @cellChange="cellChange" />
          </div>
        </div>
      </div>
    </div>
    
    <Teleport to="body">
      <AttachmentPreview />
    </Teleport>
  </NuxtLayout>
</template>