<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: '',
  amtApproval: 0,
  isManual: false,
  isPersonalAccess: false,
  isShowAcct: false,
  isPersonalLock: false,
  isCanReport: false,
  isCanExport: false,
  isCanApproveOwnDoc: false,
  isAccessAllOrgs: false,
  isChangeLog: false,
  overwritePriceLimit: false,
  isUseUserOrgAccess: false,
  confirmQueryRecords: 0,
  maxQueryRecords: 0,
  allow_Info_Account: false,
  allow_Info_Asset: false,
  allow_Info_BPartner: false,
  allow_Info_InOut: false,
  allow_Info_Invoice: false,
  allow_Info_Order: false,
  allow_Info_Payment: false,
  allow_Info_Product: false,
  allow_Info_Resource: false,
  allow_Info_Schedule: false,
  isDiscountUptoLimitPrice: false,
  isDiscountAllowedOnTotal: false,
  isMenuAutoExpand: false,
  isMasterRole: false,
  isAccessAdvanced: false,
  isClientAdministrator: false,
  amtApprovalAccum: 0,
  daysApprovalAccum: 0,
  userLevel: 'Client+Organization',
  userLevelId: ' CO',
  currency: '',
  currencyId: '',
  preferenceType: 'None',
  preferenceTypeId: 'N',
  treeMenu: '',
  treeMenuId: '',
  roleType: '',
  roleTypeId: '',
  treeOrg: '',
  treeOrgId: '',
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/admin/roles/'+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 || '',
      amtApproval: res.AmtApproval || 0,
      isManual: res.IsManual ?? false,
      isPersonalAccess: res.IsPersonalAccess ?? false,
      isShowAcct: res.IsShowAcct ?? false,
      isPersonalLock: res.IsPersonalLock ?? false,
      isCanReport: res.IsCanReport ?? false,
      isCanExport: res.IsCanExport ?? false,
      isCanApproveOwnDoc: res.IsCanApproveOwnDoc ?? false,
      isAccessAllOrgs: res.IsAccessAllOrgs ?? false,
      isChangeLog: res.IsChangeLog ?? false,
      overwritePriceLimit: res.OverwritePriceLimit ?? false,
      isUseUserOrgAccess: res.IsUseUserOrgAccess ?? false,
      confirmQueryRecords: res.ConfirmQueryRecords || 0,
      maxQueryRecords: res.MaxQueryRecords || 0,
      allow_Info_Account: res.Allow_Info_Account ?? false,
      allow_Info_Asset: res.Allow_Info_Asset ?? false,
      allow_Info_BPartner: res.Allow_Info_BPartner ?? false,
      allow_Info_InOut: res.Allow_Info_InOut ?? false,
      allow_Info_Invoice: res.Allow_Info_Invoice ?? false,
      allow_Info_Order: res.Allow_Info_Order ?? false,
      allow_Info_Payment: res.Allow_Info_Payment ?? false,
      allow_Info_Product: res.Allow_Info_Product ?? false,
      allow_Info_Resource: res.Allow_Info_Resource ?? false,
      allow_Info_Schedule: res.Allow_Info_Schedule ?? false,
      isDiscountUptoLimitPrice: res.IsDiscountUptoLimitPrice ?? false,
      isDiscountAllowedOnTotal: res.IsDiscountAllowedOnTotal ?? false,
      isMenuAutoExpand: res.IsMenuAutoExpand ?? false,
      isMasterRole: res.IsMasterRole ?? false,
      isAccessAdvanced: res.IsAccessAdvanced ?? false,
      isClientAdministrator: res.IsClientAdministrator ?? false,
      amtApprovalAccum: res.AmtApprovalAccum || 0,
      daysApprovalAccum: res.DaysApprovalAccum || 0,
      userLevel: res.UserLevel?.identifier || '',
      userLevelId: res.UserLevel?.id || '',
      currency: res.C_Currency_ID?.identifier || '',
      currencyId: res.C_Currency_ID?.id || '',
      preferenceType: res.PreferenceType?.identifier || '',
      preferenceTypeId: res.PreferenceType?.id || '',
      treeMenu: res.AD_Tree_Menu_ID?.identifier || '',
      treeMenuId: res.AD_Tree_Menu_ID?.id || '',
      roleType: res.RoleType?.identifier || '',
      roleTypeId: res.RoleType?.id || '',
      treeOrg: res.AD_Tree_Org_ID?.identifier || '',
      treeOrgId: res.AD_Tree_Org_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: ''
      }
    }

    setActiveSave()
  }
}
onMounted(retrieve)

const setActiveSave = () => {
  if(form.value.name !== '' && form.value.userLevelId !== '') {
    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/roles')
    openTab('/users/roles', 'Roles')
  }
}

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

const submit = async (saveType = '') => {
  form.value.alert.processing = true
  activeSave.value = true

  const res = await $fetch('/api/admin/roles/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      name: form.value.name,
      description: form.value.description,
      amtApproval: form.value.amtApproval,
      isManual: form.value.isManual,
      isPersonalAccess: form.value.isPersonalAccess,
      isShowAcct: form.value.isShowAcct,
      isPersonalLock: form.value.isPersonalLock,
      isCanReport: form.value.isCanReport,
      isCanExport: form.value.isCanExport,
      isCanApproveOwnDoc: form.value.isCanApproveOwnDoc,
      isAccessAllOrgs: form.value.isAccessAllOrgs,
      isChangeLog: form.value.isChangeLog,
      overwritePriceLimit: form.value.overwritePriceLimit,
      isUseUserOrgAccess: form.value.isUseUserOrgAccess,
      confirmQueryRecords: form.value.confirmQueryRecords,
      maxQueryRecords: form.value.maxQueryRecords,
      allow_Info_Account: form.value.allow_Info_Account,
      allow_Info_Asset: form.value.allow_Info_Asset,
      allow_Info_BPartner: form.value.allow_Info_BPartner,
      allow_Info_InOut: form.value.allow_Info_InOut,
      allow_Info_Invoice: form.value.allow_Info_Invoice,
      allow_Info_Order: form.value.allow_Info_Order,
      allow_Info_Payment: form.value.allow_Info_Payment,
      allow_Info_Product: form.value.allow_Info_Product,
      allow_Info_Resource: form.value.allow_Info_Resource,
      allow_Info_Schedule: form.value.allow_Info_Schedule,
      isDiscountUptoLimitPrice: form.value.isDiscountUptoLimitPrice,
      isDiscountAllowedOnTotal: form.value.isDiscountAllowedOnTotal,
      isMenuAutoExpand: form.value.isMenuAutoExpand,
      isMasterRole: form.value.isMasterRole,
      isAccessAdvanced: form.value.isAccessAdvanced,
      isClientAdministrator: form.value.isClientAdministrator,
      amtApprovalAccum: form.value.amtApprovalAccum,
      daysApprovalAccum: form.value.daysApprovalAccum,
      userLevelId: form.value.userLevelId,
      currencyId: form.value.currencyId,
      preferenceTypeId: form.value.preferenceTypeId,
      treeMenuId: form.value.treeMenuId,
      roleTypeId: form.value.roleTypeId,
      treeOrgId: form.value.treeOrgId,
    }
  })

  if(Number(res.status) === 200) {
    /*for(let [key, items] of Object.entries(entries)) {
      for(let entry of items) {
        if(entry.id) {
          let body = {}
          if(key === 'document_status_access') {
            body = {
              id: entry.id,
              userId: entry.userId,
              documentStatusId: entry.documentStatusId,
              isActive: entry.isActive,
            }
          }

          await $fetch(`/api/admin/roles/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'PUT',
            headers: useRequestHeaders(['cookie']),
            body
          })
        } else {
          let body = {}
          if(key === 'org_access') {
            body = {
              roleId: res.id,
              organizationId: entry.organizationId,
              isActive: entry.isActive,
              isReadOnly: entry.isReadOnly
            }
          } else if(key === 'user_assignment') {
            body = {
              roleId: res.id,
              organizationId: record.organizationId,
              userId: entry.userId,
              isActive: entry.isActive
            }
          } else if(key === 'window_access') {
            body = {
              roleId: res.id,
              organizationId: record.organizationId,
              windowId: entry.windowId,
              isActive: entry.isActive,
              isReadOnly: entry.isReadOnly
            }
          } else if(key === 'workflow_access') {
            body = {
              roleId: res.id,
              organizationId: record.organizationId,
              workflowId: entry.workflowId,
              isActive: entry.isActive,
              isReadWrite: entry.isReadWrite
            }
          } else if(key === 'task_access') {
            body = {
              roleId: res.id,
              organizationId: record.organizationId,
              taskId: entry.taskId,
              isActive: entry.isActive,
              isReadWrite: entry.isReadWrite
            }
          } else if(key === 'document_status_access') {
            body = {
              roleId: res.id,
              organizationId: record.organizationId,
              userId: entry.userId,
              documentStatusId: entry.documentStatusId,
              isActive: entry.isActive,
            }
          }

          await $fetch(`/api/admin/roles/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'POST',
            headers: useRequestHeaders(['cookie']),
            body
          })
        }
      }
    }*/
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      //router.push('/users/roles/'+res.id+'/view')
      openTab('/view/role-'+res.id, 'Role: View Details', '/duplicate/role-'+res.id)
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      //router.push('/users/roles/'+res.id+'/edit')
      openTab('/edit/role-'+res.id, 'Role: '+res.Name, '/duplicate/role-'+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/roles', text: 'Roles'},
  { link: '#', text: 'Add Role', active: true}
]))

const tab = ref(route.query?.tab || 'basic')
const tabs2 = computed(() => ([
  { value: 'basic', text: 'Basic'},
  { value: 'workflow', text: 'Workflow'},
  { value: 'access', text: 'Access'},
  { value: 'info', text: 'Allow Info In Role'}
]))
</script>

<template>
  <Head>
    <Title>Add Role</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.userLevelId === '' || 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>
        <AdminRoleForm v-model="form" :tab="tab" @save="save"/>
      </div>
      <div class="opacity-0.6 pointerEvents-none">
        <AdminRoleDetailRecord action="create" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>