<script>
import StockTransferAction from '../../../components/materials/StockTransferAction.vue'

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

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    documentNo: item.DocumentNo,
    movementDate: item.MovementDate,
    approvalAmt: item.ApprovalAmt,
    chargeAmt: item.ChargeAmt,
    freightAmt: item.FreightAmt,
    description: item.Description,
    poReference: item.POReference,
    isActive: item.IsActive,
    isApproved: item.IsApproved,
    isInTransit: item.IsInTransit,
    processed: item.Processed,
    processing: item.Processing,
    warehouse: item.M_Warehouse_ID?.identifier || '',
    warehouseId: item.M_Warehouse_ID?.id || '',
    warehouseTo: item.M_WarehouseTo_ID?.identifier || '',
    warehouseToId: item.M_WarehouseTo_ID?.id || '',
    docType: item.C_DocType_ID?.identifier || '',
    docTypeId: item.C_DocType_ID?.id || '',
    shipper: item.M_Shipper_ID?.identifier || '',
    shipperId: item.M_Shipper_ID?.id || '',
    salesRep: item.SalesRep_ID?.identifier || '',
    salesRepId: item.SalesRep_ID?.id || '',
    user: item.AD_User_ID?.identifier || '',
    userId: item.AD_User_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 || '',
    freightCostRule: item.FreightCostRule?.identifier || '',
    freightCostRuleId: item.FreightCostRule?.id || '',
    priorityRule: item.PriorityRule?.identifier || '',
    priorityRuleId: item.PriorityRule?.id || '',
    deliveryRule: item.DeliveryRule?.identifier || '',
    deliveryRuleId: item.DeliveryRule?.id || '',
    deliveryViaRule: item.DeliveryViaRule?.identifier || '',
    deliveryViaRuleId: item.DeliveryViaRule?.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 || '',
    docStatus: item.DocStatus?.identifier || '',
    docStatusId: item.DocStatus?.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: 'Document No'
  },
  { 
    field: 'movementDate',
    headerName: 'Movement Date'
  },
  { 
    field: 'approvalAmt',
    headerName: 'Approval Amount'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'isApproved',
    headerName: 'Approved'
  },
  {
    headerName: 'Action',
    width: 100,
    pinned: 'right',
    cellRenderer: StockTransferAction
  }
]);

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/materials/stock-transfers/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      documentNo: event.data.documentNo,
      movementDate: event.data.movementDate,
      approvalAmt: event.data.approvalAmt,
      chargeAmt: event.data.chargeAmt,
      freightAmt: event.data.freightAmt,
      description: event.data.description,
      poReference: event.data.poReference,
      isActive: event.data.isActive,
      isApproved: event.data.isApproved,
      isInTransit: event.data.isInTransit,
      processed: event.data.processed,
      processing: event.data.processing,
    }
  })

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

const breadCrumb = computed(() => ([
  { link: '#', text: 'Materials'},
  { link: '/materials/stock-transfers', text: 'Stock Transfers', active: true}
]))

const create = () => {
  //router.push('/materials/stock-transfers/create')
  router.push('/materials/stock-transfers/add')
}

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

    const res = await $fetch('/api/materials/stock-transfers/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>Stock Transfers</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="materials/stock-transfers" />
      <MaterialsStockTransferQuickView />
    </Teleport>
  </NuxtLayout>
</template>