<script setup>
import { date } from 'alga-js'
const router = useRouter()
const route = useRoute()

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

const form = ref({
  id: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  description: '',
  isActive: true,
  documentNo: '',
  isPrinted: false,
  dateDoc: date.now('date'),
  dateAcct: date.now('date'),
  totalDr: 0,
  totalCr: 0,
  isApproved: false,
  currencyRate: 1,
  controlAmt: 0,
  processed: false,
  docType: '',
  docTypeId: '',
  docStatus: 'Draft',
  docStatusId: 'DR',
  postingType: '',
  postingTypeId: '',
  acctSchema: '',
  acctSchemaId: '',
  category: '',
  categoryId: '',
  period: '',
  periodId: '',
  currency: '',
  currencyId: '',
  conversionType: '',
  conversionTypeId: '',
  processing: false,
  alert: {
    status: '',
    message: ''
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/accountings/journals/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: route.params.id,
      client: res?.AD_Client_ID?.identifier || '',
      clientId: res?.AD_Client_ID?.id || '',
      organization: res?.AD_Org_ID?.identifier || '',
      organizationId: res?.AD_Org_ID?.id || '',
      description: res?.Description || '',
      isActive: res?.IsActive ?? true,
      documentNo: res?.DocumentNo || '',
      isPrinted: res?.IsPrinted ?? false,
      dateDoc: res?.DateDoc || date.now('date'),
      dateAcct: res?.DateAcct || date.now('date'),
      totalDr: res?.TotalDr || 0,
      totalCr: res?.TotalCr || 0,
      isApproved: res?.IsApproved ?? false,
      currencyRate: res?.CurrencyRate || 1,
      controlAmt: res?.ControlAmt || 0,
      processed: res?.Processed ?? false,
      docType: res?.C_DocType_ID?.identifier || '',
      docTypeId: res?.C_DocType_ID?.id || '',
      docStatus: res?.DocStatus?.identifier || 'Draft',
      docStatusId: res?.DocStatus?.id || 'DR',
      postingType: res?.PostingType?.identifier || '',
      postingTypeId: res?.PostingType?.id || '',
      acctSchema: res?.C_AcctSchema_ID?.identifier || '',
      acctSchemaId: res?.C_AcctSchema_ID?.id || '',
      category: res?.GL_Category_ID?.identifier || '',
      categoryId: res?.GL_Category_ID?.id || '',
      period: res?.C_Period_ID?.identifier || '',
      periodId: res?.C_Period_ID?.id || '',
      currency: res?.C_Currency_ID?.identifier || '',
      currencyId: res?.C_Currency_ID?.id || '',
      conversionType: res?.C_ConversionType_ID?.identifier || '',
      conversionTypeId: res?.C_ConversionType_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: ''
      }
    }
  }
}
onMounted(retrieve)

const back = () => {
  router.push('/accountings/journals')
}

const save = async (record, id = '', saveType = '') => {
  const res = await $fetch('/api/accountings/journals/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: record.id,
      organizationId: record.organizationId,
      description: record.description,
      isActive: record.isActive,
      documentNo: record.documentNo,
      isPrinted: record.isPrinted,
      dateDoc: record.dateDoc,
      dateAcct: record.dateAcct,
      totalDr: record.totalDr,
      totalCr: record.totalCr,
      isApproved: record.isApproved,
      currencyRate: record.currencyRate,
      controlAmt: record.controlAmt,
      processed: record.processed,
      docTypeId: record.docTypeId,
      docStatusId: record.docStatusId,
      postingTypeId: record.postingTypeId,
      acctSchemaId: record.acctSchemaId,
      categoryId: record.categoryId,
      periodId: record.periodId,
      currencyId: record.currencyId,
      conversionTypeId: record.conversionTypeId,
    }
  })

  if(Number(res.status) === 200) {
    if(saveType === 'preview') {
      router.push('/accountings/journals/'+res.id+'/view')
    } else if(saveType === 'changes') {
      form.value.processing = false
      location.reload()
    } else {
      back()
    }
  } else {
    form.value.alert.status = res.status
    form.value.alert.message = res.message
    form.value.processing = false
    window.scrollTo(0, 0)
  }
}

const breadCrumb = computed(() => ([
  { link: '/accountings/journals', text: 'Journal Entries'},
  { link: '#', text: 'Edit Journal Entry', active: true}
]))
</script>

<template>
  <Head>
    <Title>Edit Journal Entry</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <div>
      <div class="banner">
        <div class="d-flex justify-between mb-3">
          <h4></h4>
          <div class="d-flex gap-0.75rem">
            <button type="button" @click="back" class="button">
              <span class="tf-icon ti ti-chevron-left ti-xs me-1"></span> Back
            </button>
          </div>
        </div>
        <div>
          <AccountingsJournalForm v-model="form" @save="save"/>
        </div>
      </div>

    </div>
  </NuxtLayout>
</template>