<script>
import JournalAction from '../../../components/accountings/JournalAction.vue'

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

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    description: item.Description,
    isActive: item.IsActive,
    documentNo: item.DocumentNo,
    isPrinted: item.IsPrinted,
    dateDoc: item.DateDoc,
    dateAcct: item.DateAcct,
    totalDr: item.TotalDr,
    totalCr: item.TotalCr,
    isApproved: item.IsApproved,
    currencyRate: item.CurrencyRate,
    controlAmt: item.ControlAmt,
    processed: item.Processed,
    docType: item?.C_DocType_ID?.identifier || '',
    docTypeId: item?.C_DocType_ID?.id || '',
    docStatus: item?.DocStatus?.identifier || '',
    docStatusId: item?.DocStatus?.id || '',
    postingType: item?.PostingType?.identifier || '',
    postingTypeId: item?.PostingType?.id || '',
    acctSchema: item?.C_AcctSchema_ID?.identifier || '',
    acctSchemaId: item?.C_AcctSchema_ID?.id || '',
    category: item?.GL_Category_ID?.identifier || '',
    categoryId: item?.GL_Category_ID?.id || '',
    period: item?.C_Period_ID?.identifier || '',
    periodId: item?.C_Period_ID?.id || '',
    currency: item?.C_Currency_ID?.identifier || '',
    currencyId: item?.C_Currency_ID?.id || '',
    conversionType: item?.C_ConversionType_ID?.identifier || '',
    conversionTypeId: item?.C_ConversionType_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' },
  { field: 'name' },
  { 
    field: 'description',
    headerName: 'Description'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'dateAcct',
    headerName: 'Date'
  },
  { 
    field: 'totalDr',
    headerName: 'Debit'
  },
  { 
    field: 'totalCr',
    headerName: 'Credit'
  },
  { 
    headerName: 'Action',
    minWidth: 80,
    type: 'nonEditableColumn',
    cellRenderer: 'JournalAction'
  }
]);

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/accountings/journals/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      description: event.data.description,
      isActive: event.data.isActive,
      documentNo: event.data.documentNo,
      isPrinted: event.data.isPrinted,
      dateDoc: event.data.dateDoc,
      dateAcct: event.data.dateAcct,
      totalDr: event.data.totalDr,
      totalCr: event.data.totalCr,
      isApproved: event.data.isApproved,
      currencyRate: event.data.currencyRate,
      controlAmt: event.data.controlAmt,
      processed: event.data.processed,
    }
  })

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

const breadCrumb = computed(() => ([
  { link: '#', text: 'Journal Entries', active: true}
]))

const create = () => {
  router.push('/accountings/journals/create')
}

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

    const res = await $fetch('/api/accountings/journals/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>Journal Entries</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>
  </NuxtLayout>
</template>