import Vue from 'vue'
import Vuex from 'vuex'
import { getUser } from '@/api/account'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    groupList: [],
    user: {}
  },
  mutations: {
    setGroupList(state, list) {
      state.groupList = list
    },
    setUser(state, user) {
      state.user = user
    }
  },
  actions: {
    getUser({ commit }) {
      getUser().then(response => {
        commit('setUser', response)
      })
    },
    async checkLogin({ commit }) {
      const isLogin = await getUser()
        .then(response => {
          if (response.code === 0) {
            commit('setUser', response)
            return true
          } else {
            commit('setUser', {})
            return false
          }
        })
        .catch(() => {
          commit('setUser', {})
          return false
        })
      return isLogin
    }
  }
})
