import Vue from 'vue'
import Vuex from 'vuex'
// import router from '@/router'
import { routes } from '@/router/routes.js'
import { getUser, logout } from '@/api/my'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: {},
    sidebar: []
  },
  getters: {
    getSidebar: state => state.sidebar
  },
  mutations: {
    setUser(state, user) {
      state.user = user
      window.G.UserInfo = user
    },
    SET_ROUTES: (state, routes) => {
      state.sidebar = routes
    }
  },
  actions: {
    getUser({ commit }) {
      getUser().then(response => {
        commit('setUser', response.data)
      })
    },
    // 检测登录状态
    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
    },
    generateRoutes({ commit }) {
      return new Promise(resolve => {
        commit('SET_ROUTES', routes)
        resolve(routes)
      })
    },
    logout() {
      return logout().then(() => {
        // router.push('/')
        window.location.href = '/'
      })
    }
  }
})
