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

const router = useRouter()
const route = useRoute()

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

const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  isActive: true,
  name: '',
  value: '',
  help: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/settings/document-groups/'+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 || '',
      isActive: res?.IsActive ?? true,
      name: res?.Name || '',
      value: res?.Value || '',
      help: res?.Help || '',
      alert: {
        status: '',
        message: '',
        processing: false,
      }
    }
  }
}
onMounted(retrieve)

const back = () => {
  router.push('/settings/document-groups')
}

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

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

  const res = await $fetch('/api/settings/document-groups/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      name: form.value.name,
      value: form.value.value,
      help: form.value.help
    }
  })

  if(Number(res.status) === 200) {
    if(saveType === 'preview') {
      router.push('/settings/document-groups/'+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-groups', text: 'Document Groups'},
  { link: '#', text: 'Add Document Group', active: true}
]))
</script>

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