<script>
import ReceiptAction from '../../../components/procurements/ReturnAction.vue'

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

const rowData = computed(() => data.value?.records?.filter(i => i.MovementType.id === 'V-')?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    isActive: item.IsActive,
    documentNo: item.DocumentNo,
    description: item.Description,
    isApproved: item.IsApproved,
    processed: item.Processed,
    isSOTrx: item.IsSOTrx,
    isPrinted: item.IsPrinted,
    dateAcct: item.DateAcct,
    poReference: item.POReference,
    freightAmt: item.FreightAmt,
    chargeAmt: item.ChargeAmt,
    dateOrdered: item.DateOrdered,
    sendEMail: item.SendEMail,
    noPackages: item.NoPackages,
    isInTransit: item.IsInTransit,
    isInDispute: item.IsInDispute,
    volume: item.Volume,
    weight: item.Weight,
    isDropShip: item.IsDropShip,
    processedOn: item.ProcessedOn,
    isAlternateReturnAddress: item.IsAlternateReturnAddress,
    movementType: item.MovementType?.identifier || '',
    movementTypeId: item.MovementType?.id || '',
    docType: item.C_DocType_ID?.identifier || '',
    docTypeId: item.C_DocType_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 || '',
    user: item.AD_User_ID?.identifier || '',
    userId: item.AD_User_ID?.id || '',
    warehouse: item.M_Warehouse_ID?.identifier || '',
    warehouseId: item.M_Warehouse_ID?.id || '',
    deliveryRule: item.DeliveryRule?.identifier || '',
    deliveryRuleId: item.DeliveryRule?.id || '',
    freightCostRule: item.FreightCostRule?.identifier || '',
    freightCostRuleId: item.FreightCostRule?.id || '',
    deliveryViaRule: item.DeliveryViaRule?.identifier || '',
    deliveryViaRuleId: item.DeliveryViaRule?.id || '',
    priorityRule: item.PriorityRule?.identifier || '',
    priorityRuleId: item.PriorityRule?.id || '',
    order: item.C_Order_ID?.identifier || '',
    orderId: item.C_Order_ID?.id || '',
    docStatus: item.DocStatus?.identifier || '',
    docStatusId: item.DocStatus?.id || '',
    salesRep: item.SalesRep_ID?.identifier || '',
    salesRepId: item.SalesRep_ID?.id || '',
    project: item.C_Project_ID?.identifier || '',
    projectId: item.C_Project_ID?.id || '',
    campaign: item.C_Campaign_ID?.identifier || '',
    campaignId: item.C_Campaign_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: 'documentNo',
    headerName: 'Doc Number'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'dateAcct',
    headerName: 'Date Accounted'
  },
  { 
    field: 'dateOrdered',
    headerName: 'Date Ordered'
  },
  { 
    field: 'docType',
    headerName: 'Doc Type',
    type: 'nonEditableColumn'
  },
  { 
    field: 'docStatus',
    headerName: 'Order',
    type: 'nonEditableColumn'
  },
  { 
    field: 'partner',
    headerName: 'Partner',
    type: 'nonEditableColumn'
  },
  {
    headerName: 'Action',
    width: 100,
    pinned: 'right',
    cellRenderer: ReceiptAction
  }
]);

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/inouts/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,
      processed: event.data.processed,
      isSOTrx: event.data.isSOTrx,
      isPrinted: event.data.isPrinted,
      dateAcct: event.data.dateAcct,
      poReference: event.data.poReference,
      freightAmt: event.data.freightAmt,
      chargeAmt: event.data.chargeAmt,
      dateOrdered: event.data.dateOrdered,
      sendEMail: event.data.sendEMail,
      noPackages: event.data.noPackages,
      isInTransit: event.data.isInTransit,
      isInDispute: event.data.isInDispute,
      volume: event.data.volume,
      weight: event.data.weight,
      isDropShip: event.data.isDropShip,
      processedOn: event.data.processedOn,
      isAlternateReturnAddress: event.data.isAlternateReturnAddress
    }
  })

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

const breadCrumb = computed(() => ([
  { link: '#', text: 'Procurements'},
  { link: '/procurements/returns', text: 'Vendor Returns', active: true}
]))

const create = () => {
  //router.push('/procurements/returns/create')
  router.push('/procurements/returns/add')
}

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

    const res = await $fetch('/api/inouts/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>Vendor Returns</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="col-12 mb-3">
              <AgGrid :entries="rowData" :columns="colDefs" @cellClick="cellClick" @cellChange="cellChange" />
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <Teleport to="body">
      <PrintPreview modelName="inouts" />
      <ProcurementsReceiptQuickView />
    </Teleport>
  </NuxtLayout>
</template>