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

const router = useRouter()
const route = useRoute()
const user = useCookie('logship_user')

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

const form = ref({
  id: '',
  organizationId: '',
  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: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  let userProfile = user.value
  if(userProfile) {
    const userProfileStorage = localStorage.getItem('idempiere_user')
    if(userProfileStorage) {
      userProfile = JSON.parse(userProfileStorage)
    }
  }
  if(userProfile) {
    const res = await $fetch('/api/admin/users/'+userProfile.id, {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      form.value = {
        id: res?.id,
        organizationId: res?.AD_Org_ID?.id || '',
        isActive: res?.IsActive ?? true,
        name: res?.Name || '',
        description: res?.Description || '',
        password: res?.Password || '',
        eMail: res?.EMail || '',
        isFullBPAccess: res?.IsFullBPAccess ?? false,
        value: res?.Value || '',
        isInPayroll: res?.IsInPayroll ?? false,
        isSalesLead: res?.IsSalesLead ?? false,
        isLocked: res?.IsLocked ?? false,
        failedLoginCount: res?.FailedLoginCount || 0,
        isNoPasswordReset: res?.IsNoPasswordReset ?? false,
        isExpired: res?.IsExpired ?? false,
        isEditMailTextAutomatically: res?.IsEditMailTextAutomatically ?? false,
        isNoExpire: res?.IsNoExpire ?? false,
        isSupportUser: res?.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: res?.LastContact || date.now('date'),
        title: res?.Title || '',
        comments: res?.Comments || '',
        eMailVerify: res?.EMailVerify || 0,
        eMailVerifyDate: res?.EMailVerifyDate || '',
        LDAPUser: res?.LDAPUser || '',
        datePasswordChanged: res?.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 || '',
        processing: false,
        alert: {
          status: '',
          message: '',
          processing: false
        }
      }
    }
  }
}
onMounted(retrieve)

const back = () => {
  router.push('/users/users')
}

const save = async (record) => {
  form.value = record
  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

  const res = await $fetch('/api/admin/users/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,
      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 ?? false,
      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,
    }
  })

  if(Number(res.status) === 200) {
    if(saveType === 'preview') {
      router.push('/users/users/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      //router.push('/users/profile')
      form.value.alert.processing = false
      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
    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: 'User Profile', active: true}
]))

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

<template>
  <Head>
    <Title>User Profile</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>
        <!--<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 class="banner datatable-wrapper">
      <div class="d-flex justify-between mb-3">
        <InsideWindowTab v-model="tab" :tabs="tabs" />
      </div>
      <div>
        <DashboardProfileForm v-model="form" v-model:tab="tab" @save="save"/>
      </div>
      <div>
        <DashboardProfileDetailRecord action="edit" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>