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

const router = useRouter()
const route = useRoute()
const url = useRequestURL()
const windowFrom = useWindowFrom()
const windowParam = useWindowParam()

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

const window = (from) => {
  let newParam = {}
  if(windowParam.value?.[from] && url.pathname.includes('windows/documents-types-edit/')) {
    newParam = windowParam.value?.[from] || {}
  }
  return newParam
}

const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  isActive: true,
  name: '',
  description: '',
  isDocNoControlled: false,
  printName: '',
  hasCharges: false,
  hasProforma: false,
  isDefault: false,
  documentCopies: 1,
  isSOTrx: false,
  isDefaultCounterDoc: false,
  isPickQAConfirm: false,
  isShipConfirm: false,
  isInTransit: false,
  isSplitWhenDifference: false,
  isCreateCounter: false,
  isIndexed: false,
  isOverwriteSeqOnComplete: false,
  isOverwriteDateOnComplete: false,
  isPrepareSplitDocument: false,
  isChargeOrProductMandatory: false,
  isNoPriceListCheck: false,
  documentNote: '',
  printFormat: '',
  printFormatId: '',
  definiteSequence: '',
  definiteSequenceId: '',
  docNoSequence: '',
  docNoSequenceId: '',
  category: '',
  categoryId: '',
  docBaseType: '',
  docBaseTypeId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/settings/document-types/'+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,
      name: res?.Name || '',
      description: res?.Description || '',
      isDocNoControlled: res?.IsDocNoControlled ?? false,
      printName: res?.PrintName || '',
      hasCharges: res?.HasCharges ?? false,
      hasProforma: res?.HasProforma ?? false,
      isDefault: res?.IsDefault ?? false,
      documentCopies: res?.DocumentCopies || '',
      isSOTrx: res?.IsSOTrx ?? false,
      isDefaultCounterDoc: res?.IsDefaultCounterDoc ?? false,
      isPickQAConfirm: res?.IsPickQAConfirm ?? false,
      isShipConfirm: res?.IsShipConfirm ?? false,
      isInTransit: res?.IsInTransit ?? false,
      isSplitWhenDifference: res?.IsSplitWhenDifference ?? false,
      isCreateCounter: res?.IsCreateCounter ?? false,
      isIndexed: res?.IsIndexed ?? false,
      isOverwriteSeqOnComplete: res?.IsOverwriteSeqOnComplete ?? false,
      isOverwriteDateOnComplete: res?.IsOverwriteDateOnComplete ?? false,
      isPrepareSplitDocument: res?.IsPrepareSplitDocument ?? false,
      isChargeOrProductMandatory: res?.IsChargeOrProductMandatory ?? false,
      isNoPriceListCheck: res?.IsNoPriceListCheck ?? false,
      documentNote: res?.DocumentNote || '',
      printFormat: res?.AD_PrintFormat_ID?.identifier || '',
      printFormatId: res?.AD_PrintFormat_ID?.id || '',
      definiteSequence: res?.DefiniteSequence_ID?.identifier || '',
      definiteSequenceId: res?.DefiniteSequence_ID?.id || '',
      docNoSequence: res?.DocNoSequence_ID?.identifier || '',
      docNoSequenceId: res?.DocNoSequence_ID?.id || '',
      category: res?.GL_Category_ID?.identifier || '',
      categoryId: res?.GL_Category_ID?.id || '',
      docBaseType: res?.DocBaseType?.identifier || '',
      docBaseTypeId: res?.DocBaseType?.id || '',
      alert: {
        status: '',
        message: '',
        processing: false,
      }
    }
  }
}
onMounted(retrieve)

const back = () => {
  router.push(window('sales-orders-zoom')?.path || '/settings/document-types')
  if(window('sales-orders-zoom')?.path) {
    windowFrom.value = ''
    windowParam.value = {}
  }
}

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

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

  const res = await $fetch('/api/settings/document-types/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      name: form.value.name,
      description: form.value.description,
      isDocNoControlled: form.value.isDocNoControlled,
      printName: form.value.printName,
      hasCharges: form.value.hasCharges,
      hasProforma: form.value.hasProforma,
      isDefault: form.value.isDefault,
      documentCopies: form.value.documentCopies,
      isSOTrx: form.value.isSOTrx,
      isDefaultCounterDoc: form.value.isDefaultCounterDoc,
      isPickQAConfirm: form.value.isPickQAConfirm,
      isShipConfirm: form.value.isShipConfirm,
      isInTransit: form.value.isInTransit,
      isSplitWhenDifference: form.value.isSplitWhenDifference,
      isCreateCounter: form.value.isCreateCounter,
      isIndexed: form.value.isIndexed,
      isOverwriteSeqOnComplete: form.value.isOverwriteSeqOnComplete,
      isOverwriteDateOnComplete: form.value.isOverwriteDateOnComplete,
      isPrepareSplitDocument: form.value.isPrepareSplitDocument,
      isChargeOrProductMandatory: form.value.isChargeOrProductMandatory,
      isNoPriceListCheck: form.value.isNoPriceListCheck,
      documentNote: form.value.documentNote,
      printFormatId: form.value.printFormatId,
      definiteSequenceId: form.value.definiteSequenceId,
      docNoSequenceId: form.value.docNoSequenceId,
      categoryId: form.value.categoryId,
      docBaseTypeId: form.value.docBaseTypeId,
    }
  })

  if(Number(res.status) === 200) {
    windowFrom.value = ''
    windowParam.value = {}

    if(saveType === 'preview') {
      router.push('/settings/document-types/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      form.value.alert.processing = false
      toast({
        message: 'Updated!',
        type: 'is-success',
        duration: 2000
      })
      //location.reload()
    } else {
      back()
    }
  } else {
    form.value.alert.status = res.status
    form.value.alert.message = res.message
    form.value.alert.processing = 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: 'Settings'},
  { link: '/settings/document-types', text: 'Document Types'},
  { link: '#', text: 'Add Document Type', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Document Type</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.printName === '' || form.categoryId === '' || form.docBaseTypeId === '' || form.documentCopies === '' || form.printFormatId === '' || 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.printName === '' || form.categoryId === '' || form.docBaseTypeId === '' || form.documentCopies === '' || form.printFormatId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.name === '' || form.printName === '' || form.categoryId === '' || form.docBaseTypeId === '' || form.documentCopies === '' || form.printFormatId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Attachment</button>
        </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>
        <SettingsDocumentTypeForm v-model="form" @save="save" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="C_DocType" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>