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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: {},
    case: {},
    role: 0
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    setCase(state, data) {
      state.case = data
    },
    setRole(state, data) {
      state.role = data
    }
  },
  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)
            // 获取选中案例
            getSelectCase().then(response => {
              commit('setCase', response.data.case)
            })
            // 获取用户选中的角色
            getSelectRole().then(res => {
              commit('setRole', res.data.role)
            })
            return true
          } else {
            commit('setUser', {})
            return false
          }
        })
        .catch(() => {
          commit('setUser', {})
          return false
        })
      return isLogin
    }
  }
})
