import { ref, watch } from 'vue'


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'), {}),
  role: localStorage.getItem('role'),
  fdkkToken: localStorage.getItem('fdkkToken')
})

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

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


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

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

export const setFDKKToken = val => {
  user.value.fdkkToken = val
}

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

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

export const setRole = val => {
  user.value.role = val
}

export default user