<script>
import CustomerRmaAction from '../../../components/rmas/CustomerRmaAction.vue'

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

const rowData = computed(() => data.value?.records?.filter(i => i.IsSOTrx === true)?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    isActive: item.IsActive,
    documentNo: item.DocumentNo,
    description: item.Description,
    isApproved: item.IsApproved,
    name: item.Name,
    processing: item.Processing,
    isSOTrx: item.IsSOTrx,
    processed: item.Processed,
    amt: item.Amt,
    help: item.Help,
    inOut: item.InOut_ID?.identifier || '',
    inOutId: item.InOut_ID?.id || '',
    order: item.C_Order_ID?.identifier || '',
    orderId: item.C_Order_ID?.id || '',
    docType: item.C_DocType_ID?.identifier || '',
    docTypeId: item.C_DocType_ID?.id || '',
    docStatus: item.DocStatus?.identifier || '',
    docStatusId: item.DocStatus?.id || '',
    salesRep: item.SalesRep_ID?.identifier || '',
    salesRepId: item.SalesRep_ID?.id || '',
    rmaType: item.M_RMAType_ID?.identifier || '',
    rmaTypeId: item.M_RMAType_ID?.id || '',
    currency: item.C_Currency_ID?.identifier || '',
    currencyId: item.C_Currency_ID?.id || '',
    partner: item.C_BPartner_ID?.identifier || '',
    partnerId: item.C_BPartner_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: 'documentNo',
    headerName: 'Document Number',
    type: 'nonEditableColumn',
  },
  { 
    field: 'organization',
    type: 'nonEditableColumn',
    minWidth: 150
  },
  { 
    field: 'name',
    minWidth: 150
  },
  { 
    field: 'isActive',
    headerName: 'Action',
    minWidth: 50
  },
  { 
    field: 'isApproved',
    headerName: 'Approved',
    minWidth: 70
  },
  { 
    field: 'isSOTrx',
    headerName: 'Sales',
    minWidth: 50
  },
  { 
    field: 'amt'
  },
  { 
    headerName: 'Action',
    minWidth: 80,
    type: 'nonEditableColumn',
    cellRenderer: CustomerRmaAction
  },
]);

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) => {
  if(event.data.docStatusId === 'CO') {
    alert.value.status = 500
    alert.value.message = 'Sorry, this document is in a completed status, so you cannot update it!'
    window.scrollTo(0, 0)
  } else {
    const res = await $fetch('/api/rma/update', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: event.data.id,
        isActive: event.data.isActive,
        documentNo: event.data.documentNo,
        description: event.data.description,
        isApproved: event.data.isApproved,
        processing: event.data.processing,
        name: event.data.name,
        isSOTrx: event.data.isSOTrx,
        processed: event.data.processed,
        amt: event.data.amt,
        help: event.data.help,
      }
    })

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

const breadCrumb = computed(() => ([
  { link: '#', text: 'Sales'},
  { link: '/sales/customer-rma', text: 'Customer RMA', active: true}
]))

const create = () => {
  router.push('/sales/customer-rma/add')
}

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

    const res = await $fetch('/api/rma/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>Customer RMA</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>
    
    <Teleport to="body">
      <PrintPreview modelName="rma" />
    </Teleport>
  </NuxtLayout>
</template>