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

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

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

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

const retrieve = async () => {
  const res = await $fetch('/api/partners/job-positions/'+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 || '',
      help: res?.Help || '',
      isEmployee: res?.IsEmployee ?? false,
      jobCategory: res?.C_JobCategory_ID?.identifier || '',
      jobCategoryId: res?.C_JobCategory_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
    lastRecord.value = res
    setNoEdit()
  }
}
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.name == (lastRecord.value?.Name || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.help == (lastRecord.value?.Help || '') &&
    form.value.isEmployee == (lastRecord.value?.IsEmployee ?? false) &&
    form.value.jobCategoryId == (lastRecord.value?.C_JobCategory_ID?.id || '')
  ) ? true : false
}

const back = () => {
  router.push('/partners/job-positions')
}

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

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

  const res = await $fetch('/api/partners/job-positions/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      organizationId: form.value.organizationId,
      name: form.value.name,
      description: form.value.description,
      help: form.value.help,
      isActive: form.value.isActive,
      isEmployee: form.value.isEmployee,
      jobCategoryId: form.value.jobCategoryId
    }
  })

  if(Number(res.status) === 200) {
    if(saveType === 'preview') {
      router.push('/partners/job-positions/'+res.id+'/view')
    } else if(saveType === 'changes') {
      form.value.alert.processing = false
      location.reload()
    } else if(saveType === 'onlysave') {
      form.value.alert.processing = false
      toast({
        message: 'Saved!',
        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
    })
  }
}

const showAttachment = ref(false)

const breadCrumb = computed(() => ([
  { link: '/partners/partners', text: 'Partners'},
  { link: '/partners/job-positions', text: 'Job Positions'},
  { link: '#', text: 'Add Job Position', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Job Position</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.jobCategoryId === '' || 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.jobCategoryId === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.name === '' || form.jobCategoryId === '' || 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 class="editwrapper">
        <PartnersJobPositionForm v-model="form" @save="save"/>
      </div>
      <div>
        <PartnersJobPositionDetailRecord action="edit" :info="form" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="C_Job" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>