<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: '',
  organization: '',
  organizationId: '',
  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,
      uid: res?.uid || '',
      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,
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false

    /*for(let record of ['tenant_info', 'tenant_share']) {
      const response = await $fetch('/api/admin/tenants/'+route.params.id+'/'+record.replaceAll('_', '-'), {
        headers: useRequestHeaders(['cookie'])
      })
      if(response) {
        let newData = []
        if(record === 'tenant_info') {
          newData = response.records.map(item => {
            return {
              id: item.uid,
              organization: item.AD_Org_ID.identifier,
              organizationId: item.AD_Org_ID.id,
              treeMenu: item.AD_Tree_Menu_ID.identifier || '',
              treeMenuId: item.AD_Tree_Menu_ID.id || '',
              treeOrg: item.AD_Tree_Org_ID.identifier || '',
              treeOrgId: item.AD_Tree_Org_ID.id || '',
              treeBPartner: item.AD_Tree_BPartner_ID.identifier || '',
              treeBPartnerId: item.AD_Tree_BPartner_ID.id || '',
              treeProject: item.AD_Tree_Project_ID.identifier || '',
              treeProjectId: item.AD_Tree_Project_ID.id || '',
              treeSalesRegion: item.AD_Tree_SalesRegion_ID.identifier || '',
              treeSalesRegionId: item.AD_Tree_SalesRegion_ID.id || '',
              treeProduct: item.AD_Tree_Product_ID.identifier || '',
              treeProductId: item.AD_Tree_Product_ID.id || '',
              isDiscountLineAmt: item.IsDiscountLineAmt ?? false,
              keepLogDays: item.KeepLogDays ?? false,
              isConfirmOnDocClose: item.IsConfirmOnDocClose ?? false,
              isConfirmOnDocVoid: item.IsConfirmOnDocVoid ?? false,
            }
          })
        }
        if(record === 'tenant_share') {
          newData = response.records.map(item => {
            return {
              id: item.uid,
              organization: item.AD_Org_ID.identifier,
              organizationId: item.AD_Org_ID.id,
              table: item.AD_Table_ID.identifier,
              tableId: item.AD_Table_ID.id,
              shareType: item.ShareType_ID.identifier,
              shareTypeId: item.ShareType_ID.id,
              name: item.name,
              description: item.description,
              isActive: item.IsActive,
            }
          })
        }

        detailRecord.value[record] = newData
      }
    }*/
  }
}
onMounted(retrieve)

const noEdit = ref(true)
const setNoEdit = () => {
  noEdit.value = (
    form.value.name == (lastRecord.value?.Name || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.value == (lastRecord.value?.Value || '') &&
    form.value.requestEMail == (lastRecord.value?.RequestEMail || '') &&
    form.value.requestFolder == (lastRecord.value?.RequestFolder || '') &&
    form.value.requestUser == (lastRecord.value?.RequestUser || '') &&
    form.value.isMultiLingualDocument == (lastRecord.value?.IsMultiLingualDocument ?? false) &&
    form.value.isSmtpAuthorization == (lastRecord.value?.IsSmtpAuthorization ?? false) &&
    form.value.isUseBetaFunctions == (lastRecord.value?.IsUseBetaFunctions ?? false) &&
    form.value.isPostImmediate == (lastRecord.value?.IsPostImmediate ?? false) &&
    form.value.isUseASP == (lastRecord.value?.IsUseASP ?? false) &&
    form.value.isSecureSMTP == (lastRecord.value?.IsSecureSMTP ?? false) &&
    form.value.languageId == (lastRecord.value?.AD_Language?.id || '') &&
    form.value.autoArchiveId == (lastRecord.value?.AutoArchive?.id || '') &&
    form.value.mMPolicyId == (lastRecord.value?.MMPolicy?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/users/tenants/${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('/users/tenants')
  }
}

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/admin/tenants/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,
      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') {
      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 breadCrumb = computed(() => ([
  { link: '/users/users', text: 'Users'},
  { link: '/users/tenants', text: 'Tenants'},
  { link: '#', text: 'Edit 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>Edit 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 === '' || 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 === '' || noEdit || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</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 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>