<script>
import UserAction from '../../../components/admin/UserAction.vue'

export default {
  components: {
    UserAction
  }
}
</script>

<script setup>
const router = useRouter()
const tabs = useTabs()

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

const isDeletable = ref(false)
const searchQuery = ref('')
const selectedRows = ref([])

const { data, pending, error, refresh } = await useFetch('/api/admin/users/internal-users', {
  headers: useRequestHeaders(['cookie'])
})

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    isActive: item.IsActive,
    name: item.Name,
    description: item.Description,
    eMail: item.EMail,
    isFullBPAccess: item.IsFullBPAccess,
    value: item.Value,
    isInPayroll: item.IsInPayroll,
    isSalesLead: item.IsSalesLead,
    isLocked: item.IsLocked,
    failedLoginCount: item.FailedLoginCount,
    isNoPasswordReset: item.IsNoPasswordReset,
    isExpired: item.IsExpired,
    isAddMailTextAutomatically: item.IsAddMailTextAutomatically,
    isNoExpire: item.IsNoExpire,
    isSupportUser: item.IsSupportUser,
    isShipTo: item.IsShipTo,
    isBillTo: item.IsBillTo,
    isVendorLead: item.IsVendorLead,
    eMailUser: item.EMailUser,
    phone2: item.Phone2,
    birthday: item.Birthday,
    phone: item.Phone,
    fax: item.Fax,
    lastResult: item.LastResult,
    lastContact: item.LastContact,
    title: item.Title,
    comments: item.Comments,
    eMailVerify: item.EMailVerify,
    eMailVerifyDate: item.EMailVerifyDate,
    LDAPUser: item.LDAPUser,
    isLocked: item.IsLocked,
    datePasswordChanged: item.datePasswordChanged,
    supervisor: item.Supervisor_ID?.identifier || '',
    supervisorId: item.Supervisor_ID?.id || '',
    partner: item.C_BPartner_ID?.identifier || '',
    partnerId: item.C_BPartner_ID?.id || '',
    notificationType: item.NotificationType?.identifier || '',
    notificationTypeId: item.NotificationType?.id || '',
    greeting: item.C_Greeting_ID?.identifier || '',
    greetingId: item.C_Greeting_ID?.id || '',
    partnerLocation: item.C_BPartner_Location_ID?.identifier || '',
    partnerLocationId: item.C_BPartner_Location_ID?.id || '',
    orgTrx: item.AD_OrgTrx_ID?.identifier || '',
    orgTrxId: item.AD_OrgTrx_ID?.id || '',
    job: item.C_Job_ID?.identifier || '',
    jobId: item.C_Job_ID?.id || '',
    isMenuAutoExpand: item.IsMenuAutoExpand?.identifier || '',
    isMenuAutoExpandId: item.IsMenuAutoExpand?.id || '',
    mailText: item.R_DefaultMailText_ID?.identifier || '',
    mailTextId: item.R_DefaultMailText_ID?.id || '',
    organization: item.AD_Org_ID?.identifier || '',
    organizationId: item.AD_Org_ID?.id || ''
  }
}) || []);

const forcingLogout = async () => {
  await $fetch('/api/idempiere-auth/logout', {
    method: 'POST',
    headers: useRequestHeaders(['cookie'])
  })

  tabs.value = [{link: '/', text: 'Home', active: true}]
  localStorage.setItem('tabs', JSON.stringify(tabs.value))

  console.info('Session expired and it will auto redirected toward login page.')
  location.href = '/signin'
}
const alert = ref({
  status: data.value?.status || 200,
  message: data.value?.message || ''
});
onBeforeMount(() => {
  if(Number(data.value?.status || 200) === 401) {
    forcingLogout()
  }
})
watch(data, () => {
  alert.value.status = data.value?.status || 200
  alert.value.message = data.value?.message || ''
  if(Number(data.value?.status || 200) === 401) {
    forcingLogout()
  }
})

const checkboxSelection = (params) => {
  return params.api.getRowGroupColumns().length === 0;
};
const headerCheckboxSelection = (params) => {
  return params.api.getRowGroupColumns().length === 0;
};

const colDefs = ref([
  { 
    width: 50,
    checkboxSelection: checkboxSelection,
    headerCheckboxSelection: headerCheckboxSelection
  },
  { 
    field: 'id',
    //hide: true,
    sort: 'desc'
  },
  { 
    field: 'name',
  },
  { 
    field: 'organization',
    type: 'nonEditableColumn' 
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'eMail',
    headerName: 'Email'
  },
  { 
    field: 'isFullBPAccess',
    headerName: 'Full Partner Access'
  },
  { 
    field: 'isInPayroll',
    headerName: 'In Payroll'
  },
  { 
    field: 'phone',
    headerName: 'Phone'
  },
  { 
    field: 'action',
    width: 100,
    pinned: 'right',
    type: 'nonEditableColumn',
    cellRenderer: UserAction
  }
]);

const cellClick = (event, gridApi) => {
  selectedRows.value = gridApi.getSelectedRows()

  if(event.source === 'checkboxSelected') {
    isDeletable.value = false
    if(selectedRows.value.length >= 1) {
      isDeletable.value = true
    }
  }
}

const cellChange = async (event) => {
  const res = await $fetch('/api/admin/users/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      isActive: event.data.isActive,
      name: event.data.name,
      description: event.data.description,
      eMail: event.data.eMail,
      isFullBPAccess: event.data.isFullBPAccess,
      value: event.data.value,
      isInPayroll: event.data.isInPayroll,
      isSalesLead: event.data.isSalesLead,
      isLocked: event.data.isLocked,
      failedLoginCount: event.data.failedLoginCount,
      isNoPasswordReset: event.data.isNoPasswordReset,
      isExpired: event.data.isExpired,
      isAddMailTextAutomatically: event.data.isAddMailTextAutomatically,
      isNoExpire: event.data.isNoExpire,
      isSupportUser: event.data.isSupportUser,
      isShipTo: event.data.isShipTo,
      isBillTo: event.data.isBillTo,
      isVendorLead: event.data.isVendorLead,
      eMailUser: event.data.eMailUser,
      phone2: event.data.phone2,
      birthday: event.data.birthday,
      phone: event.data.phone,
      fax: event.data.fax,
      lastResult: event.data.lastResult,
      lastContact: event.data.lastContact,
      title: event.data.title,
      comments: event.data.comments,
      eMailVerify: event.data.eMailVerify,
      eMailVerifyDate: event.data.eMailVerifyDate,
      LDAPUser: event.data.LDAPUser,
      isLocked: event.data.isLocked,
      datePasswordChanged: event.data.datePasswordChanged
    }
  })

  if(Number(res.status) >= 400) {
    alert.value.status = res.status
    alert.value.message = res.message
  }
}

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

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 create = () => {
  //router.push('/users/users/create')
  openTab('/create/user', 'User: New')
}

const destroy = async () => {
  if(selectedRows.value.length >= 1) {
    isDeletable.value = false

    const res = await $fetch('/api/admin/users/destroy', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie']),
      body: {
        ids: selectedRows.value.map(i => i.id)
      }
    })

    if(Number(res.status) >= 400) {
      alert.value.status = res.status
      alert.value.message = res.message
    }

    refresh()
  }
}
</script>

<template>
  <Head>
    <Title>Users</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <div class="banner datatable-wrapper">
      <HeaderAction :isDeletable="isDeletable" @create="create" @destroy="destroy" />
      <div>
        <div>
          <AlertBox :alert="alert" />
          <div class="mb-3">
            <AgGrid :entries="rowData" :columns="colDefs" @cellClick="cellClick" @cellChange="cellChange" />
          </div>
        </div>
      </div>
    </div>
  </NuxtLayout>
</template>