<script>
import DocumentTypeAction from '../../../components/settings/DocumentTypeAction.vue'

export default {
  components: {
    DocumentTypeAction
  }
}
</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/settings/document-types', {
  headers: useRequestHeaders(['cookie'])
})

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    isActive: item.IsActive,
    name: item.Name,
    description: item.Description,
    isDocNoControlled: item.IsDocNoControlled,
    printName: item.PrintName,
    hasCharges: item.HasCharges,
    hasProforma: item.HasProforma,
    isDefault: item.IsDefault,
    documentCopies: item.DocumentCopies,
    isSOTrx: item.IsSOTrx,
    isDefaultCounterDoc: item.IsDefaultCounterDoc,
    isPickQAConfirm: item.IsPickQAConfirm,
    isShipConfirm: item.IsShipConfirm,
    isInTransit: item.IsInTransit,
    isSplitWhenDifference: item.IsSplitWhenDifference,
    isCreateCounter: item.IsCreateCounter,
    isIndexed: item.IsIndexed,
    isOverwriteSeqOnComplete: item.IsOverwriteSeqOnComplete,
    isOverwriteDateOnComplete: item.IsOverwriteDateOnComplete,
    isPrepareSplitDocument: item.IsPrepareSplitDocument,
    isChargeOrProductMandatory: item.IsChargeOrProductMandatory,
    isNoPriceListCheck: item.IsNoPriceListCheck,
    docNoSequence: item.DocNoSequence_ID?.identifier || '',
    docNoSequenceId: item.DocNoSequence_ID?.id || '',
    category: item.GL_Category_ID?.identifier || '',
    categoryId: item.GL_Category_ID?.id || '',
    docBaseType: item.DocBaseType?.identifier || '',
    docBaseTypeId: item.DocBaseType?.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: 'docBaseType',
    headerName: 'Base Type'
  },
  { 
    field: 'description',
    headerName: 'Description'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    headerName: 'Action',
    minWidth: 80,
    type: 'nonEditableColumn',
    cellRenderer: DocumentTypeAction
  }
]);

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/settings/document-types/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      isActive: event.data.isActive,
      name: event.data.name,
      description: event.data.description,
    }
  })

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

const breadCrumb = computed(() => ([
  { link: '#', text: 'Settings'},
  { link: '/settings/document-types', text: 'Document Types', active: true}
]))

const create = () => {
  router.push('/settings/document-types/create')
}

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

    const res = await $fetch('/api/settings/document-types/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>Document Types</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>
  </NuxtLayout>
</template>