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

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    user: {},
    permissions: [],
    commonMap: {} // 权限列表
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    setPermissions(state, permissions) {
      state.permissions = permissions
    },
    setCommonMap(state, commonMap) {
      state.commonMap = commonMap
    }
  },
  actions: {
    // 获取所有项目列表
    getCommonMap({ commit }) {
      getCommonMap().then(res => {
        const data = res.data
        // 所有项目列表
        commit('setCommonMap', data)
      })
    },
    getPermissions({ commit }) {
      getPermissions({ type: 2 }).then(res => {
        if (res.data && res.data.items) {
          commit('setPermissions', res.data.items)
        }
      })
    },
    // 获取用户信息
    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
    }
  }
})
// 获取权限列表
// store.dispatch('getPermissions')
// 初始化获取项目列表
// store.dispatch('getCommonMap')

export default store
