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

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

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

const client = useCookie('logship_client')
const clientId = useCookie('logship_client_id')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')

const form = ref({
  id: '',
  uid: '',
  client: client.value?.Name || '',
  clientId: clientId.value || '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  isActive: true,
  name: '',
  description: '',
  password: '',
  eMail: '',
  isFullBPAccess: false,
  value: '',
  isInPayroll: false,
  isSalesLead: false,
  isLocked: false,
  failedLoginCount: 0,
  isNoPasswordReset: false,
  isExpired: false,
  isAddMailTextAutomatically: false,
  isNoExpire: false,
  isSupportUser: false,
  isShipTo: false,
  isBillTo: false,
  isVendorLead: false,
  eMailUser: '',
  phone2: '',
  birthday: date.now('date'),
  phone: '',
  fax: '',
  lastResult: '',
  lastContact: date.now('date'),
  title: '',
  comments: '',
  eMailVerify: 0,
  eMailVerifyDate: '',
  LDAPUser: '',
  datePasswordChanged: '',
  supervisor: '',
  supervisorId: '',
  partner: '',
  partnerId: '',
  notificationType: 'X',
  notificationTypeId: 'X',
  greeting: '',
  greetingId: '',
  partnerLocation: '',
  partnerLocationId: '',
  orgTrx: '',
  orgTrxId: '',
  job: '',
  jobId: '',
  isMenuAutoExpand: '',
  isMenuAutoExpandId: '',
  mailText: '',
  mailTextId: '',
  image: '',
  imageData: '',
  imageId: '',
  isSystemUser: true,
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const openTab = (toPath, pathName, oldPath = null) => {
  let comparePath = toPath
  if(oldPath) {
    comparePath = oldPath
  }
  tabs.value.map(item => {
    item.active = false
    return item
  })
  if(tabs.value.filter(i => i.link === comparePath).length >= 1) {
    const tabIndex = tabs.value.findIndex(i => i.link === comparePath)
    tabs.value[tabIndex].active = true
    if(oldPath) {
      tabs.value[tabIndex].link = toPath
      tabs.value[tabIndex].text = pathName
    }
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  } else {
    tabs.value.push({link: toPath, text: pathName, active: true})
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  }
  //location.href = toPath
}

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/users')
    openTab('/users/users', 'Users')
  }
}

const save = async (record) => {
  form.value = record
  
  if(form.value.name !== '' && form.value.notificationTypeId !== '') {
    activeSave.value = true
  } else {
    activeSave.value = false
  }

  if(form.value.image.includes(';base64,')) {
    const base64Val = form.value.image.split(',')[1]
    if(base64Val) {
      form.value.imageData = base64Val
    }
  }
}

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

  const res = await $fetch('/api/admin/users/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      name: form.value.name,
      description: form.value.description,
      password: form.value.password,
      eMail: form.value.eMail,
      isFullBPAccess: form.value.isFullBPAccess,
      value: form.value.value,
      isInPayroll: form.value.isInPayroll,
      isSalesLead: form.value.isSalesLead,
      isLocked: form.value.isLocked,
      failedLoginCount: form.value.failedLoginCount,
      isNoPasswordReset: form.value.isNoPasswordReset,
      isExpired: form.value.isExpired,
      isAddMailTextAutomatically: form.value.isAddMailTextAutomatically,
      isNoExpire: form.value.isNoExpire,
      isSupportUser: form.value.isSupportUser,
      isShipTo: form.value.isShipTo,
      isBillTo: form.value.isBillTo,
      isVendorLead: form.value.isVendorLead,
      eMailUser: form.value.eMailUser,
      phone2: form.value.phone2,
      birthday: form.value.birthday,
      phone: form.value.phone,
      fax: form.value.fax,
      lastResult: form.value.lastResult,
      lastContact: form.value.lastContact,
      title: form.value.title,
      comments: form.value.comments,
      eMailVerify: form.value.eMailVerify,
      eMailVerifyDate: form.value.eMailVerifyDate,
      LDAPUser: form.value.LDAPUser,
      datePasswordChanged: form.value.datePasswordChanged,
      supervisorId: form.value.supervisorId,
      partnerId: form.value.partnerId,
      notificationTypeId: form.value.notificationTypeId,
      greetingId: form.value.greetingId,
      partnerLocationId: form.value.partnerLocationId,
      orgTrxId: form.value.orgTrxId,
      jobId: form.value.jobId,
      isMenuAutoExpandId: form.value.isMenuAutoExpandId,
      mailTextId: form.value.mailTextId,
      image: form.value.image,
      imageData: form.value.imageData,
      imageId: form.value.imageId,
      isSystemUser: form.value.isSystemUser,
    }
  })

  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 === 'user_roles') {
            body = {
              id: entry.id,
              roleId: entry.roleId,
              isActive: entry.isActive
            }
          } else if(key === 'user_substitute') {
            body = {
              id: entry.id,
              substituteId: entry.substituteId,
              name: entry.name,
              description: entry.description,
              validFrom: entry.validFrom,
              validTo: entry.validTo,
              isActive: entry.isActive
            }
          } else if(key === 'user_orgaccess') {
            body = {
              id: entry.id,
              organizationId: entry.organizationId,
              isActive: entry.isActive,
              isReadOnly: entry.isReadOnly
            }
          } else if(key === 'user_mail') {
            body = {
              id: entry.id,
              messageID: entry.messageID,
              subject: entry.subject,
              mailText: entry.mailText,
              isDeliveredId: entry.isDeliveredId || 'N',
              isActive: entry.isActive,
            }
          } else if(key === 'user_query') {
            body = {
              id: entry.id,
              tableId: entry.tableId,
              tabId: entry.tabId,
              windowId: entry.windowId,
              name: entry.name,
              code: entry.code,
              isActive: entry.isActive,
              isDefault: entry.isDefault,
            }
          } else if(key === 'document_status_access') {
            body = {
              id: entry.id,
              roleId: entry.roleId,
              documentStatusId: entry.documentStatusId,
              isActive: entry.isActive,
            }
          }

          await $fetch(`/api/admin/users/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'PUT',
            headers: useRequestHeaders(['cookie']),
            body
          })
        } else {
          let body = {}
          if(key === 'user_roles') {
            body = {
              organizationId: record.organizationId,
              userId: res.id,
              roleId: entry.roleId,
              isActive: entry.isActive
            }
          } else if(key === 'user_substitute') {
            body = {
              organizationId: record.organizationId,
              userId: res.id,
              substituteId: entry.substituteId,
              name: entry.name,
              description: entry.description,
              validFrom: entry.validFrom,
              validTo: entry.validTo,
              isActive: entry.isActive
            }
          } else if(key === 'user_orgaccess') {
            body = {
              userId: res.id,
              organizationId: entry.organizationId,
              isActive: entry.isActive,
              isReadOnly: entry.isReadOnly
            }
          } else if(key === 'user_mail') {
            body = {
              userId: res.id,
              organizationId: record.organizationId,
              messageID: entry.messageID,
              subject: entry.subject,
              mailText: entry.mailText,
              isDeliveredId: entry.isDeliveredId || 'N',
              isActive: entry.isActive,
            }
          } else if(key === 'user_query') {
            body = {
              userId: res.id,
              organizationId: record.organizationId,
              tableId: entry.tableId,
              tabId: entry.tabId,
              windowId: entry.windowId,
              name: entry.name,
              code: entry.code,
              isActive: entry.isActive,
              isDefault: entry.isDefault,
            }
          } else if(key === 'document_status_access') {
            body = {
              userId: res.id,
              organizationId: record.organizationId,
              roleId: entry.roleId,
              documentStatusId: entry.documentStatusId,
              isActive: entry.isActive,
            }
          }

          await $fetch(`/api/admin/users/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'POST',
            headers: useRequestHeaders(['cookie']),
            body
          })
        }
      }
    }*/
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      //router.push('/users/users/'+res.id+'/view')
      openTab('/view/user-'+res.id, 'User: View Details', '/create/user')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      //router.push('/users/users/'+res.id+'/edit')
      openTab('/edit/user-'+res.id, 'User: '+res.Name, '/create/user')
      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: '#', text: 'Add User', active: true}
]))

const tab = ref(route.query?.tab || 'contact')
const tabs2 = computed(() => ([
  { value: 'contact', text: 'User Contact'},
  { value: 'internal', text: 'Internal'},
  { value: 'external', text: 'External'},
  { value: 'locking', text: 'User Locking'}
]))
</script>

<template>
  <Head>
    <Title>Add User</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.notificationTypeId === '' || 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="tabs2" />
      </div>
      <div>
        <AdminUserForm v-model="form" v-model:tab="tab" @save="save"/>
      </div>
      <div class="opacity-0.6 pointerEvents-none">
        <AdminUserDetailRecord action="create" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>