{"size": 1878, "ext": "js", "max_stars_repo_path": "src/store/user.js", "max_stars_repo_name": "FishPlusOrange/easy-admin", "max_stars_repo_stars_event_min_datetime": "2019-02-01T01:32:07.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-10T11:33:48.000Z", "max_issues_repo_path": "src/store/user.js", "max_issues_repo_name": "FishPlusOrange/easy-admin", "max_issues_repo_issues_event_min_datetime": "2020-07-16T16:52:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-17T19:48:53.000Z", "max_forks_repo_path": "src/store/user.js", "max_forks_repo_name": "FishPlusOrange/admin-by-vue", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 4, "max_issues_count": 6, "max_forks_count": null, "avg_line_length": 22.6265060241, "max_line_length": 75, "alphanum_fraction": 0.4627263046}
import axios from 'axios'
import qs from 'qs'
import { getToken, setToken } from '@/libs/util'

export default {
  state: {
    token: getToken(),
    userInfo: {
      userId: '',
      userName: '',
      email: '',
      avatar: '',
      access: ''
    }
  },
  getters: {
    hasGotUserInfo (state) {
      return !!state.userInfo.userId
    }
  },
  mutations: {
    setToken (state, payload) {
      const token = payload.token
      state.token = token
      setToken(token)
    },
    setUserInfo (state, payload) {
      const userInfo = payload.userInfo
      state.userInfo = userInfo
    }
  },
  actions: {
    // 用户登录
    userLogin ({ state, commit }, { loginName, password }) {
      return new Promise((resolve, reject) => {
        axios.post('/user/login', qs.stringify({
          loginName,
          password
        }))
          .then(res => {
            const token = res.data.token
            commit('setToken', { token }) // 设置 Vuex 和 localStorage 的 token
            resolve()
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    // 退出登录
    userLogout ({ state, commit }) {
      return new Promise((resolve, reject) => {
        axios.post('/user/logout')
          .then(() => {
            commit('setToken', { token: '' }) // 初始化 token
            resolve()
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    // 获取用户信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        axios.get('/user/getInfo', {
          params: {
            token: state.token
          }
        })
          .then(res => {
            const userInfo = res.data.userInfo
            commit('setUserInfo', { userInfo })
            resolve()
          })
          .catch(err => {
            reject(err)
          })
      })
    }
  }
}
