import { ref, watch } from 'vue'
import { keyViewMap } from '@/constant/view'
import { detailRole } from '@/request/config'
import router from '../router/index'
import axios from 'axios'

// const rokrole = [
// {id:100, role:'user',menu: 'user',name: '用户管理', },
// {id:102, role:'user:add',menu: 'user',name: '新增', },
// {id:103, role:'user:edit',menu: 'user',name: '编辑', },
// {id:104, role:'user:del',menu: 'user',name: '删除', },
// {id:106, role:'user:disabled',menu: 'user',name: '启用/禁用', },
// {id:107, role:'user:pwd',menu: 'user',name: '修改密码', },
// {id:101, role:'user:view',menu: 'user',name: '查看', },
// {id:200, role:'role',menu: 'role',name: '角色管理', },
// {id:201, role:'role:view',menu: 'role',name: '查看', },
// {id:202, role:'role:add',menu: 'role',name: '新增', },
// {id:203, role:'role:edit',menu: 'role',name: '编辑', },
// {id:204, role:'role:del',menu: 'role',name: '删除', },
// {id:300, role:'organization',menu: 'organization',name: '组织架构', },
// {id:301, role:'organization:view',menu: 'organization',name: '查看', },
// {id:302, role:'organization:add',menu: 'organization',name: '新增', },
// {id:303, role:'organization:edit',menu: 'organization',name: '编辑', },
// {id:304, role:'organization:del',menu: 'organization',name: '删除', },
// {id:500, role:'vrmodel',menu: 'vrmodel',name: '场景管理', },
// {id:501, role:'vrmodel:view',menu: 'vrmodel',name: '查看', },
// {id:503, role:'vrmodel:edit',menu: 'vrmodel',name: '编辑', },
// {id:504, role:'vrmodel:del',menu: 'vrmodel',name: '删除', },
// {id:506, role:'vrmodel:sync',menu: 'vrmodel',name: '同步', },
// {id:507, role:'vrmodel:download',menu: 'vrmodel',name: '下载', },
// {id:600, role:'camera',menu: 'camera',name: '相机管理', },
// {id:601, role:'camera:view',menu: 'camera',name: '查看', },
// {id:606, role:'camera:bind',menu: 'camera',name: '绑定', },
// {id:607, role:'camera:unbind',menu: 'camera',name: '解绑', },
// {id:700, role:'dispatch',menu: 'dispatch',name: '火调项目', },
// {id:701, role:'dispatch:view',menu: 'dispatch',name: '查看', },
// {id:702, role:'dispatch:add',menu: 'dispatch',name: '新增', },
// {id:703, role:'dispatch:edit',menu: 'dispatch',name: '编辑', },
// {id:704, role:'dispatch:del',menu: 'dispatch',name: '删除', },
// {id:706, role:'dispatch:vrmodel:look',menu: 'dispatch',name: '查看场景', },
// {id:707, role:'dispatch:vrmodel:look',menu: 'dispatch',name: '带看', },
// {id:708, role:'dispatch:doc:look',menu: 'dispatch',name: '档案查看', },
// {id:709, role:'dispatch:doc:upload',menu: 'dispatch',name: '档案管理', },
// {id:710, role:'dispatch:teach',menu: 'dispatch',name: '设置教学项目', },
// {id:711, role:'dispatch:share',menu: 'dispatch',name: '分享', },
// {id:800, role:'teaching',menu: 'teaching',name: '教学平台', },
// {id:801, role:'teaching:view',menu: 'teaching',name: '查看', },
// {id:806, role:'teaching:doc:look',menu: 'teaching',name: '查看档案', },
// {id:807, role:'teaching:vrmodel:look',menu: 'teaching',name: '查看场景', },
// {id:808, role:'teaching:message:add',menu: 'teaching',name: '发表留言', },
// {id:809, role:'teaching:cancel',menu: 'teaching',name: '撤销教学', },
// {id:810, role:'teaching:message:look',menu: 'teaching',name: '查看留言',},
// ]
const strToJson = (str, def) => {
  try {
    str = JSON.parse(str)
  } catch {
    str = def
  }
  return str || def
}

const user = ref({
  token: localStorage.getItem('token'),
  info: strToJson(localStorage.getItem('info'), {}),
  permission: strToJson(localStorage.getItem('permission'), []),
  roleKeyList:strToJson(localStorage.getItem('roleKeyList'), []),
  roleData: strToJson(sessionStorage.getItem('roleData'), {}),
  roleLevel:sessionStorage.getItem('roleLevel')
  
})
watch(
  () => user.value.roleLevel,
  () => sessionStorage.setItem('roleLevel', user.value.roleLevel)
)
watch(
  () => user.value.token,
  () => localStorage.setItem('token', user.value.token)
)
watch(
  () => user.value.roleData,
  () => sessionStorage.setItem('roleData', JSON.stringify(user.value.roleData))
)

watch(
  () => user.value.info,
  () => localStorage.setItem('info', JSON.stringify(user.value.info))
)

watch(
  () => user.value.permission,
  () => localStorage.setItem('permission', JSON.stringify(user.value.permission))
)

watch(
  () => user.value.roleKeyList,
  () => localStorage.setItem('roleKeyList', JSON.stringify(user.value.roleKeyList))
)

export const setPermission = async (val,permissions) => {
  let power = []
  if (val !== void 0){
    power = permissions&&permissions.map(element => element.replace('dept','organization').replace('scene','vrmodel') );
    let pubPermission = ['home', 'vrmodel', 'camera', 'teaching', 'dispatch','role','organization'].map(key => ({
      children: [
        { resourceKey: key + ':select' },
        { resourceKey: key + ':update' },
        { resourceKey: key + ':delete' },
        { resourceKey: key + ':add' }
      ],
      resourceKey: key
    }))

     if (val === 'admin' || val==="admin-dept" || val==="admin-super"  ) {
      pubPermission[pubPermission.length - 1].children.push(
        { resourceKey: 'dispatch:setting' }
      )
      pubPermission[pubPermission.length - 2].children.push(
        { resourceKey: 'teaching:setting' }
      )

      pubPermission.push({children: [
          { resourceKey: 'user:select' },
          { resourceKey: 'user:update' },
          { resourceKey: 'user:delete' },
          { resourceKey: 'user:add' }
        ],
        resourceKey: 'user'
      })
    }

    val = pubPermission.map(item => ({
      ...item,
      viewName: keyViewMap[item.resourceKey] || item.resourceKey
    }))
  } else {
    val = []
  }
  console.log('setInfoPermission',val);
  // user.value.permission = val || []
  user.value.roleKeyList = power
}

export const setToken = val => {
  user.value.token = val
}

export const setInfoPermission = val => {
  const replacetest = {
    'dept':'organization',
    'scene':'vrmodel',
  }
  let permission = [{
    children: [
      { resourceKey: 'home:select' },
      { resourceKey: 'home:update' },
      { resourceKey: 'home:delete' },
      { resourceKey: 'home:add' }
    ],
    viewName:'home',
    resourceKey: 'home'
  }]
  val.map(ele => {
    if(ele.type == "menu" && ele.authority){
      let key = replacetest[ele.module]||ele.module
      permission.push({
        resourceKey:key,
        viewName: keyViewMap[key] || key,
        children: [
            { resourceKey: ele.module + ':select' },
            { resourceKey: ele.module + ':update' },
            { resourceKey: ele.module + ':delete' },
            { resourceKey: ele.module + ':add' }
          ],
      })
    }
  })
  console.log('permission',permission);
  user.value.permission = permission || []
}

export const setInfo = val => {
  user.value.info = val
}
export const setRoleLevel = val => {
  user.value.roleLevel = val
}
export const setRoleKey = async val => {
    let {data} = await axios.get(detailRole+val.id, {roleId:val.id});
    let roleData = {}
    data&&data.perm.map(ele => {
      let {perms} = ele
      perms = perms.replace('dept','organization').replace('scene','vrmodel')
      roleData[perms] = Number(ele.dataScope)
    })
    user.value.roleData = roleData
}

export const rolePower = (value) =>{
  let {roleKeyList,roleData,info} = user.value;
  let replacelist = {
    'organizationlist':'organization',
  }
  let routeName = router.currentRoute._value.name
  let item = null,qxdj=false,rokeName=''
  if(typeof(value)=='string'){
      rokeName =  `${replacelist[routeName] || routeName}:${value}`
  }else{
      rokeName =  `${replacelist[routeName] || routeName}:${value.roleType}`
      item = value
      switch(roleData[rokeName]){
        case 2:
        if(item.deptId != info.deptId){
            qxdj = true;
        }
        break;
          case 4://所属组织内部数据
              if(item.deptId != info.deptId){
                  qxdj = true;
              }
              break;
          case 5:
              if(item.creatorId != info.id){
                  qxdj = true;
              }
              break;
      }
  }
  if((!roleKeyList.includes(rokeName))){//判断无权
     return true
  }else if(qxdj){//判断有权查询是否权限足够
     return true
  }
  return false //有权
}

export default user
