<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,
  name: '',
  processing: true,
  isSOTrx: true,
  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 retrieve = async () => {
  const res = await $fetch('/api/rma/'+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,
      name: res?.Name || '',
      processing: res?.Processing ?? true,
      isSOTrx: res?.IsSOTrx ?? true,
      processed: res?.Processed ?? false,
      amt: res?.Amt || 0,
      help: res?.Help || '',
      inOut: res?.InOut_ID?.identifier || '',
      inOutId: res?.InOut_ID?.id || '',
      order: res?.C_Order_ID?.identifier || '',
      orderId: res?.C_Order_ID?.id || '',
      docType: res?.C_DocType_ID?.identifier || '',
      docTypeId: res?.C_DocType_ID?.id || '',
      docStatus: res?.DocStatus?.identifier || 'Draft',
      docStatusId: res?.DocStatus?.id || 'DR',
      salesRep: res?.SalesRep_ID?.identifier || '',
      salesRepId: res?.SalesRep_ID?.id || '',
      rmaType: res?.M_RMAType_ID?.identifier || '',
      rmaTypeId: res?.M_RMAType_ID?.id || '',
      currency: res?.C_Currency_ID?.identifier || '',
      currencyId: res?.C_Currency_ID?.id || '',
      partner: res?.C_BPartner_ID?.identifier || '',
      partnerId: res?.C_BPartner_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.name == (lastRecord.value?.Name || '') &&
    form.value.processing == (lastRecord.value?.Processing ?? true) &&
    form.value.processed == (lastRecord.value?.Processed ?? false) &&
    form.value.help == (lastRecord.value?.Help || '') &&
    form.value.inOutId == (lastRecord.value?.InOut_ID?.id || '') &&
    form.value.orderId == (lastRecord.value?.C_Order_ID?.id || '') &&
    form.value.docTypeId == (lastRecord.value?.C_DocType_ID?.id || '') &&
    form.value.docStatusId == (lastRecord.value?.DocStatus?.id || 'DR') &&
    form.value.salesRepId == (lastRecord.value?.SalesRep_ID?.id || '') &&
    form.value.rmaTypeId == (lastRecord.value?.M_RMAType_ID?.id || '') &&
    form.value.currencyId == (lastRecord.value?.C_Currency_ID?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/sales/customer-rma/${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('/sales/customer-rma')
  }
}

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/rma/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,
      name: form.value.name,
      processing: form.value.processing,
      isSOTrx: true,
      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,
    }
  })

  if(Number(res.status) === 200) {
    form.value.alert.processing = false
    activeSave.value = false
    
    if(saveType === 'preview') {
      router.push('/sales/customer-rma/'+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: 'Sales'},
  { link: '/sales/customer-rma', text: 'Customer RMA'},
  { link: '#', text: 'Edit RMA', active: true}
]))

const setDocumentAction = async (docAction) => {
  const res = await $fetch('/api/rma/'+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 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' || 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.name === '' || form.docTypeId === '' || form.inOutId === '' || form.salesRepId === '' || form.rmaTypeId === '' || 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.name === '' || form.docTypeId === '' || form.inOutId === '' || form.salesRepId === '' || form.rmaTypeId === '' || form.docStatusId === 'CO' || form.alert.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'">
            <button type="button" @click="setDocumentAction('CO')" class="button" :class="form.alert.processing ? 'pointerEvents-none opacity-0.6' : ''">Complete</button>
            <button type="button" @click="setDocumentAction('VO')" class="button" :class="form.alert.processing ? 'pointerEvents-none opacity-0.6' : ''">Void</button>
          </template>

        </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>
        <RmasCustomerRmaForm v-model="form" @save="save" />
      </div>
      <div>
        <RmasCustomerRmaDetailRecord action="edit" :info="form" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="M_RMA" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>