<script setup>
import { date } from 'alga-js'
import { toast } from 'bulma-toast'

const router = useRouter()
const route = useRoute()
const activeSave = useActiveSave()

definePageMeta({
  middleware: ['auth', 'org']
})

const lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  isActive: true,
  documentNo: '',
  description: '',
  isApproved: false,
  processed: false,
  creditCardNumber: 0,
  creditCardExpMM: Number(new Date().getMonth()) + 1,
  creditCardExpYY: new Date().getFullYear(),
  creditCardVV: '',
  isReconciled: false,
  taxAmt: 0,
  discountAmt: 0,
  payAmt: 0,
  dateTrx: date.now('date'),
  isAllocated: false,
  isOnline: false,
  isReceipt: true,
  writeOffAmt: 0,
  overUnderAmt: 0,
  isOverUnderPayment: false,
  isSelfService: false,
  isDelayedCapture: false,
  chargeAmt: 0,
  R_CVV2Match: 0,
  dateAcct: date.now('date'),
  isPrepayment: false,
  processedOn: 0,
  isVoided: false,
  isOverrideCurrencyRate: false,
  routingNo: '',
  accountNo: '',
  A_Zip: '',
  A_Ident_DL: '',
  A_Ident_SSN: '',
  A_EMail: '',
  voiceAuthCode: '',
  orig_TrxID: '',
  micr: '',
  checkNo: '',
  A_Name: '',
  A_Street: '',
  A_City: '',
  A_State: '',
  A_Country: '',
  swiftCode: '',
  creditCardType: '',
  creditCardTypeId: '',
  bankAccount: '',
  bankAccountId: '',
  trxType: '',
  trxTypeId: '',
  tenderType: '',
  tenderTypeId: '',
  currency: '',
  currencyId: '',
  docType: '',
  docTypeId: '',
  order: '',
  orderId: '',
  invoice: '',
  invoiceId: '',
  docStatus: 'Draft',
  docStatusId: 'DR',
  partner: '',
  partnerId: '',
  charge: '',
  chargeId: '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/payments/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: route.params.id,
      uid: res?.uid || '',
      client: res?.AD_Client_ID?.identifier || '',
      clientId: res?.AD_Client_ID?.id || '',
      organization: res?.AD_Org_ID?.identifier || '',
      organizationId: res?.AD_Org_ID?.id || '',
      isActive: res?.IsActive ?? true,
      documentNo: res?.DocumentNo || '',
      description: res?.Description || '',
      isApproved: res?.IsApproved ?? false,
      processed: res?.Processed ?? false,
      creditCardNumber: res?.CreditCardNumber || 0,
      creditCardExpMM: res?.CreditCardExpMM || Number(new Date().getMonth()) + 1,
      creditCardExpYY: res?.CreditCardExpYY || new Date().getFullYear(),
      creditCardVV: res?.CreditCardVV || '',
      isReconciled: res?.IsReconciled ?? false,
      taxAmt: res?.TaxAmt || 0,
      discountAmt: res?.DiscountAmt || 0,
      payAmt: res?.PayAmt || 0,
      dateTrx: res?.DateTrx || date.now('date'),
      isAllocated: res?.IsAllocated ?? false,
      isOnline: res?.IsOnline ?? false,
      isReceipt: res?.IsReceipt ?? true,
      writeOffAmt: res?.WriteOffAmt || 0,
      overUnderAmt: res?.OverUnderAmt || 0,
      isOverUnderPayment: res?.IsOverUnderPayment ?? false,
      isSelfService: res?.IsSelfService ?? false,
      isDelayedCapture: res?.IsDelayedCapture ?? false,
      chargeAmt: res?.ChargeAmt || 0,
      R_CVV2Match: res?.R_CVV2Match || 0,
      dateAcct: res?.DateAcct || date.now('date'),
      isPrepayment: res?.IsPrepayment ?? false,
      processedOn: res?.ProcessedOn || 0,
      isVoided: res?.IsVoided ?? false,
      isOverrideCurrencyRate: res?.IsOverrideCurrencyRate ?? false,
      routingNo: res?.RoutingNo || '',
      accountNo: res?.AccountNo || '',
      A_Zip: res?.A_Zip || '',
      A_Ident_DL: res?.A_Ident_DL || '',
      A_Ident_SSN: res?.A_Ident_SSN || '',
      A_EMail: res?.A_EMail || '',
      voiceAuthCode: res?.VoiceAuthCode || '',
      orig_TrxID: res?.Orig_TrxID || '',
      micr: res?.Micr || '',
      checkNo: res?.CheckNo || '',
      A_Name: res?.A_Name || '',
      A_Street: res?.A_Street || '',
      A_City: res?.A_City || '',
      A_State: res?.A_State || '',
      A_Country: res?.A_Country || '',
      swiftCode: res?.SwiftCode || '',
      creditCardType: res?.CreditCardType?.identifier || '',
      creditCardTypeId: res?.CreditCardType?.id || '',
      bankAccount: res?.C_BankAccount_ID?.identifier || '',
      bankAccountId: res?.C_BankAccount_ID?.id || '',
      trxType: res?.TrxType?.identifier || '',
      trxTypeId: res?.TrxType?.id || '',
      tenderType: res?.TenderType?.identifier || '',
      tenderTypeId: res?.TenderType?.id || '',
      currency: res?.C_Currency_ID?.identifier || '',
      currencyId: res?.C_Currency_ID?.id || '',
      docType: res?.C_DocType_ID?.identifier || 'AR Receipt',
      docTypeId: res?.C_DocType_ID?.id || '119',
      order: res?.C_Order_ID?.identifier || '',
      orderId: res?.C_Order_ID?.id || '',
      invoice: res?.C_Invoice_ID?.identifier || '',
      invoiceId: res?.C_Invoice_ID?.id || '',
      docStatus: res?.DocStatus?.identifier || 'Draft',
      docStatusId: res?.DocStatus?.id || 'DR',
      partner: res?.C_BPartner_ID?.identifier || '',
      partnerId: res?.C_BPartner_ID?.id || '',
      charge: res?.C_Charge_ID?.identifier || '',
      chargeId: res?.C_Charge_ID?.id || '',
      project: res?.C_Project_ID?.identifier || '',
      projectId: res?.C_Project_ID?.id || '',
      campaign: res?.C_Campaign_ID?.identifier || '',
      campaignId: res?.C_Campaign_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false
  }
}
onMounted(retrieve)

const noEdit = ref(true)
const setNoEdit = () => {
  noEdit.value = (
    form.value.organizationId == (lastRecord.value?.AD_Org_ID?.id || '') &&
    form.value.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.documentNo == (lastRecord.value?.DocumentNo || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.isApproved == (lastRecord.value?.IsApproved ?? false) &&
    form.value.processed == (lastRecord.value?.Processed ?? false) &&
    form.value.creditCardNumber == (lastRecord.value?.CreditCardNumber || 0) &&
    form.value.creditCardExpMM == (lastRecord.value?.CreditCardExpMM || Number(new Date().getMonth()) + 1) &&
    form.value.creditCardExpYY == (lastRecord.value?.CreditCardExpYY || new Date().getFullYear()) &&
    form.value.creditCardVV == (lastRecord.value?.CreditCardVV || '') &&
    form.value.isReconciled == (lastRecord.value?.IsReconciled ?? false) &&
    form.value.taxAmt == (lastRecord.value?.TaxAmt || 0) &&
    form.value.discountAmt == (lastRecord.value?.DiscountAmt || 0) &&
    form.value.payAmt == (lastRecord.value?.PayAmt || 0) &&
    form.value.dateTrx == (lastRecord.value?.DateTrx || date.now('date')) &&
    form.value.isAllocated == (lastRecord.value?.IsAllocated ?? false) &&
    form.value.isOnline == (lastRecord.value?.IsOnline ?? false) &&
    form.value.isReceipt == (lastRecord.value?.IsReceipt ?? false) &&
    form.value.writeOffAmt == (lastRecord.value?.WriteOffAmt || 0) &&
    form.value.overUnderAmt == (lastRecord.value?.OverUnderAmt || 0) &&
    form.value.isOverUnderPayment == (lastRecord.value?.IsOverUnderPayment ?? false) &&
    form.value.isSelfService == (lastRecord.value?.IsSelfService ?? false) &&
    form.value.isDelayedCapture == (lastRecord.value?.IsDelayedCapture ?? false) &&
    form.value.chargeAmt == (lastRecord.value?.ChargeAmt || 0) &&
    form.value.R_CVV2Match == (lastRecord.value?.R_CVV2Match || 0) &&
    form.value.dateAcct == (lastRecord.value?.DateAcct || date.now('date')) &&
    form.value.isPrepayment == (lastRecord.value?.IsPrepayment ?? false) &&
    form.value.processedOn == (lastRecord.value?.ProcessedOn || 0) &&
    form.value.isVoided == (lastRecord.value?.IsVoided ?? false) &&
    form.value.isOverrideCurrencyRate == (lastRecord.value?.IsOverrideCurrencyRate ?? false) &&
    form.value.routingNo == (lastRecord.value?.RoutingNo || '') &&
    form.value.accountNo == (lastRecord.value?.AccountNo || '') &&
    form.value.A_Zip == (lastRecord.value?.A_Zip || '') &&
    form.value.A_Ident_DL == (lastRecord.value?.A_Ident_DL || '') &&
    form.value.A_Ident_SSN == (lastRecord.value?.A_Ident_SSN || '') &&
    form.value.A_EMail == (lastRecord.value?.A_EMail || '') &&
    form.value.voiceAuthCode == (lastRecord.value?.VoiceAuthCode || '') &&
    form.value.orig_TrxID == (lastRecord.value?.Orig_TrxID || '') &&
    form.value.micr == (lastRecord.value?.Micr || '') &&
    form.value.checkNo == (lastRecord.value?.CheckNo || '') &&
    form.value.A_Name == (lastRecord.value?.A_Name || '') &&
    form.value.A_Street == (lastRecord.value?.A_Street || '') &&
    form.value.A_City == (lastRecord.value?.A_City || '') &&
    form.value.A_State == (lastRecord.value?.A_State || '') &&
    form.value.A_Country == (lastRecord.value?.A_Country || '') &&
    form.value.swiftCode == (lastRecord.value?.SwiftCode || '') &&
    form.value.creditCardTypeId == (lastRecord.value?.CreditCardType?.id || '') &&
    form.value.bankAccountId == (lastRecord.value?.C_BankAccount_ID?.id || '') &&
    form.value.trxTypeId == (lastRecord.value?.TrxType?.id || '') &&
    form.value.tenderTypeId == (lastRecord.value?.TenderType?.id || '') &&
    form.value.currencyId == (lastRecord.value?.C_Currency_ID?.id || '') &&
    form.value.docTypeId == (lastRecord.value?.C_DocType_ID?.id || '119') &&
    form.value.orderId == (lastRecord.value?.C_Order_ID?.id || '') &&
    form.value.invoiceId == (lastRecord.value?.C_Invoice_ID?.id || '') &&
    form.value.docStatusId == (lastRecord.value?.DocStatus?.id || 'DR') &&
    form.value.partnerId == (lastRecord.value?.C_BPartner_ID?.id || '') &&
    form.value.chargeId == (lastRecord.value?.C_Charge_ID?.id || '') &&
    form.value.projectId == (lastRecord.value?.C_Project_ID?.id || '') &&
    form.value.campaignId == (lastRecord.value?.C_Campaign_ID?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/procurements/payments/${route.params.id}/duplicate`)
}

const back = () => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    router.push('/procurements/payments')
  }
}

const save = async (record) => {
  form.value = record
  setNoEdit()
  if(!noEdit.value) {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

const submit = async (saveType = '') => {
  form.value.alert.processing = true
  activeSave.value = true

  const res = await $fetch('/api/payments/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      documentNo: form.value.documentNo,
      description: form.value.description,
      isApproved: form.value.isApproved,
      processed: form.value.processed,
      creditCardNumber: form.value.creditCardNumber,
      creditCardExpMM: form.value.creditCardExpMM,
      creditCardExpYY: form.value.creditCardExpYY,
      isReconciled: form.value.isReconciled,
      taxAmt: form.value.taxAmt,
      discountAmt: form.value.discountAmt,
      payAmt: form.value.payAmt,
      dateTrx: form.value.dateTrx,
      isAllocated: form.value.isAllocated,
      isOnline: form.value.isOnline,
      isReceipt: form.value.isReceipt,
      writeOffAmt: form.value.writeOffAmt,
      overUnderAmt: form.value.overUnderAmt,
      isOverUnderPayment: form.value.isOverUnderPayment,
      isSelfService: form.value.isSelfService,
      isDelayedCapture: form.value.isDelayedCapture,
      chargeAmt: form.value.chargeAmt,
      R_CVV2Match: form.value.R_CVV2Match,
      dateAcct: form.value.dateAcct,
      isPrepayment: form.value.isPrepayment,
      processedOn: form.value.processedOn,
      isVoided: form.value.isVoided,
      isOverrideCurrencyRate: form.value.isOverrideCurrencyRate,
      routingNo: form.value.routingNo,
      accountNo: form.value.accountNo,
      A_Zip: form.value.A_Zip,
      A_Ident_DL: form.value.A_Ident_DL,
      A_Ident_SSN: form.value.A_Ident_SSN,
      A_EMail: form.value.A_EMail,
      voiceAuthCode: form.value.voiceAuthCode,
      orig_TrxID: form.value.orig_TrxID,
      micr: form.value.micr,
      checkNo: form.value.checkNo,
      A_Name: form.value.A_Name,
      A_Street: form.value.A_Street,
      A_City: form.value.A_City,
      A_State: form.value.A_State,
      A_Country: form.value.A_Country,
      swiftCode: form.value.swiftCode,
      creditCardTypeId: form.value.creditCardTypeId,
      bankAccountId: form.value.bankAccountId,
      trxTypeId: form.value.trxTypeId,
      tenderTypeId: form.value.tenderTypeId,
      currencyId: form.value.currencyId,
      docTypeId: form.value.docTypeId,
      orderId: form.value.orderId,
      invoiceId: form.value.invoiceId,
      docStatusId: form.value.docStatusId,
      partnerId: form.value.partnerId,
      chargeId: form.value.chargeId,
      projectId: form.value.projectId,
      campaignId: form.value.campaignId,
    }
  })

  if(Number(res.status) === 200) {
    form.value.alert.processing = false
    activeSave.value = false
    
    if(saveType === 'preview') {
      router.push('/procurements/payments/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
      retrieve()
    } else {
      back()
    }
  } else {
    //form.value.alert.status = res.status
    //form.value.alert.message = res.message
    form.value.alert.processing = false
    activeSave.value = false
    toast({
      message: res.message || 'Save error',
      type: 'is-danger',
      duration: 2000
    })
    //window.scrollTo(0, 0)
  }
}

const showAttachment = ref(false)

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

const tab = ref(route.query?.tab || 'payment')
const tabs = computed(() => ([
  { value: 'payment', text: 'Payment'},
  { value: 'reference', text: 'Allocate & Reference'},
  { value: 'amounts', text: 'Amounts'},
  { value: 'document', text: 'Document'},
  { value: 'status', text: 'Status'}
]))

const openOtherTab = () => {
  if(tab.value === 'payment') {
    tab.value = 'reference'
  } else if(tab.value === 'reference') {
    tab.value = 'amounts'
  } else if(tab.value === 'amounts') {
    tab.value = 'document'
  } else if(tab.value === 'document') {
    tab.value = 'status'
  }
}

const setDocumentAction = async (docAction) => {
  const res = await $fetch('/api/payments/'+route.params.id+'/document-action', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      documentAction: docAction
    }
  })
  if(res) {
    toast({
      message: 'Document has been successfully set to '+docAction+' status.',
      type: 'is-success',
      duration: 2000
    })
    back()
  } else {
    toast({
      message: 'Document failed to set to '+docAction+' status.',
      type: 'is-danger',
      duration: 2000
    })
  }
}
</script>

<template>
  <Head>
    <Title>Edit Payment</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    
    <div class="bannercontrol">
      <div class="d-flex gap-10px">
        <button type="button" @click="submit('onlysave')" class="button" :class="(form.bankAccountId === '' || form.docTypeId === '' || form.dateTrx === '' || form.dateAcct === '' || form.payAmt === '' || form.tenderTypeId === '' || form.currencyId === '' || form.partnerId === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
        <template v-if="form.id !== ''">
          <button type="button" @click="submit" class="button" :class="(form.bankAccountId === '' || form.docTypeId === '' || form.dateTrx === '' || form.dateAcct === '' || form.payAmt === '' || form.tenderTypeId === '' || form.currencyId === '' || form.partnerId === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Attachment</button>
          <button type="button" @click="duplicate" class="button" :class="(!noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Duplicate</button>
          
          <template v-if="form.docStatusId !== 'CO' && form.docStatusId !== 'VO'">
            <button type="button" class="button" @click="setDocumentAction('CO')">Complete</button>
          </template>
          <button type="button" class="button" @click="setDocumentAction('VO')">Void</button>

        </template>
      </div>
      <div>
        <div class="d-flex gap-10px">
          <button v-if="activeSave" type="button" @click="activeSave = false; back();" class="button">
            <span class="tf-icon ti ti-square-x ti-xs me-1 color-inherit"></span> Abort
          </button>
          <button type="button" @click="back" class="button">
            <span class="tf-icon ti ti-chevron-left ti-xs me-1 color-inherit"></span> Back
          </button>
        </div>
      </div>
    </div>
    
    <div class="banner">
      <div class="d-flex justify-between mb-3">
        <InsideWindowTab v-model="tab" :tabs="tabs" />
      </div>
      <div>
        <ProcurementsPaymentForm v-model="form" v-model:tab="tab" @save="save" />
      </div>
      <div :class="(form.orderId === '' && form.invoiceId === '' && form.chargeId === '') ? '' : 'opacity-0.6 pointerEvents-none'">
        <ProcurementsPaymentDetailRecord action="edit" :info="form" tab="allocate" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="PO_Payment" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>