<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: false,
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/admin/users/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: '',
      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: true,
      name: res?.Name || '',
      description: res?.Description || '',
      password: res?.Password || '',
      eMail: res?.EMail || '',
      isFullBPAccess: res?.IsFullBPAccess ?? false,
      value: '',
      isInPayroll: res?.IsInPayroll ?? false,
      isSalesLead: res?.IsSalesLead ?? false,
      isLocked: false,
      failedLoginCount: 0,
      isNoPasswordReset: false,
      isExpired: false,
      isEditMailTextAutomatically: res?.IsEditMailTextAutomatically ?? false,
      isNoExpire: false,
      isSupportUser: false,
      isShipTo: res?.IsShipTo ?? false,
      isBillTo: res?.IsBillTo ?? false,
      isVendorLead: res?.IsVendorLead ?? false,
      eMailUser: res?.EMailUser || '',
      phone2: res?.Phone2 || '',
      birthday: res?.Birthday || date.now('date'),
      phone: res?.Phone || '',
      fax: res?.Fax || '',
      lastResult: res?.LastResult || '',
      lastContact: date.now('date'),
      title: res?.Title || '',
      comments: res?.Comments || '',
      eMailVerify: 0,
      eMailVerifyDate: '',
      LDAPUser: res?.LDAPUser || '',
      datePasswordChanged: '',
      supervisor: res?.Supervisor_ID?.identifier || '',
      supervisorId: res?.Supervisor_ID?.id || '',
      partner: res?.C_BPartner_ID?.identifier || '',
      partnerId: res?.C_BPartner_ID?.id || '',
      notificationType: res?.NotificationType?.identifier || '',
      notificationTypeId: res?.NotificationType?.id || '',
      greeting: res?.C_Greeting_ID?.identifier || '',
      greetingId: res?.C_Greeting_ID?.id || '',
      partnerLocation: res?.C_BPartner_Location_ID?.identifier || '',
      partnerLocationId: res?.C_BPartner_Location_ID?.id || '',
      orgTrx: res?.AD_OrgTrx_ID?.identifier || '',
      orgTrxId: res?.AD_OrgTrx_ID?.id || '',
      job: res?.C_Job_ID?.identifier || '',
      jobId: res?.C_Job_ID?.id || '',
      isMenuAutoExpand: res?.IsMenuAutoExpand?.identifier || '',
      isMenuAutoExpandId: res?.IsMenuAutoExpand?.id || '',
      mailText: res?.R_DefaultMailText_ID?.identifier || '',
      mailTextId: res?.R_DefaultMailText_ID?.id || '',
      imageData: res?.AD_Image_ID?.data || '',
      imageId: res?.AD_Image_ID?.id || '',
      isSystemUser: res?.IsSystemUser ?? false,
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }

    setActiveSave()
  }
}
onMounted(retrieve)

const setActiveSave = () => {
  if(form.value.name !== '' && form.value.notificationTypeId !== '') {
    activeSave.value = true
  } else {
    activeSave.value = 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/external-users', 'External Users')
  }
}

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

  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) {
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      //router.push('/users/users/'+res.id+'/view')
      openTab('/view/external-user-'+res.id, 'External User: View Details', '/duplicate/external-user-'+res.id)
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      //router.push('/users/users/'+res.id+'/edit')
      openTab('/edit/external-user-'+res.id, 'External User: '+res.Name, '/duplicate/external-user-'+res.id)
      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/external-users', text: 'External 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>