import { ref, watch } from 'vue'
import { keyViewMap } from '@/constant/view'


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'), [])
})

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

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

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

export const setPermission = val => {
  if (val !== void 0){
    let pubPermission = ['home', 'vrmodel', 'camera', 'teaching', 'dispatch'].map(key => ({
      children: [
        { resourceKey: key + ':select' }, 
        { resourceKey: key + ':update' }, 
        { resourceKey: key + ':delete' }, 
        { resourceKey: key + ':add' }
      ],
      resourceKey: key
    }))

    if (val === '1') {
      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
}

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

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

export default user