<script>
import PaymentAction from '../../../components/procurements/PaymentAction.vue'

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

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    isActive: item.IsActive,
    documentNo: item.DocumentNo,
    description: item.Description,
    isApproved: item.IsApproved,
    processed: item.Processed,
    creditCardExpMM: item.CreditCardExpMM,
    creditCardExpYY: item.CreditCardExpYY,
    isReconciled: item.IsReconciled,
    taxAmt: item.TaxAmt,
    discountAmt: item.DiscountAmt,
    payAmt: item.PayAmt,
    dateTrx: item.DateTrx,
    isAllocated: item.IsAllocated,
    isOnline: item.IsOnline,
    isReceipt: item.IsReceipt,
    writeOffAmt: item.WriteOffAmt,
    overUnderAmt: item.OverUnderAmt,
    isOverUnderPayment: item.IsOverUnderPayment,
    isSelfService: item.IsSelfService,
    isDelayedCapture: item.IsDelayedCapture,
    chargeAmt: item.ChargeAmt,
    R_CVV2Match: item.R_CVV2Match,
    dateAcct: item.DateAcct,
    isPrepayment: item.IsPrepayment,
    processedOn: item.ProcessedOn,
    isVoided: item.IsVoided,
    isOverrideCurrencyRate: item.IsOverrideCurrencyRate,
    routingNo: item.RoutingNo,
    accountNo: item.AccountNo,
    A_Zip: item.A_Zip,
    A_Ident_DL: item.A_Ident_DL,
    A_Ident_SSN: item.A_Ident_SSN,
    A_EMail: item.A_EMail,
    voiceAuthCode: item.VoiceAuthCode,
    orig_TrxID: item.Orig_TrxID,
    micr: item.Micr,
    checkNo: item.CheckNo,
    A_Name: item.A_Name,
    A_Street: item.A_Street,
    A_City: item.A_City,
    A_State: item.A_State,
    A_Country: item.A_Country,
    swiftCode: item.SwiftCode,
    creditCardType: item.CreditCardType?.identifier || '',
    creditCardTypeId: item.CreditCardType?.id || '',
    bankAccount: item.C_BankAccount_ID?.identifier || '',
    bankAccountId: item.C_BankAccount_ID?.id || '',
    trxType: item.TrxType?.identifier || '',
    trxTypeId: item.TrxType?.id || '',
    tenderType: item.TenderType?.identifier || '',
    tenderTypeId: item.TenderType?.id || '',
    currency: item.C_Currency_ID?.identifier || '',
    currencyId: item.C_Currency_ID?.id || '',
    docType: item.C_DocType_ID?.identifier || '',
    docTypeId: item.C_DocType_ID?.id || '',
    order: item.C_Order_ID?.identifier || '',
    orderId: item.C_Order_ID?.id || '',
    invoice: item.C_Payment_ID?.identifier || '',
    invoiceId: item.C_Payment_ID?.id || '',
    docStatus: item.DocStatus?.identifier || '',
    docStatusId: item.DocStatus?.id || '',
    partner: item.C_BPartner_ID?.identifier || '',
    partnerId: item.C_BPartner_ID?.id || '',
    charge: item.C_Charge_ID?.identifier || '',
    chargeId: item.C_Charge_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: 'Document Number'
  },
  { 
    field: 'payAmt',
    headerName: 'Pay Amount'
  },
  { 
    field: 'dateTrx',
    headerName: 'Date Trx'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'isApproved',
    headerName: 'Approved'
  },
  { 
    field: 'isAllocated',
    headerName: 'Allocated'
  },
  { 
    field: 'isReceipt',
    headerName: 'Receipt'
  },
  {
    headerName: 'Action',
    width: 100,
    pinned: 'right',
    cellRenderer: PaymentAction
  }
]);

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/payments/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,
      creditCardExpMM: event.data.creditCardExpMM,
      creditCardExpYY: event.data.creditCardExpYY,
      isReconciled: event.data.isReconciled,
      taxAmt: event.data.taxAmt,
      discountAmt: event.data.discountAmt,
      payAmt: event.data.payAmt,
      dateTrx: event.data.dateTrx,
      isAllocated: event.data.isAllocated,
      isOnline: event.data.isOnline,
      isReceipt: event.data.isReceipt,
      writeOffAmt: event.data.writeOffAmt,
      overUnderAmt: event.data.overUnderAmt,
      isOverUnderPayment: event.data.isOverUnderPayment,
      isSelfService: event.data.isSelfService,
      isDelayedCapture: event.data.isDelayedCapture,
      chargeAmt: event.data.chargeAmt,
      R_CVV2Match: event.data.R_CVV2Match,
      dateAcct: event.data.dateAcct,
      isPrepayment: event.data.isPrepayment,
      processedOn: event.data.processedOn,
      isVoided: event.data.isVoided,
      isOverrideCurrencyRate: event.data.isOverrideCurrencyRate,
      routingNo: event.data.routingNo,
      accountNo: event.data.accountNo,
      A_Zip: event.data.A_Zip,
      A_Ident_DL: event.data.A_Ident_DL,
      A_Ident_SSN: event.data.A_Ident_SSN,
      A_EMail: event.data.A_EMail,
      voiceAuthCode: event.data.voiceAuthCode,
      Orig_TrxID: event.data.orig_TrxID,
      micr: event.data.micr,
      checkNo: event.data.checkNo,
      A_Name: event.data.A_Name,
      A_Street: event.data.A_Street,
      A_City: event.data.A_City,
      A_State: event.data.A_State,
      A_Country: event.data.A_Country,
      swiftCode: event.data.swiftCode,
    }
  })

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

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

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

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

    const res = await $fetch('/api/payments/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>Payments</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="payments" />
      <ProcurementsPaymentQuickView />
    </Teleport>
  </NuxtLayout>
</template>