<script>
import RequestAction from '../../../components/requests/RequestAction.vue'

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

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    isActive: item.IsActive,
    documentNo: item.DocumentNo,
    requestAmt: item.RequestAmt,
    dueType: item.DueType,
    summary: item.Summary,
    isEscalated: item.IsEscalated,
    isEMailWhenDue: item.IsEMailWhenDue,
    dateLastAction: item.DateLastAction,
    processed: item.Processed,
    isSelfService: item.IsSelfService,
    isInvoiced: item.IsInvoiced,
    qtySpent: item.QtySpent,
    qtyInvoiced: item.QtyInvoiced,
    priority: item.Priority?.identifier || '',
    priorityId: item.Priority?.id || '',
    dueType: item.DueType?.identifier || '',
    dueTypeId: item.DueType?.id || '',
    salesRep: item.SalesRep_ID?.identifier || '',
    salesRepId: item.SalesRep_ID?.id || '',
    partner: item.C_BPartner_ID?.identifier || '',
    partnerId: item.C_BPartner_ID?.id || '',
    user: item.AD_User_ID?.identifier || '',
    userId: item.AD_User_ID?.id || '',
    nextAction: item.NextAction?.identifier || '',
    nextActionId: item.NextAction?.id || '',
    requestType: item.R_RequestType_ID?.identifier || '',
    requestTypeId: item.R_RequestType_ID?.id || '',
    group: item.R_Group_ID?.identifier || '',
    groupId: item.R_Group_ID?.id || '',
    category: item.R_Category_ID?.identifier || '',
    categoryId: item.R_Category_ID?.id || '',
    status: item.R_Status_ID?.identifier || '',
    statusId: item.R_Status_ID?.id || '',
    priorityUser: item.PriorityUser?.identifier || '',
    priorityUserId: item.PriorityUser?.id || '',
    confidentialType: item.ConfidentialType?.identifier || '',
    confidentialTypeId: item.ConfidentialType?.id || '',
    confidentialTypeEntry: item.ConfidentialTypeEntry?.identifier || '',
    confidentialTypeEntryId: item.ConfidentialTypeEntry?.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: 'documentNo',
    headerName: 'Document Number'
  },
  { 
    field: 'organization',
    type: 'nonEditableColumn' 
  },
  {
    field: 'partner',
    headerName: 'Customer'
  },
  // {
  //   field: 'isActive',
  //   headerName: 'Active'
  // },
  // {
  //   field: 'requestAmt',
  //   headerName: 'Request Amount'
  // },
  // {
  //   field: 'dueType',
  //   headerName: 'Due Type'
  // },
  {
    field: 'requestType',
    headerName: 'Type'
  },

  {
    field: 'category',
    headerName: 'Category'
  },
  { 
    field: 'summary',
    headerName: 'Summary',
    maxWidth: 400,
  },
  { 
    headerName: 'Action',
    minWidth: 80,
    type: 'nonEditableColumn',
    cellRenderer: RequestAction
  },
]);

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/requests/requests/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      isActive: event.data.isActive,
      documentNo: event.data.documentNo,
      requestAmt: event.data.requestAmt,
      dueType: event.data.dueType,
      summary: event.data.summary,
      isEscalated: event.data.isEscalated,
      isEMailWhenDue: event.data.isEMailWhenDue,
      dateLastAction: event.data.dateLastAction,
      processed: event.data.processed,
      isSelfService: event.data.isSelfService,
      isInvoiced: event.data.isInvoiced,
      qtySpent: event.data.qtySpent,
      qtyInvoiced: event.data.qtyInvoiced,
    }
  })

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

const breadCrumb = computed(() => ([
  { link: '/', text: 'Home'},
  { link: '/requests/requests', text: 'Requests', active: true}
]))

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

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

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