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

export default {
  components: {
    RoleAction
  }
}
</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/roles', {
  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,
    amtApproval: item.AmtApproval,
    isManual: item.IsManual,
    isPersonalAccess: item.IsPersonalAccess,
    isShowAcct: item.IsShowAcct,
    isPersonalLock: item.IsPersonalLock,
    isCanReport: item.IsCanReport,
    isCanExport: item.IsCanExport,
    isCanApproveOwnDoc: item.IsCanApproveOwnDoc,
    isAccessAllOrgs: item.IsAccessAllOrgs,
    isChangeLog: item.IsChangeLog,
    overwritePriceLimit: item.OverwritePriceLimit,
    isUseUserOrgAccess: item.IsUseUserOrgAccess,
    confirmQueryRecords: item.ConfirmQueryRecords,
    maxQueryRecords: item.MaxQueryRecords,
    allow_Info_Account: item.Allow_Info_Account,
    allow_Info_Asset: item.Allow_Info_Asset,
    allow_Info_BPartner: item.Allow_Info_BPartner,
    allow_Info_InOut: item.Allow_Info_InOut,
    allow_Info_Invoice: item.Allow_Info_Invoice,
    allow_Info_Order: item.Allow_Info_Order,
    allow_Info_Payment: item.Allow_Info_Payment,
    allow_Info_Product: item.Allow_Info_Product,
    allow_Info_Resource: item.Allow_Info_Resource,
    allow_Info_Schedule: item.Allow_Info_Schedule,
    isDiscountUptoLimitPrice: item.IsDiscountUptoLimitPrice,
    isDiscountAllowedOnTotal: item.IsDiscountAllowedOnTotal,
    isMenuAutoExpand: item.IsMenuAutoExpand,
    isMasterRole: item.IsMasterRole,
    isAccessAdvanced: item.IsAccessAdvanced,
    isClientAdministrator: item.IsClientAdministrator,
    userLevel: item.UserLevel?.identifier || '',
    userLevelId: item.UserLevel?.id || '',
    currency: item.C_Currency_ID?.identifier || '',
    currencyId: item.C_Currency_ID?.id || '',
    preferenceType: item.PreferenceType?.identifier || '',
    preferenceTypeId: item.PreferenceType?.id || '',
    treeMenu: item.AD_Tree_Menu_ID?.identifier || '',
    treeMenuId: item.AD_Tree_Menu_ID?.id || '',
    roleType: item.RoleType?.identifier || '',
    roleTypeId: item.RoleType?.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: 'organization',
    type: 'nonEditableColumn' 
  },
  { 
    field: 'name',
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'description',
    headerName: 'Description'
  },
  { 
    field: 'amtApproval',
    headerName: 'Amount Approval'
  },
  { 
    field: 'userLevel',
    headerName: 'User Level',
    type: 'nonEditableColumn'
  },
  { 
    field: 'roleType',
    headerName: 'Role Type',
    type: 'nonEditableColumn'
  },
  { 
    field: 'action',
    width: 100,
    pinned: 'right',
    type: 'nonEditableColumn',
    cellRenderer: RoleAction
  },
]);

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/roles/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      isActive: event.data.isActive,
      name: event.data.name,
      description: event.data.description,
      amtApproval: event.data.amtApproval,
      isManual: event.data.isManual,
      isPersonalAccess: event.data.isPersonalAccess,
      isShowAcct: event.data.isShowAcct,
      isPersonalLock: event.data.isPersonalLock,
      isCanReport: event.data.isCanReport,
      isCanExport: event.data.isCanExport,
      isCanApproveOwnDoc: event.data.isCanApproveOwnDoc,
      isAccessAllOrgs: event.data.isAccessAllOrgs,
      isChangeLog: event.data.isChangeLog,
      overwritePriceLimit: event.data.overwritePriceLimit,
      isUseUserOrgAccess: event.data.isUseUserOrgAccess,
      confirmQueryRecords: event.data.confirmQueryRecords,
      maxQueryRecords: event.data.maxQueryRecords,
      allow_Info_Account: event.data.allow_Info_Account,
      allow_Info_Asset: event.data.allow_Info_Asset,
      allow_Info_BPartner: event.data.allow_Info_BPartner,
      allow_Info_InOut: event.data.allow_Info_InOut,
      allow_Info_Invoice: event.data.allow_Info_Invoice,
      allow_Info_Order: event.data.allow_Info_Order,
      allow_Info_Payment: event.data.allow_Info_Payment,
      allow_Info_Product: event.data.allow_Info_Product,
      allow_Info_Resource: event.data.allow_Info_Resource,
      allow_Info_Schedule: event.data.allow_Info_Schedule,
      isDiscountUptoLimitPrice: event.data.isDiscountUptoLimitPrice,
      isDiscountAllowedOnTotal: event.data.isDiscountAllowedOnTotal,
      isMenuAutoExpand: event.data.isMenuAutoExpand,
      isMasterRole: event.data.isMasterRole,
      isAccessAdvanced: event.data.isAccessAdvanced,
      isClientAdministrator: event.data.isClientAdministrator
    }
  })

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

const breadCrumb = computed(() => ([
  { link: '/users/users', text: 'Users'},
  { link: '/users/roles', text: 'Roles', 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/roles/create')
  openTab('/create/role', 'Role: New')
}

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

    const res = await $fetch('/api/admin/roles/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>Roles</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>