<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 organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')

const form = ref({
  id: '',
  uid: '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  isActive: true,
  name: '',
  description: '',
  value: '',
  requestEMail: '',
  requestFolder: '',
  requestUser: '',
  isMultiLingualDocument: false,
  isSmtpAuthorization: false,
  isUseBetaFunctions: false,
  isPostImmediate: false,
  isUseASP: false,
  isSecureSMTP: false,
  language: '',
  languageId: 'en_US',
  autoArchive: '',
  autoArchiveId: 'N',
  mMPolicy: '',
  mMPolicyId: 'F',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/admin/tenants/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: route.params.id,
      organizationId: res?.AD_Org_ID?.id || '',
      isActive: res?.IsActive ?? true,
      name: res?.Name || '',
      description: res?.Description || '',
      value: res?.Value || '',
      requestEMail: res?.RequestEMail|| '',
      requestFolder: res?.RequestFolder || '',
      requestUser: res?.RequestUser || '',
      isMultiLingualDocument: res?.IsMultiLingualDocument ?? false,
      isSmtpAuthorization: res?.IsSmtpAuthorization ?? false,
      isUseBetaFunctions: res?.IsUseBetaFunctions ?? false,
      isPostImmediate: res?.IsPostImmediate ?? false,
      isUseASP: res?.IsUseASP ?? false,
      isSecureSMTP: res?.IsSecureSMTP ?? false,
      language: res.AD_Language?.identifier || '',
      languageId: res.AD_Language?.id || '',
      autoArchive: res.AutoArchive?.identifier || '',
      autoArchiveId: res.AutoArchive?.id || '',
      mMPolicy: res.MMPolicy?.identifier || '',
      mMPolicyId: res.MMPolicy?.id || '',
      alert: {
        status: '',
        message: '',
        processing: false,
      }
    }

    setActiveSave()
  }
}
onMounted(retrieve)

const setActiveSave = () => {
  if(form.value.name !== '') {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

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('/users/tenants')
  }
}

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

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

  const res = await $fetch('/api/admin/tenants/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      name: form.value.name,
      description: form.value.description,
      value: form.value.value,
      requestEMail: form.value.requestEMail,
      requestFolder: form.value.requestFolder,
      requestUser: form.value.requestUser,
      isMultiLingualDocument: form.value.isMultiLingualDocument,
      isSmtpAuthorization: form.value.isSmtpAuthorization,
      isUseBetaFunctions: form.value.isUseBetaFunctions,
      isPostImmediate: form.value.isPostImmediate,
      isUseASP: form.value.isUseASP,
      isSecureSMTP: form.value.isSecureSMTP,
      languageId: form.value.languageId,
      autoArchiveId: form.value.autoArchiveId,
      mMPolicyId: form.value.mMPolicyId,
    }
  })

  if(Number(res.status) === 200 && res.id) {
    /*for(let [key, items] of Object.entries(entries)) {
      for(let entry of items) {
        if(entry.id) {
          let body = {}
          if(key === 'tenant_share') {
            body = {
              id: entry.id,
              organizationId: entry.organizationId,
              tableId: entry.tableId,
              shareTypeId: entry.shareTypeId,
              isActive: entry.isActive,
            }
          }

          await $fetch(`/api/admin/tenants/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'PUT',
            headers: useRequestHeaders(['cookie']),
            body
          })
        } else {
          let body = {}
          if(key === 'tenant_share') {
            body = {
              tenantId: res.id,
              organizationId: entry.organizationId,
              tableId: entry.tableId,
              shareTypeId: entry.shareTypeId,
              isActive: entry.isActive,
              isReadOnly: entry.isReadOnly
            }
          }

          await $fetch(`/api/admin/tenants/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'POST',
            headers: useRequestHeaders(['cookie']),
            body
          })
        }
      }
    }*/
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      router.push('/users/tenants/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/users/tenants/'+res.id+'/edit')
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
    } 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 breadCrumb = computed(() => ([
  { link: '/users/users', text: 'Users'},
  { link: '/users/tenants', text: 'Tenants'},
  { link: '#', text: 'Add Tenant', active: true}
]))

const tab = ref(route.query?.tab || 'basic')
const tabs = computed(() => ([
  { value: 'basic', text: 'Basic'},
  { value: 'request', text: 'Request Management'},
  { value: 'technical', text: 'Technical'}
]))
</script>

<template>
  <Head>
    <Title>Add Tenant</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>
      </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="d-flex justify-between mb-3">
        <InsideWindowTab v-model="tab" :tabs="tabs" />
      </div>
      <div>
        <AdminTenantForm v-model="form" :tab="tab" @save="save" />
      </div>
    </div>
  </NuxtLayout>
</template>