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

export default {
  components: {
    SchemaAction
  }
}
</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/schemas', {
  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,
    isAccrual: item.IsAccrual,
    autoPeriodControl: item.AutoPeriodControl,
    periodOpenHistory: item.Period_OpenHistory,
    periodOpenFuture: item.Period_OpenFuture,
    separator: item.Separator,
    hasAlias: item.HasAlias,
    hasCombination: item.HasCombination,
    isTradeDiscountPosted: item.IsTradeDiscountPosted,
    isDiscountCorrectsTax: item.IsDiscountCorrectsTax,
    isAdjustCOGS: item.IsAdjustCOGS,
    isPostServices: item.IsPostServices,
    isExplicitCostAdjustment: item.IsExplicitCostAdjustment,
    isAllowNegativePosting: item.IsAllowNegativePosting,
    isPostIfClearingEqual: item.IsPostIfClearingEqual,
    gaap: item?.GAAP?.identifier || '',
    gaapId: item?.GAAP?.id || '',
    costingMethod: item?.CostingMethod?.identifier || '',
    costingMethodId: item?.CostingMethod?.id || '',
    currency: item?.C_Currency_ID?.identifier || '',
    currencyId: item?.C_Currency_ID?.id || '',
    period: item?.C_Period_ID?.identifier || '',
    periodId: item?.C_Period_ID?.id || '',
    costType: item?.M_CostType_ID?.identifier || '',
    costTypeId: item?.M_CostType_ID?.id || '',
    costingLevel: item?.CostingLevel?.identifier || '',
    costingLevelId: item?.CostingLevel?.id || '',
    commitmentType: item?.CommitmentType?.identifier || '',
    commitmentTypeId: item?.CommitmentType?.id || '',
    taxCorrectionType: item?.TaxCorrectionType?.identifier || '',
    taxCorrectionTypeId: item?.TaxCorrectionType?.id || '',
    orgOnly: item?.AD_OrgOnly_ID?.identifier || '',
    orgOnlyId: item?.AD_OrgOnly_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: 'name' },
  { 
    field: 'description',
    headerName: 'Description'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'gaap',
    headerName: 'GAAP',
    type: 'nonEditableColumn'
  },
  { 
    field: 'commitmentType',
    headerName: 'Commitment Type',
    type: 'nonEditableColumn'
  },
  { 
    headerName: 'Action',
    minWidth: 80,
    type: 'nonEditableColumn',
    cellRenderer: 'SchemaAction'
  }
]);

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/schemas/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      name: event.data.name,
      description: event.data.description,
      isActive: event.data.isActive,
      isAccrual: event.data.isAccrual,
      autoPeriodControl: event.data.autoPeriodControl,
      periodOpenHistory: event.data.periodOpenHistory,
      periodOpenFuture: event.data.periodOpenFuture,
      separator: event.data.separator,
      hasAlias: event.data.hasAlias,
      hasCombination: event.data.hasCombination,
      isTradeDiscountPosted: event.data.isTradeDiscountPosted,
      isDiscountCorrectsTax: event.data.isDiscountCorrectsTax,
      isAdjustCOGS: event.data.isAdjustCOGS,
      isPostServices: event.data.isPostServices,
      isExplicitCostAdjustment: event.data.isExplicitCostAdjustment,
      isAllowNegativePosting: event.data.isAllowNegativePosting,
      isPostIfClearingEqual: event.data.isPostIfClearingEqual,
    }
  })

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

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

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

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

    const res = await $fetch('/api/accountings/schemas/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>Accounting Schemas</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>