<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: '',
  name: '',
  description: '',
  isActive: true,
  isAccrual: false,
  autoPeriodControl: false,
  periodOpenHistory: 0,
  periodOpenFuture: 0,
  separator: '-',
  hasAlias: true,
  hasCombination: false,
  isTradeDiscountPosted: false,
  isDiscountCorrectsTax: false,
  isAdjustCOGS: false,
  isPostServices: false,
  isExplicitCostAdjustment: false,
  isAllowNegativePosting: true,
  isPostIfClearingEqual: true,
  gaap: '',
  gaapId: '',
  costingMethod: '',
  costingMethodId: '',
  currency: '',
  currencyId: '',
  period: '',
  periodId: '',
  costType: '',
  costTypeId: '',
  costingLevel: '',
  costingLevelId: '',
  commitmentType: '',
  commitmentTypeId: '',
  taxCorrectionType: '',
  taxCorrectionTypeId: '',
  orgOnly: '',
  orgOnlyId: '',
  processing: false,
  alert: {
    status: '',
    message: ''
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/accountings/schemas/'+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 || '',
      name: res?.Name || '',
      description: res?.Description || '',
      isActive: res?.IsActive ?? true,
      isAccrual: res?.IsAccrual ?? false,
      autoPeriodControl: res?.AutoPeriodControl ?? false,
      periodOpenHistory: res?.Period_OpenHistory || 0,
      periodOpenFuture: res?.Period_OpenFuture || 0,
      separator: res?.Separator || '-',
      hasAlias: res?.HasAlias ?? true,
      hasCombination: res?.HasCombination ?? false,
      isTradeDiscountPosted: res?.IsTradeDiscountPosted ?? false,
      isDiscountCorrectsTax: res?.IsDiscountCorrectsTax ?? false,
      isAdjustCOGS: res?.IsAdjustCOGS ?? false,
      isPostServices: res?.IsPostServices ?? false,
      isExplicitCostAdjustment: res?.IsExplicitCostAdjustment ?? false,
      isAllowNegativePosting: res?.IsAllowNegativePosting ?? true,
      isPostIfClearingEqual: res?.IsPostIfClearingEqual ?? true,
      gaap: res?.GAAP?.identifier || '',
      gaapId: res?.GAAP?.id || '',
      costingMethod: res?.CostingMethod?.identifier || '',
      costingMethodId: res?.CostingMethod?.id || '',
      currency: res?.C_Currency_ID?.identifier || '',
      currencyId: res?.C_Currency_ID?.id || '',
      period: res?.C_Period_ID?.identifier || '',
      periodId: res?.C_Period_ID?.id || '',
      costType: res?.M_CostType_ID?.identifier || '',
      costTypeId: res?.M_CostType_ID?.id || '',
      costingLevel: res?.CostingLevel?.identifier || '',
      costingLevelId: res?.CostingLevel?.id || '',
      commitmentType: res?.CommitmentType?.identifier || '',
      commitmentTypeId: res?.CommitmentType?.id || '',
      taxCorrectionType: res?.TaxCorrectionType?.identifier || '',
      taxCorrectionTypeId: res?.TaxCorrectionType?.id || '',
      orgOnly: res?.AD_OrgOnly_ID?.identifier || '',
      orgOnlyId: res?.AD_OrgOnly_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: ''
      }
    }
  }
}
onMounted(retrieve)

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

const save = async (record, id = '', saveType = '') => {
  const res = await $fetch('/api/accountings/schemas/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: record.id,
      organizationId: record.organizationId,
      name: record.name,
      description: record.description,
      isActive: record.isActive,
      isAccrual: record.isAccrual,
      autoPeriodControl: record.autoPeriodControl,
      periodOpenHistory: record.periodOpenHistory,
      periodOpenFuture: record.periodOpenFuture,
      separator: record.separator,
      hasAlias: record.hasAlias,
      hasCombination: record.hasCombination,
      isTradeDiscountPosted: record.isTradeDiscountPosted,
      isDiscountCorrectsTax: record.isDiscountCorrectsTax,
      isAdjustCOGS: record.isAdjustCOGS,
      isPostServices: record.isPostServices,
      isExplicitCostAdjustment: record.isExplicitCostAdjustment,
      isAllowNegativePosting: record.isAllowNegativePosting,
      isPostIfClearingEqual: record.isPostIfClearingEqual,
      gaapId: record.gaapId,
      costingMethodId: record.costingMethodId,
      currencyId: record.currencyId,
      periodId: record.periodId,
      costTypeId: record.costTypeId,
      costingLevelId: record.costingLevelId,
      commitmentTypeId: record.commitmentTypeId,
      taxCorrectionTypeId: record.taxCorrectionTypeId,
      orgOnlyId: record.orgOnlyId,
    }
  })

  if(Number(res.status) === 200) {
    if(saveType === 'preview') {
      router.push('/accountings/schemas/'+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/schemas', text: 'Accounting Schemas'},
  { link: '#', text: 'Edit Accounting Schemas', active: true}
]))
</script>

<template>
  <Head>
    <Title>Edit Accounting Schemas</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>
          <AccountingsSchemaForm v-model="form" @save="save"/>
        </div>
      </div>

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