import api from '@/request/api'

const state = {
    user: JSON.parse(localStorage.getItem('USER_INFO') || null)
}

const mutations = {
    /**
     * 储存当前登录用户信息
     * @param {*} state 
     * @param {*} userinfo 用户信息
     */
    SET_USERINFO(state,userinfo){
        state.user = userinfo
        localStorage.setItem('USER_INFO',JSON.stringify(userinfo))
        state.loaded = true
    },
    /**
     * 退出登录清除用户数据
     * @param {*} state 
     */
    LOGOUT(state){
        state.user = null
        localStorage.removeItem('USER_INFO')
    }
}

const actions = {
    async fetchUserInfo({ commit, state }) {
    if (state.user) return
    try {
      const res = await api.getUserInfo()
      if(res.code == 1000){
        commit('SET_USERINFO', res.data)
      }else{
        console.error('获取用户信息失败')
      }
    } catch (e) {
      console.error('获取用户信息失败', e)
    }
  }
}

const getters = {
    /**
     * 用户是否为管理员
     * @param {*} state 
     * @returns 
     */
    isAdmin:state => state.user.roles.some(x => x.role == 'Admin'),
    Avatar:state => state.user.avatar
}


export default {
    namespaced:true,
    state,
    mutations,
    actions,
    getters
}