import Vue from 'vue'
import Vuex from 'vuex'
import { getUser, logout } from '@/api/base'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: {}
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    }
  },
  actions: {
    // 获取用户信息
    getUser({ commit }) {
      getUser().then(response => {
        commit('setUser', response)
      })
    },
    // 退出登录
    logout({ commit }) {
      return logout().then(response => {
        commit('setUser', {})
        return response
      })
    },
    async checkLogin({ commit }) {
      const isLogin = await getUser()
        .then(response => {
          if (response.code === 0) {
            commit('setUser', response.data)
            return true
          } else {
            commit('setUser', {})
            return false
          }
        })
        .catch(() => {
          commit('setUser', {})
          return false
        })
      return isLogin
    }
  }
})
