import { ref, watch } from 'vue'
import { keyViewMap } from '@/constant/view'
// import { userperInfo } from '@/request/config'
// import axios from 'axios'


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'), []),
  roleKey: localStorage.getItem('roleKey'),
  
})

watch(
  () => user.value.token,
  () => localStorage.setItem('token', user.value.token)
)
watch(
  () => user.value.roleKey,
  () => localStorage.setItem('roleKey', user.value.roleKey)
)

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 = []
  }

  user.value.permission = val || []
  user.value.roleKeyList = power
}

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

export const setInfo = val => {
  user.value.info = val
}

export const setRoleKey = val => {
  user.value.roleKey = val
}

export default user
