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

const url = useRequestURL()
const router = useRouter()
const route = useRoute()

const printPreview = usePrintPreview()
const printParam = usePrintParam()
const activeSave = useActiveSave()
const windowFrom = useWindowFrom()
const windowParam = useWindowParam()

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

const invoiceParam = ref({})
const window = (from) => {
  if(windowParam.value?.[from] && url.pathname.includes('windows/sales-invoices-edit/')) {
    invoiceParam.value = windowParam.value?.[from] || {}
  }
  
  return invoiceParam.value
}

const showDocumentAction = ref(false)
const lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  isActive: true,
  documentNo: '',
  poReference: '',
  description: '',
  isApproved: false,
  isPaid: false,
  isPrinted: false,
  isTransferred: false,
  dateOrdered: date.now('date'),
  dateAcct: date.now('date'),
  totalLines: 1,
  grandTotal: 0,
  chargeAmt: 0,
  processed: false,
  isSOTrx: true,
  isDiscountPrinted: false,
  isTaxIncluded: false,
  sendEMail: false,
  isSelfService: false,
  processedOn: 0,
  isPayScheduleValid: false,
  dateInvoiced: date.now('date'),
  isInDispute: false,
  isFixedAssetInvoice: false,
  isOverrideCurrencyRate: false,
  docBaseType: '',
  docBaseTypeId: '',
  user: '',
  userId: '',
  order: '',
  orderId: '',
  docStatus: 'Draft',
  docStatusId: 'DR',
  docType: '',
  docTypeId: 0,
  docTypeTarget: '',
  docTypeTargetId: '',
  salesRep: '',
  salesRepId: '',
  paymentTerm: '',
  paymentTermId: '',
  currency: '',
  currencyId: '',
  invoiceRule: '',
  invoiceRuleId: '',
  paymentRule: '',
  paymentRuleId: '',
  priceList: '',
  priceListId: '',
  partner: '',
  partnerId: '',
  partnerLocation: '',
  partnerLocationId: '',
  cashLine: '',
  cashLineId: '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/invoices/'+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 || '',
      poReference: res?.POReference || '',
      description: res?.Description || '',
      isApproved: res?.IsApproved ?? false,
      isPaid: res?.IsPaid ?? false,
      isPrinted: res?.IsPrinted ?? false,
      isTransferred: res?.IsTransferred ?? false,
      dateOrdered: res?.DateOrdered || date.now('date'),
      dateAcct: res?.DateAcct || date.now('date'),
      totalLines: res?.TotalLines || 1,
      grandTotal: res?.QrandTotal || 0,
      chargeAmt: res?.ChargeAmt || 0,
      processed: res?.Processed ?? false,
      isSOTrx: res?.IsSOTrx ?? true,
      isDiscountPrinted: res?.IsDiscountPrinted ?? false,
      isTaxIncluded: res?.IsTaxIncluded ?? false,
      isSelected: res?.IsSelected ?? false,
      sendEMail: res?.SendEMail ?? false,
      isSelfService: res?.IsSelfService ?? false,
      processedOn: res?.ProcessedOn || 0,
      isPayScheduleValid: res?.IsPayScheduleValid ?? false,
      dateInvoiced: res?.DateInvoiced || date.now('date'),
      isInDispute: res?.IsInDispute ?? false,
      isFixedAssetInvoice: res?.IsFixedAssetInvoice ?? false,
      isOverrideCurrencyRate: res?.IsOverrideCurrencyRate ?? false,
      docBaseType: res?.DocBaseType?.identifier || '',
      docBaseTypeId: res?.DocBaseType?.id || '',
      user: res?.AD_User_ID?.identifier || '',
      userId: res?.AD_User_ID?.id || '',
      order: res?.C_Order_ID?.identifier || '',
      orderId: res?.C_Order_ID?.id || '',
      docStatus: res?.DocStatus?.identifier || 'Draft',
      docStatusId: res?.DocStatus?.id || 'DR',
      docType: res?.C_DocType_ID?.identifier || '',
      docTypeId: res?.C_DocType_ID?.id || 0,
      docTypeTarget: res?.C_DocTypeTarget_ID?.identifier || '',
      docTypeTargetId: res?.C_DocTypeTarget_ID?.id || '',
      salesRep: res?.SalesRep_ID?.identifier || '',
      salesRepId: res?.SalesRep_ID?.id || '',
      paymentTerm: res?.C_PaymentTerm_ID?.identifier || '',
      paymentTermId: res?.C_PaymentTerm_ID?.id || '',
      currency: res?.C_Currency_ID?.identifier || '',
      currencyId: res?.C_Currency_ID?.id || '',
      invoiceRule: res?.InvoiceRule?.identifier || '',
      invoiceRuleId: res?.InvoiceRule?.id || '',
      paymentRule: res?.PaymentRule?.identifier || '',
      paymentRuleId: res?.PaymentRule?.id || '',
      priceList: res?.M_PriceList_ID?.identifier || '',
      priceListId: res?.M_PriceList_ID?.id || '',
      partner: res?.C_BPartner_ID?.identifier || '',
      partnerId: res?.C_BPartner_ID?.id || '',
      partnerLocation: res?.C_BPartner_Location_ID?.identifier || '',
      partnerLocationId: res?.C_BPartner_Location_ID?.id || '',
      cashLine: res?.C_CashLine_ID?.identifier || '',
      cashLineId: res?.C_CashLine_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.poReference == (lastRecord.value?.POReference || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.isApproved == (lastRecord.value?.IsApproved ?? false) &&
    form.value.isPaid == (lastRecord.value?.IsPaid ?? false) &&
    form.value.isPrinted == (lastRecord.value?.IsPrinted ?? false) &&
    form.value.isTransferred == (lastRecord.value?.IsTransferred ?? false) &&
    form.value.dateOrdered == (lastRecord.value?.DateOrdered || date.now('date')) &&
    form.value.dateAcct == (lastRecord.value?.DateAcct || date.now('date')) &&
    form.value.totalLines == (lastRecord.value?.TotalLines || 1) &&
    form.value.grandTotal == (lastRecord.value?.QrandTotal || 0) &&
    form.value.chargeAmt == (lastRecord.value?.ChargeAmt || 0) &&
    form.value.processed == (lastRecord.value?.Processed ?? false) &&
    form.value.isSOTrx == (lastRecord.value?.IsSOTrx ?? true) &&
    form.value.isDiscountPrinted == (lastRecord.value?.IsDiscountPrinted ?? false) &&
    form.value.isTaxIncluded == (lastRecord.value?.IsTaxIncluded ?? false) &&
    form.value.isSelected == (lastRecord.value?.IsSelected ?? false) &&
    form.value.sendEMail == (lastRecord.value?.SendEMail ?? false) &&
    form.value.isSelfService == (lastRecord.value?.IsSelfService ?? false) &&
    form.value.processedOn == (lastRecord.value?.ProcessedOn || 0) &&
    form.value.isPayScheduleValid == (lastRecord.value?.IsPayScheduleValid ?? false) &&
    form.value.dateInvoiced == (lastRecord.value?.DateInvoiced || date.now('date')) &&
    form.value.isInDispute == (lastRecord.value?.IsInDispute ?? false) &&
    form.value.isFixedAssetInvoice == (lastRecord.value?.IsFixedAssetInvoice ?? false) &&
    form.value.isOverrideCurrencyRate == (lastRecord.value?.IsOverrideCurrencyRate ?? false) &&
    form.value.docBaseTypeId == (lastRecord.value?.DocBaseType?.id || '') &&
    form.value.userId == (lastRecord.value?.AD_User_ID?.id || '') &&
    form.value.orderId == (lastRecord.value?.C_Order_ID?.id || '') &&
    form.value.docStatusId == (lastRecord.value?.DocStatus?.id || 'DR') &&
    form.value.docTypeId == (lastRecord.value?.C_DocType_ID?.id || 0) &&
    form.value.docTypeTargetId == (lastRecord.value?.C_DocTypeTarget_ID?.id || '') &&
    form.value.salesRepId == (lastRecord.value?.SalesRep_ID?.id || '') &&
    form.value.paymentTermId == (lastRecord.value?.C_PaymentTerm_ID?.id || '') &&
    form.value.currencyId == (lastRecord.value?.C_Currency_ID?.id || '') &&
    form.value.invoiceRuleId == (lastRecord.value?.InvoiceRule?.id || '') &&
    form.value.paymentRuleId == (lastRecord.value?.PaymentRule?.id || '') &&
    form.value.priceListId == (lastRecord.value?.M_PriceList_ID?.id || '') &&
    form.value.partnerId == (lastRecord.value?.C_BPartner_ID?.id || '') &&
    form.value.partnerLocationId == (lastRecord.value?.C_BPartner_Location_ID?.id || '') &&
    form.value.cashLineId == (lastRecord.value?.C_CashLine_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(`/sales/invoices/${route.params.id}/duplicate`)
}
const print = () => {
  //router.push(`/sales/invoices/${route.params.id}/print`)
  printParam.value = form.value
  printPreview.value = true
}

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(window('partners')?.path || '/sales/invoices')
    let newUrl = '/sales/invoices'
    if(windowParam.value?.[windowFrom.value]?.path) {
      newUrl = windowParam.value[windowFrom.value].path
    }
    router.push(newUrl)
    if(windowParam.value?.[windowFrom.value]?.path) {
      windowFrom.value = ''
      windowParam.value = {}
    }
  }
}

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/invoices/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      documentNo: form.value.documentNo,
      poReference: form.value.poReference,
      description: form.value.description,
      isApproved: form.value.isApproved,
      isPaid: form.value.isPaid,
      isPrinted: form.value.isPrinted,
      isTransferred: form.value.isTransferred,
      dateOrdered: form.value.dateOrdered,
      dateAcct: form.value.dateAcct,
      totalLines: form.value.totalLines,
      grandTotal: form.value.grandTotal,
      chargeAmt: form.value.chargeAmt,
      processed: form.value.processed,
      isSOTrx: true,
      isDiscountPrinted: form.value.isDiscountPrinted,
      isTaxIncluded: form.value.isTaxIncluded,
      sendEMail: form.value.sendEMail,
      isSelfService: form.value.isSelfService,
      processedOn: form.value.processedOn,
      isPayScheduleValid: form.value.isPayScheduleValid,
      dateInvoiced: form.value.dateInvoiced,
      isInDispute: form.value.isInDispute,
      isFixedAssetInvoice: form.value.isFixedAssetInvoice,
      isOverrideCurrencyRate: form.value.isOverrideCurrencyRate,
      docBaseTypeId: form.value.docBaseTypeId,
      userId: form.value.userId,
      orderId: form.value.orderId,
      docStatusId: form.value.docStatusId,
      docTypeId: form.value.docTypeId,
      docTypeTargetId: form.value.docTypeTargetId,
      salesRepId: form.value.salesRepId,
      paymentTermId: form.value.paymentTermId,
      currencyId: form.value.currencyId,
      invoiceRuleId: form.value.invoiceRuleId,
      paymentRuleId: form.value.paymentRuleId,
      priceListId: form.value.priceListId,
      partnerId: form.value.partnerId,
      partnerLocationId: form.value.partnerLocationId,
      cashLineId: form.value.cashLineId,
      projectId: form.value.projectId,
      campaignId: form.value.campaignId,
    }
  })

  if(Number(res.status) === 200) {
    windowFrom.value = ''
    windowParam.value = {}
    form.value.alert.processing = false
    activeSave.value = false
    
    if(saveType === 'preview') {
      router.push('/sales/invoices/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
      retrieve()
      // location.reload()
    } 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: 'Sales'},
  { link: '/sales/invoices', text: 'Invoices'},
  { link: '#', text: 'Edit Invoice', active: true}
]))

const tab = ref(route.query?.tab || 'basic')
const tabs = computed(() => ([
  { value: 'basic', text: 'Basic'},
  { value: 'invoice', text: 'Invoice'},
  { value: 'reference', text: 'Reference'},
  { value: 'status', text: 'Status'}
]))
const isOpen = ref(false)

// const { data, error, pending } = useFetch('/api/changelog/' + route.params.id, {
//   headers: useRequestHeaders(['cookie'])
// })

const data = ref(null)
const error = ref(null)
const pending = ref(false)
let groupedByUpdated = ref(null)

const fetchData = async () => {
  pending.value = true
  const { data: fetchedData, error: fetchError } = await useFetch('/api/changelog/' + route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })

   groupedByUpdated = fetchedData.value?.reduce((acc, item) => {
    const updatedKey = item.Updated;
    if (!acc[updatedKey]) {
      acc[updatedKey] = [];
    }
    acc[updatedKey].push(item);
    return acc;
  }, {});
  // console.log(groupedByUpdated);

  console.log('YOUNES')
  console.log(fetchedData)
  console.log(groupedByUpdated)
  // data.value = fetchedData.value
  data.value = groupedByUpdated
  error.value = fetchError.value
  pending.value = false
}

const setDocumentAction = async (docAction) => {
  const res = await $fetch('/api/invoices/'+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 Invoice</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.paymentRuleId === '' || form.dateInvoiced === '' || form.dateAcct === '' || form.partnerId === '' || form.partnerLocationId === '' || form.priceListId === '' || form.currencyId === '' || form.docStatusId === 'CO' || 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.paymentRuleId === '' || form.dateInvoiced === '' || form.dateAcct === '' || form.partnerId === '' || form.partnerLocationId === '' || form.priceListId === '' || form.currencyId === '' || form.docStatusId === 'CO' || 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>
          
          <button type="button" class="button" @click="print();">Print Preview</button>
          
          <template v-if="form.docStatusId !== 'CO' && form.docStatusId !== 'VO' && form.docStatusId !== 'CL'">
            <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>
        <SalesInvoiceForm v-model="form" v-model:tab="tab" @save="save" />
      </div>
      <div>
        <SalesInvoiceDetailRecord :action="(form.docStatusId === 'CO' || form.docStatusId === 'VO') ? 'view' : 'edit'" :info="form" tab="invoice_line" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="C_Invoice" :info="form" />
      </div>
    </div>
  </NuxtLayout>

  <Teleport to="body">
    <PrintPreview modelName="invoices" />
    <SalesInvoiceDocumentAction v-model="showDocumentAction" :id="form.id" v-model:docId="form.docStatusId"/>
  </Teleport>
</template>