<script>
import StockUnitAction from '../../../components/materials/StockUnitAction.vue'

export default {
  components: {
    StockUnitAction
  }
}
</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/stock-units', {
  headers: useRequestHeaders(['cookie'])
})

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    name: item.Name,
    description: item.Description,
    isActive: item.IsActive,
    isDefault: item.IsDefault,
    stdPrecision: item.StdPrecision,
    costingPrecision: item.CostingPrecision,
    uomSymbol: item.UOMSymbol,
    uomCode: item.X12DE355,
    organization: item.AD_Org_ID?.identifier || '',
    organizationId: item.AD_Org_ID?.id || '',
    uomType: item.UOMType?.identifier || '',
    uomTypeId: item.UOMType?.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: 'uomSymbol',
    headerName: 'Unit Symbol'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'stdPrecision',
    headerName: 'Standard Precision'
  },
  { 
    field: 'costingPrecision',
    headerName: 'Costing Precision'
  },
  { 
    field: 'uomType',
    headerName: 'Unit Type',
    type: 'nonEditableColumn'
  },
  {
    headerName: 'Action',
    width: 100,
    pinned: 'right',
    cellRenderer: StockUnitAction
  }
]);

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/stock-units/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      name: event.data.name,
      description: event.data.description,
      isActive: event.data.isActive,
      value: event.data.value,
      isDefault: event.data.isDefault,
      plannedMargin: event.data.plannedMargin,
      isSelfService: event.data.isSelfService,
      assetGroupId: event.data.assetGroupId,
      printColorId: event.data.printColorId,
      mMPolicyId: event.data.mMPolicyId,
      parentProductCategoryId: event.data.parentProductCategoryId,
    }
  })

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

const breadCrumb = computed(() => ([
  { link: '#', text: 'Materials'},
  { link: '/materials/stock-units', text: 'Stock Units', active: true}
]))

const create = () => {
  router.push('/materials/stock-units/create')
}

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

    const res = await $fetch('/api/materials/stock-units/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>Stock Units</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <div>
      <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>
    </div>

    <Teleport to="body">
      <MaterialsStockUnitQuickView />
    </Teleport>
  </NuxtLayout>
</template>