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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: {},
    case: {}
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    setCase(state, data) {
      state.case = 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)
            })
            return true
          } else {
            commit('setUser', {})
            return false
          }
        })
        .catch(() => {
          commit('setUser', {})
          return false
        })
      return isLogin
    }
  }
})
