<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 clients = useCookie('logship_clients')
const client = useCookie('logship_client')
const clientId = useCookie('logship_client_id')
//const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')

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: '',
  description: '',
  isApproved: false,
  name: '',
  processing: true,
  isSOTrx: false,
  processed: false,
  amt: 0,
  help: '',
  inOut: '',
  inOutId: '',
  order: '',
  orderId: '',
  docType: '',
  docTypeId: '',
  docStatus: 'Draft',
  docStatusId: 'DR',
  salesRep: '',
  salesRepId: '',
  rmaType: '',
  rmaTypeId: '',
  currency: '',
  currencyId: '',
  partner: '',
  partnerId: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

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

const setActiveSave = () => {
  if(form.value.name !== '' && form.value.docTypeId !== '' && form.value.inOutId !== '' && form.value.salesRepId !== '' && form.value.rmaTypeId !== '' && !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/vendor-rma')
  }
}

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

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

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

  let newObjValue = {}
  if(lines.value.length >= 1) {
    newObjValue = {...newObjValue, 
      rmaLines: lines.value.map(entry => {
        let newObjEntry = {}
        if(entry.productId) {
          newObjEntry = {...newObjEntry, 
            M_Product_ID: {
              id: entry.productId
            }
          }
        }
        if(entry.taxId) {
          newObjEntry = {...newObjEntry, 
            C_Tax_ID: {
              id: entry.taxId
            }
          }
        }
        if(entry.inOutLineId) {
          newObjEntry = {...newObjEntry, 
            M_InOutLine_ID: {
              id: entry.inOutLineId
            }
          }
        }
        if(entry.chargeId) {
          newObjEntry = {...newObjEntry, 
            C_Charge_ID: {
              id: entry.chargeId
            }
          }
        }
        
        return {
          AD_Org_ID: {
            id: form.value.organizationId,
            tableName: 'AD_Org'
          },
          line: entry.line,
          isActive: entry.isActive,
          qty: entry.qty,
          processed: entry.processed ?? false,
          amt: entry.amt,
          taxAmt: entry.taxAmt,
          description: entry.description,
          lineNetAmt: entry.lineNetAmt,
          ...newObjEntry
        }
      })
    }
  }

  const res = await $fetch('/api/rma/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      documentNo: form.value.documentNo,
      description: form.value.description,
      isApproved: form.value.isApproved,
      name: form.value.name,
      processing: form.value.processing,
      isSOTrx: false,
      processed: form.value.processed,
      amt: form.value.amt,
      help: form.value.help,
      inOutId: form.value.inOutId,
      orderId: form.value.orderId,
      docTypeId: form.value.docTypeId,
      docStatusId: form.value.docStatusId,
      salesRepId: form.value.salesRepId,
      rmaTypeId: form.value.rmaTypeId,
      currencyId: form.value.currencyId,
      partnerId: form.value.partnerId,
      ...newObjValue
    }
  })

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

    if(saveType === 'preview') {
      router.push('/procurements/vendor-rma/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/procurements/vendor-rma/'+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/vendor-rma', text: 'Vendor RMA'},
  { link: '#', text: 'Add RMA', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add RMA</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.name === '' || form.docTypeId === '' || form.inOutId === '' || form.salesRepId === '' || form.rmaTypeId === '' || form.docStatusId === 'CO' || checkRequiredLines || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</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>
        <RmasVendorRmaForm v-model="form" v-model:lines="lines" @save="save" />
      </div>
      <div>
        <RmasVendorRmaLineTable v-model="lines" action="create" :info="form" @save="saveLines" />
      </div>
    </div>
  </NuxtLayout>
</template>