<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/stock-missings', {
  headers: useRequestHeaders(['cookie'])
})

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    name: item.Name,
    value: item.Value,
    isActive: item.IsActive,
    qtyorder: item.qtyorder,
    qtymissing: item.qtymissing,
    client: item.AD_Client_ID?.identifier || '',
    clientId: item.AD_Client_ID?.id || '',
    organization: item.AD_Org_ID?.identifier || '',
    organizationId: item.AD_Org_ID?.id || '',
  }
}) || []);

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
  },
  { 
    field: 'id',
    //hide: true,
    sort: 'desc'
  },
  { 
    field: 'organization',
    type: 'nonEditableColumn' 
  },
  { field: 'name' },
  { 
    field: 'value',
    headerName: 'Search Key'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'qtyorder',
    headerName: 'Qty Order'
  },
  { 
    field: 'qtymissing',
    headerName: 'Qty Missing'
  }
]);

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 breadCrumb = computed(() => ([
  { link: '#', text: 'Materials'},
  { link: '/materials/stock-missings', text: 'Stock Missings', active: true}
]))
</script>

<template>
  <Head>
    <Title>Stock Missings</Title>
  </Head>

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