import { ref } from 'vue'
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(
    localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {},
  )
  const routerList = ref(
    localStorage.getItem('routerList') ? JSON.parse(localStorage.getItem('routerList')) : [],
  )
  const setToken = (t) => {
    token.value = t
    localStorage.setItem('token', t)
  }
  const setUserInfo = (u) => {
    userInfo.value = u
    localStorage.setItem('userInfo', JSON.stringify(u))
  }
  const setRouterList = (u) => {
    routerList.value = u
    localStorage.setItem('routerList', JSON.stringify(u))
  }
  const logout = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('routerList')
    token.value = ''
    userInfo.value = {}
    routerList.value = []

    // 重置路由
    import('@/router').then(({ resetRouter }) => {
      resetRouter()
    })
  }
  return { token, setToken, setUserInfo, userInfo, logout, setRouterList, routerList }
})
