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

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

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

const lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  isActive: true,
  name: '',
  description: '',
  isDefault: false,
  isSelfService: false,
  dueDateTolerance: 7,
  isEMailWhenOverdue: false,
  isEMailWhenDue: false,
  isInvoiced: false,
  isAutoChangeRequest: false,
  isConfidentialInfo: false,
  isIndexed: false,
  autoDueDateDays: 0,
  headerColor: '',
  contentColor: '',
  confidentialType: '',
  confidentialTypeId: '',
  statusCategory: '',
  statusCategoryId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/requests/request-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 || '',
      isDefault: res?.IsDefault ?? false,
      isSelfService: res?.IsSelfService ?? false,
      dueDateTolerance: res?.DueDateTolerance || 7,
      isEMailWhenOverdue: res?.IsEMailWhenOverdue ?? false,
      isEMailWhenDue: res?.IsEMailWhenDue ?? false,
      isInvoiced: res?.IsInvoiced ?? false,
      isAutoChangeRequest: res?.IsAutoChangeRequest ?? false,
      isConfidentialInfo: res?.IsConfidentialInfo ?? false,
      isIndexed: res?.IsIndexed ?? false,
      autoDueDateDays: res?.AutoDueDateDays || 0,
      headerColor: res?.HeaderColor || '',
      contentColor: res?.ContentColor || '',
      confidentialType: res?.ConfidentialType?.identifier || '',
      confidentialTypeId: res?.ConfidentialType?.id || '',
      statusCategory: res?.R_StatusCategory_ID?.identifier || '',
      statusCategoryId: res?.R_StatusCategory_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false,
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false

    /*for(let record of ['update_notification']) {
      const response = await $fetch('/api/requests/request-types/'+route.params.id+'/'+record.replaceAll('_', '-'), {
        headers: useRequestHeaders(['cookie'])
      })
      if(response) {
        let newData = []
        if(record === 'update_notification') {
          newData = response.records.map(item => {
            return {
              id: item.uid,
              user: item.AD_User_ID.identifier,
              userId: item.AD_User_ID.id,
              isActive: item.IsActive,
              isSelfService: item.IsSelfService,
            }
          })
        }

        detailRecord.value[record] = newData
      }
    }*/
  }
}
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.isDefault == (lastRecord.value?.IsDefault ?? false) &&
    form.value.isSelfService == (lastRecord.value?.IsSelfService ?? false) &&
    form.value.dueDateTolerance == (lastRecord.value?.DueDateTolerance || 7) &&
    form.value.isEMailWhenOverdue == (lastRecord.value?.IsEMailWhenOverdue ?? false) &&
    form.value.isEMailWhenDue == (lastRecord.value?.IsEMailWhenDue ?? false) &&
    form.value.isInvoiced == (lastRecord.value?.IsInvoiced ?? false) &&
    form.value.isAutoChangeRequest == (lastRecord.value?.IsAutoChangeRequest ?? false) &&
    form.value.isConfidentialInfo == (lastRecord.value?.IsConfidentialInfo ?? false) &&
    form.value.isIndexed == (lastRecord.value?.IsIndexed ?? false) &&
    form.value.autoDueDateDays == (lastRecord.value?.AutoDueDateDays || 0) &&
    form.value.headerColor == (lastRecord.value?.HeaderColor || '') &&
    form.value.contentColor == (lastRecord.value?.ContentColor || '') &&
    form.value.confidentialTypeId == (lastRecord.value?.ConfidentialType?.id || '') &&
    form.value.statusCategoryId == (lastRecord.value?.R_StatusCategory_ID?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/requests/request-types/${route.params.id}/duplicate`)
}

const back = () => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    router.push('/requests/request-types')
  }
}

const save = async (record) => {
  form.value = record
  setNoEdit()
  if(!noEdit.value) {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

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

  const res = await $fetch('/api/requests/request-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,
      isDefault: form.value.isDefault,
      isSelfService: form.value.isSelfService,
      dueDateTolerance: form.value.dueDateTolerance,
      isEMailWhenOverdue: form.value.isEMailWhenOverdue,
      isEMailWhenDue: form.value.isEMailWhenDue,
      isInvoiced: form.value.isInvoiced,
      isAutoChangeRequest: form.value.isAutoChangeRequest,
      isConfidentialInfo: form.value.isConfidentialInfo,
      isIndexed: form.value.isIndexed,
      autoDueDateDays: form.value.autoDueDateDays,
      headerColor: form.value.headerColor,
      contentColor: form.value.contentColor,
      confidentialTypeId: form.value.confidentialTypeId,
      statusCategoryId: form.value.statusCategoryId,
    }
  })

  if(Number(res.status) === 200) {
    /*for(let [key, items] of Object.entries(entries)) {
      for(let entry of items) {
        if(entry.id) {
          let body = {}
          if(key === 'update_notification') {
            body = {
              id: entry.id,
              userId: entry.userId,
              isActive: entry.isActive,
              isSelfService: entry.isSelfService
            }
          }

          await $fetch(`/api/requests/request-types/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'PUT',
            headers: useRequestHeaders(['cookie']),
            body
          })
        } else {
          let body = {}
          if(key === 'update_notification') {
            body = {
              organizationId: record.organizationId,
              requestTypeId: res.id,
              userId: entry.userId,
              isActive: entry.isActive,
              isSelfService: entry.isSelfService
            }
          }

          await $fetch(`/api/requests/request-types/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'POST',
            headers: useRequestHeaders(['cookie']),
            body
          })
        }
      }
    }*/
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      router.push('/requests/request-types/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
      retrieve()
    } else {
      back()
    }
  } else {
    //form.value.alert.status = res.status
    //form.value.alert.message = res.message
    form.value.alert.processing = false
    activeSave.value = 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: 'Requests'},
  { link: '/requests/request-types', text: 'Request Types'},
  { link: '#', text: 'Edit Request Type', active: true}
]))
</script>

<template>
  <Head>
    <Title>Edit Request 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.statusCategoryId === '' || form.dueDateTolerance === '' || form.confidentialTypeId === '' || 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.statusCategoryId === '' || form.dueDateTolerance === '' || form.confidentialTypeId === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.name === '' || form.statusCategoryId === '' || form.dueDateTolerance === '' || form.confidentialTypeId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Attachment</button>
          <button type="button" @click="duplicate" class="button" :class="(!noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Duplicate</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>
        <RequestsRequestTypeForm v-model="form" @save="save" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="R_RequestType" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>