<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 lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  isActive: true,
  name: '',
  description: '',
  password: '',
  eMail: '',
  isFullBPAccess: false,
  value: '',
  isInPayroll: false,
  isSalesLead: false,
  isLocked: false,
  failedLoginCount: 0,
  isNoPasswordReset: false,
  isExpired: false,
  isEditMailTextAutomatically: 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: '',
  notificationTypeId: '',
  greeting: '',
  greetingId: '',
  partnerLocation: '',
  partnerLocationId: '',
  orgTrx: '',
  orgTrxId: '',
  job: '',
  jobId: '',
  isMenuAutoExpand: '',
  isMenuAutoExpandId: '',
  mailText: '',
  mailTextId: '',
  image: '',
  imageData: '',
  imageId: '',
  location: '',
  locationId: '',
  campaign: '',
  campaignId: '',
  leadSource: '',
  leadSourceId: '',
  leadStatus: '',
  leadStatusId: '',
  leadSourceDescription: '',
  leadStatusDescription: '',
  companyname: '',
  URL: '',
  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: route.params.id,
      uid: res?.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: 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 || '',
      image: '',
      imageData: res?.AD_Image_ID?.data || '',
      imageId: res?.AD_Image_ID?.id || '',
      location: res?.C_Location_ID?.identifier || '',
      locationId: res?.C_Location_ID?.id || '',
      campaign: res?.C_Campaign_ID?.identifier || '',
      campaignId: res?.C_Campaign_ID?.id || '',
      leadSource: res?.LeadSource?.identifier || '',
      leadSourceId: res?.LeadSource?.id || '',
      leadStatus: res?.LeadStatus?.identifier || '',
      leadStatusId: res?.LeadStatus?.id || '',
      leadSourceDescription: res?.LeadSourceDescription || '',
      leadStatusDescription: res?.LeadStatusDescription || '',
      companyname: res?.companyname || '',
      URL: res?.URL || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false
  }
}
onMounted(retrieve)

const noEdit = ref(true)
const setNoEdit = () => {
  noEdit.value = (
    form.value.organizationId == (lastRecord.value?.AD_Org_ID?.id || '') &&
    form.value.name == (lastRecord.value?.Name || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.password == (lastRecord.value?.Password || '') &&
    form.value.eMail == (lastRecord.value?.EMail || '') &&
    form.value.isFullBPAccess == (lastRecord.value?.IsFullBPAccess ?? false) &&
    form.value.value == (lastRecord.value?.Value || '') &&
    form.value.isInPayroll == (lastRecord.value?.IsInPayroll ?? false) &&
    form.value.isSalesLead == (lastRecord.value?.IsSalesLead ?? false) &&
    form.value.isLocked == (lastRecord.value?.IsLocked ?? false) &&
    form.value.failedLoginCount == (lastRecord.value?.FailedLoginCount || 0) &&
    form.value.isNoPasswordReset == (lastRecord.value?.IsNoPasswordReset ?? false) &&
    form.value.isExpired == (lastRecord.value?.IsExpired ?? false) &&
    form.value.isEditMailTextAutomatically == (lastRecord.value?.IsEditMailTextAutomatically ?? false) &&
    form.value.isNoExpire == (lastRecord.value?.IsNoExpire ?? false) &&
    form.value.isSupportUser == (lastRecord.value?.IsSupportUser ?? false) &&
    form.value.isShipTo == (lastRecord.value?.IsShipTo ?? false) &&
    form.value.isBillTo == (lastRecord.value?.IsBillTo ?? false) &&
    form.value.isVendorLead == (lastRecord.value?.IsVendorLead ?? false) &&
    form.value.eMailUser == (lastRecord.value?.EMailUser || '') &&
    form.value.phone2 == (lastRecord.value?.Phone2 || '') &&
    form.value.birthday == (lastRecord.value?.Birthday || date.now('date')) &&
    form.value.phone == (lastRecord.value?.Phone || '') &&
    form.value.fax == (lastRecord.value?.Fax || '') &&
    form.value.lastResult == (lastRecord.value?.LastResult || '') &&
    form.value.lastContact == (lastRecord.value?.LastContact || date.now('date')) &&
    form.value.title == (lastRecord.value?.Title || '') &&
    form.value.comments == (lastRecord.value?.Comments || '') &&
    form.value.eMailVerify == (lastRecord.value?.EMailVerify || 0) &&
    form.value.eMailVerifyDate == (lastRecord.value?.EMailVerifyDate || '') &&
    form.value.LDAPUser == (lastRecord.value?.LDAPUser || '') &&
    form.value.datePasswordChanged == (lastRecord.value?.DatePasswordChanged || '') &&
    form.value.supervisorId == (lastRecord.value?.Supervisor_ID?.id || '') &&
    form.value.partnerId == (lastRecord.value?.C_BPartner_ID?.id || '') &&
    form.value.notificationTypeId == (lastRecord.value?.NotificationType?.id || '') &&
    form.value.greetingId == (lastRecord.value?.C_Greeting_ID?.id || '') &&
    form.value.partnerLocationId == (lastRecord.value?.C_BPartner_Location_ID?.id || '') &&
    form.value.orgTrxId == (lastRecord.value?.AD_OrgTrx_ID?.id || '') &&
    form.value.jobId == (lastRecord.value?.C_Job_ID?.id || '') &&
    form.value.isMenuAutoExpandId == (lastRecord.value?.IsMenuAutoExpand?.id || '') &&
    form.value.mailTextId == (lastRecord.value?.R_DefaultMailText_ID?.id || '') &&
    form.value.imageData == (lastRecord.value?.AD_Image_ID?.data || '') &&
    form.value.imageId == (lastRecord.value?.AD_Image_ID?.id || '') && 
    form.value.locationId == (lastRecord.value?.C_Location_ID?.id || '') && 
    form.value.campaignId == (lastRecord.value?.C_Campaign_ID?.id || '') && 
    form.value.leadSourceId == (lastRecord.value?.LeadSource?.id || '') && 
    form.value.leadStatusId == (lastRecord.value?.LeadStatus?.id || '') && 
    form.value.leadSourceDescription == (lastRecord.value?.LeadSourceDescription || '') && 
    form.value.leadStatusDescription == (lastRecord.value?.LeadStatusDescription || '') &&
    form.value.companyname == (lastRecord.value?.companyname || '') &&
    form.value.URL == (lastRecord.value?.URL || '')

) ? true : 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 duplicate = () => {
  //router.push(`/users/leads/${route.params.id}/duplicate`)
  openTab('/duplicate/lead-'+route.params.id, 'Lead: 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/leads')
    openTab('/users/leads', 'Leads')
  }
}

const save = async (record) => {
  form.value = record
  setNoEdit()
  if(!noEdit.value) {
    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/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,
      isEditMailTextAutomatically: form.value.isEditMailTextAutomatically,
      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.imageData,
      imageId: form.value.imageId,
      locationId: form.value.locationId,
      campaignId: form.value.campaignId,
      leadSourceId: form.value.leadSourceId,
      leadStatusId: form.value.leadStatusId,
      leadSourceDescription: form.value.leadSourceDescription,
      leadStatusDescription: form.value.leadStatusDescription,
      companyname: form.value.companyname,
      URL: form.value.URL,
    }
  })

  if(Number(res.status) === 200) {
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      //router.push('/users/leads/'+res.id+'/view')
      openTab('/view/lead-'+res.id, 'Lead: View Details')
    } 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 showAttachment = ref(false)

const breadCrumb = computed(() => ([
  { link: '/users/users', text: 'Users'},
  { link: '/users/leads', text: 'Leads'},
  { link: '#', text: 'Edit Lead', active: true}
]))

const tab = ref(route.query?.tab || 'basic')
const tabs2 = computed(() => ([
  { value: 'basic', text: 'Basic'},
  { value: 'reference', text: 'Reference'},
]))
</script>

<template>
  <Head>
    <Title>Edit Lead</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="showAttachment = true" class="button" :class="(form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Attachment</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="tabs2" />
        </div>
        <div>
          <AdminLeadForm v-model="form" v-model:tab="tab" @save="save" />
        </div>
        <div>
          <AdminLeadDetailRecord action="edit" :info="form" />
        </div>
        <div>
          <AttachmentModal v-model="showAttachment" target="Lead_User" :info="form" />
        </div>
      </div>
  </NuxtLayout>
</template>