<script>
import ProjectAction from '../../../components/projects/ProjectAction.vue'

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

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    name: item.Name,
    value: item.Value,
    description: item.Description,
    isActive: item.IsActive,
    note: item.Note,
    isSummary: item.IsSummary,
    isCommitment: item.IsCommitment,
    committedAmt: item.CommittedAmt,
    dateContract: item.DateContract,
    dateFinish: item.DateFinish,
    processed: item.Processed,
    plannedAmt: item.PlannedAmt,
    plannedQty: item.PlannedQty,
    plannedMarginAmt: item.PlannedMarginAmt,
    invoicedAmt: item.InvoicedAmt,
    invoicedQty: item.InvoicedQty,
    projectBalanceAmt: item.ProjectBalanceAmt,
    committedQty: item.CommittedQty,
    isCommitCeiling: item.IsCommitCeiling,
    currency: item.C_Currency_ID?.identifier || '',
    currencyId: item.C_Currency_ID?.id || '',
    partner: item.C_BPartner_ID?.identifier || '',
    partnerId: item.C_BPartner_ID?.id || '',
    partnerLocation: item.C_BPartner_Location_ID?.identifier || '',
    partnerLocationId: item.C_BPartner_Location_ID?.id || '',
    salesRep: item.SalesRep_ID?.identifier || '',
    salesRepId: item.SalesRep_ID?.id || '',
    priceListVersion: item.M_PriceList_Version_ID?.identifier || '',
    priceListVersionId: item.M_PriceList_Version_ID?.id || '',
    campaign: item.C_Campaign_ID?.identifier || '',
    campaignId: item.C_Campaign_ID?.id || '',
    user: item.AD_User_ID?.identifier || '',
    userId: item.AD_User_ID?.id || '',
    warehouse: item.M_Warehouse_ID?.identifier || '',
    warehouseId: item.M_Warehouse_ID?.id || '',
    projectCategory: item.ProjectCategory?.identifier || '',
    projectCategoryId: item.ProjectCategory?.id || '',
    projInvoiceRule: item.ProjInvoiceRule?.identifier || '',
    projInvoiceRuleId: item.ProjInvoiceRule?.id || '',
    projectLineLevel: item.ProjectLineLevel?.identifier || '',
    projectLineLevelId: item.ProjectLineLevel?.id || '',
    partnerSR: item.C_BPartnerSR_ID?.identifier || '',
    partnerSRId: item.C_BPartnerSR_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: 'description',
    headerName: 'Description'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'isSummary',
    headerName: 'Summary'
  },
  { 
    field: 'note'
  },
  { 
    headerName: 'Action',
    minWidth: 80,
    type: 'nonEditableColumn',
    cellRenderer: ProjectAction
  }
]);

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/projects/projects/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,
      note: event.data.note,
      isSummary: event.data.isSummary,
      isCommitment: event.data.isCommitment,
      committedAmt: event.data.committedAmt,
      dateContract: event.data.dateContract,
      dateFinish: event.data.dateFinish,
      processed: event.data.processed,
      plannedAmt: event.data.plannedAmt,
      plannedQty: event.data.plannedQty,
      plannedMarginAmt: event.data.plannedMarginAmt,
      invoicedAmt: event.data.invoicedAmt,
      invoicedQty: event.data.invoicedQty,
      projectBalanceAmt: event.data.projectBalanceAmt,
      committedQty: event.data.committedQty,
      isCommitCeiling: event.data.isCommitCeiling,
    }
  })

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

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

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

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

    const res = await $fetch('/api/projects/projects/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>Projects</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>