<script setup>

import { defineEmits, onMounted,defineProps,ref } from "vue";

/* 获取用户角色信息 */
const jsonStringRole = localStorage.getItem('role')
let roleInformation = ref([])
try {
  roleInformation.value = jsonStringRole ? JSON.parse(jsonStringRole) : []
} catch (error) {
  roleInformation.value = []
}

/* 查询当前角色中是否包含安全管理系统的角色 */
let roleCode = ''
let flag = ref(true)
let roleCodes = ref([])
for (let item of roleInformation.value) {
  if (item.roleCode.includes('SX0')) {
    roleCodes.value.push(item.roleCode)
    flag.value = false
  }
}

if (flag.value) {
  ElMessage.error('未配置角色，请联系管理员')
}

/* 对用户拥有的安全角色进行排序，找出最高权限的角色 */
let temp = ''
for (let i = 0;i<roleCodes.value.length;i++) {
  for (let j = 0;j<roleCodes.value.length-1-i;j++) {
    if (parseInt(roleCodes.value[j].substring(3,1)) > parseInt(roleCodes.value[j+1].substring(3,1))) {
      temp = roleCodes.value[j+1]
      roleCodes.value[j+1] = roleCodes.value[j]
      roleCodes.value[j] = temp
    }
  }
}

if (!roleCodes.value[0]) {
  roleCode = ''
} else {
  roleCode = roleCodes.value[0]
}


/* 获取用户的部门信息 */
const jsonStringDept = localStorage.getItem('dept');
let deptInformation = ref([])
try {
  deptInformation.value = jsonStringDept ? JSON.parse(jsonStringDept) : []
} catch (error) {
  deptInformation.value = []
}
let deptCode = deptInformation.value[0].deptCode
let superDeptCode = deptCode.slice(0,-2)
if (superDeptCode === 'D11011301') {
  superDeptCode = 'D110113'
}
if (superDeptCode === 'D1101') {
  superDeptCode = 'D11'
}

const props = defineProps(['pagePath'])
const emit = defineEmits(['update:selectedPermission']);

/* 可查看的部门 */
const deptLevel = ref('')

/* 是否可编辑 */
const permission = ref(false)

/* 基础的权限控制 */
const basicPermissionControl = () => {
  if (roleCode.includes('SX01')) {
    deptLevel.value = superDeptCode
    permission.value = false
  } else if (roleCode.includes('SX02') || roleCode.includes('SX03')) {
    deptLevel.value = superDeptCode
    permission.value = true
  } else if (roleCode.includes('SX04') || roleCode.includes('SX05')) {
    deptLevel.value = deptCode
    permission.value = true
  } else if (roleCode.includes('SX06')) {
    deptLevel.value = deptCode
    permission.value = false
  }
}

/* 法律法规库的权限控制 */
const lawsRegulations = () =>{
  deptLevel.value = 'D1101'
  if (roleCode.includes('SX02')) {
    deptLevel.value = superDeptCode
    permission.value = true
  }
}


/* 判断用户角色 */
onMounted(() => {
  if (props.pagePath === 'law') {
    lawsRegulations()
  }else {
    basicPermissionControl()
  }
  emit('update:selectedPermission', deptLevel.value, permission.value);
})

</script>

<template>

</template>

<style scoped>

</style>
