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

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

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

const client = useCookie('logship_client')
const clientId = useCookie('logship_client_id')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
const warehouse = useCookie('logship_warehouse')
const warehouseId = useCookie('logship_warehouse_id')
const user = useCookie('logship_user')

const { data: preferences } = await useFetch('/api/preferences/183', {
  headers: useRequestHeaders(['cookie'])
})

const preference = (attribute) => {
  let newPreference = preferences.value[attribute] || {}
  if(newPreference?.id == '-1') {
    newPreference.id = ''
  }
  return newPreference
}

const lines = ref([])
const form = ref({
  id: '',
  uid: '',
  client: client.value?.Name || '',
  clientId: clientId.value || '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  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: false,
  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: preference('C_DocTypeTarget_ID')?.identifier || '',
  docTypeTargetId: preference('C_DocTypeTarget_ID')?.id === '123' ? '116' : (preference('C_DocTypeTarget_ID')?.id || ''),
  salesRep: preference('SalesRep_ID')?.identifier || user.value?.Name || '',
  salesRepId: preference('SalesRep_ID')?.id || user.value?.id || '',
  paymentTerm: preference('C_PaymentTerm_ID')?.identifier || '',
  paymentTermId: preference('C_PaymentTerm_ID')?.id || '',
  currency: 'EUR',
  currencyId: '102',
  invoiceRule: '',
  invoiceRuleId: '',
  paymentRule: 'Cash',
  paymentRuleId: preference('PaymentRule')?.id || 'B',
  priceList: preference('M_PriceList_ID')?.identifier || '',
  priceListId: preference('M_PriceList_ID')?.id || '',
  partner: '',
  partnerId: '',
  partnerLocation: '',
  partnerLocationId: '',
  cashLine: '',
  cashLineId: '',
  project: preference('C_Project_ID')?.identifier || '',
  projectId: preference('C_Project_ID')?.id || '',
  campaign: preference('C_Campaign_ID')?.identifier || '',
  campaignId: preference('C_Campaign_ID')?.id || '',
  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: '',
      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: '',
      poReference: res?.POReference || '',
      description: res?.Description || '',
      isApproved: false,
      isPaid: false,
      isPrinted: false,
      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: false,
      isSOTrx: false,
      isDiscountPrinted: false,
      isTaxIncluded: res?.IsTaxIncluded ?? false,
      isSelected: res?.IsSelected ?? false,
      sendEMail: res?.SendEMail ?? false,
      isSelfService: false,
      processedOn: 0,
      isPayScheduleValid: res?.IsPayScheduleValid ?? false,
      dateInvoiced: res?.DateInvoiced || date.now('date'),
      isInDispute: false,
      isFixedAssetInvoice: false,
      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: 'Draft',
      docStatusId: '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,
      }
    }
    
    lines.value = res.c_invoiceline.map(item => {
      return {
        id: '',
        client: item?.AD_Client_ID?.identifier || '',
        clientId: item?.AD_Client_ID?.id || '',
        organization: item?.AD_Org_ID?.identifier || '',
        organizationId: item?.AD_Org_ID?.id || '',
        invoice: item?.C_Invoice_ID?.identifier || '',
        invoiceId: item?.C_Invoice_ID?.id || '',
        isActive: item?.IsActive ?? true,
        line: item?.Line || '',
        product: item?.M_Product_ID?.Name || '',
        productId: item?.M_Product_ID?.id || '',
        galleries: [],
        description: item?.Description || '',
        isDescription: item?.IsDescription ?? false,
        isPrinted: item?.IsPrinted ?? false,
        qtyEntered: item?.QtyEntered || 1,
        qtyInvoiced: item?.QtyInvoiced || 0.0,
        uom: item?.C_UOM_ID?.identifier || '',
        uomId: item?.C_UOM_ID?.id || '',
        priceActual: item?.PriceActual || 0,
        priceEntered: item?.PriceEntered || 0,
        priceList: item?.PriceList || 0,
        tax: item?.C_Tax_ID?.identifier || '',
        taxId: item?.C_Tax_ID?.id || '',
        lineNetAmt: item?.LineNetAmt || 0,
        inOutLine: item?.M_InOutLine_ID?.identifier || '',
        inOutLineId: item?.M_InOutLine_ID?.id || '',
        attributeSetInstance: item?.M_AttributeSetInstance_ID?.identifier || '',
        attributeSetInstanceId: item?.M_AttributeSetInstance_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 || '',
        alert: {
          status: '',
          message: '',
          processing: false,
        }
      }
    })
    
    const newEntries = []
    for(let item of lines.value) {
      const response = await $fetch(`/api/materials/products/${item.productId}`)
      if(response?.Strapi_Product_documentId) {
        const resp = await $fetch(`/api/materials/products/${response.Strapi_Product_documentId}/galleries/images`)
        if(resp) {
          item.galleries = resp
        }
      }
      newEntries.push(item)
    }
    lines.value = newEntries
  
    setActiveSave()
  }
}
onMounted(retrieve)

const checkRequiredLines = computed(() => {
  return lines.value.filter(i => i.productId === '' || i.uomId === '' || i.qtyEntered === '' || i.priceEntered === '').length >= 1
})

const setActiveSave = () => {
  if(form.value.paymentRuleId !== '' && form.value.dateInvoiced !== '' && form.value.dateAcct !== '' && form.value.partnerId !== '' && form.value.partnerLocationId !== '' && form.value.priceListId !== '' && form.value.currencyId !== '' && !checkRequiredLines.value) {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

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/invoices')
  }
}

const save = async (record) => {
  form.value = record
  
  setActiveSave()
}

const saveLines = async (invoiceLines) => {
  lines.value = invoiceLines
  
  setActiveSave()
}

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

  let newObjValue = {}
  if(lines.value.length >= 1) {
    newObjValue = {...newObjValue, 
      invoiceLines: lines.value.map(entry => {
        let newObjEntry = {}
        if(entry.productId) {
          newObjEntry = {...newObjEntry, 
            M_Product_ID: {
              id: entry.productId
            }
          }
        }
        if(entry.uomId) {
          newObjEntry = {...newObjEntry, 
            C_UOM_ID: {
              id: entry.uomId
            }
          }
        }
        if(entry.taxId) {
          newObjEntry = {...newObjEntry, 
            C_Tax_ID: {
              id: entry.taxId
            }
          }
        }
        if(entry.inOutLineId) {
          newObjEntry = {...newObjEntry, 
            M_InOutLine_ID: {
              id: entry.inOutLineId
            }
          }
        }
        if(entry.attributeSetInstanceId) {
          newObjEntry = {...newObjEntry, 
            M_AttributeSetInstance_ID: {
              id: entry.attributeSetInstanceId
            }
          }
        }
        if(entry.chargeId) {
          newObjEntry = {...newObjEntry, 
            C_Charge_ID: {
              id: entry.chargeId
            }
          }
        }
        if(entry.projectId) {
          newObjEntry = {...newObjEntry, 
            C_Project_ID: {
              id: entry.projectId
            }
          }
        }
        if(entry.campaignId) {
          newObjEntry = {...newObjEntry, 
            C_Campaign_ID: {
              id: entry.campaignId
            }
          }
        }

        return {
          AD_Org_ID: {
            id: form.value.organizationId
          },
          line: entry.line,
          isActive: entry.isActive,
          qtyInvoiced: entry?.qtyInvoiced || 0,
          qtyEntered: entry.qtyEntered,
          priceActual: entry.priceActual,
          priceEntered: entry.priceEntered,
          priceList: entry.priceList,
          priceLimit: entry.priceList,
          lineNetAmt: entry.lineNetAmt,
          ...newObjEntry
        }
      })
    }
  }
  /*if(entries?.['payment_schedule']) {
    newObjValue = {...newObjValue, 
      paymentSchedules: entries['payment_schedule'].map(entry => {
        let newObjEntry = {}
        if(entry.payScheduleId) {
          newObjEntry = {...newObjEntry, 
            C_PaySchedule_ID: {
              id: entry.payScheduleId
            }
          }
        }

        return {
          discountAmt: entry.discountAmt,
          discountDate: entry.discountDate,
          dueAmt: entry.dueAmt,
          dueDate: entry.dueDate,
          isActive: entry.isActive,
          isValid: entry.isValid,
          ...newObjEntry
        }
      })
    }
  }*/

  const res = await $fetch('/api/invoices/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      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: false,
      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,
      ...newObjValue
    }
  })

  if(Number(res.status) === 200 && Number(res.id) !== 0) {
    form.value.alert.processing = false
    activeSave.value = false

    if(saveType === 'preview') {
      router.push('/procurements/invoices/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/procurements/invoices/'+res.id+'/edit')
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
    } 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 breadCrumb = computed(() => ([
  { link: '#', text: 'Procurements'},
  { link: '/procurements/invoices', text: 'Invoices'},
  { link: '#', text: 'Add 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 openOtherTab = () => {
  if(tab.value === 'basic') {
    tab.value = 'invoice'
  } else if(tab.value === 'invoice') {
    tab.value = 'reference'
  } else if(tab.value === 'reference') {
    tab.value = 'status'
  }
}
</script>

<template>
  <Head>
    <Title>Add 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' || checkRequiredLines || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
        <button v-if="tab !== 'status'" type="button" @click="openOtherTab" class="button">Next</button>
      </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>
        <ProcurementsInvoiceForm v-model="form" v-model:tab="tab" v-model:lines="lines" @save="save" />
      </div>
      <div>
        <ProcurementsInvoiceLineTable v-model="lines" action="create" :info="form" @save="saveLines" />
      </div>
    </div>
  </NuxtLayout>
</template>