import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    isLoggedIn: false,
    userInfo: null
  },
  getters: {
    isLoggedIn: state => state.isLoggedIn,
    userInfo: state => state.userInfo
  },
  mutations: {
    SET_LOGIN_STATE(state, isLoggedIn) {
      state.isLoggedIn = isLoggedIn
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    CLEAR_USER_DATA(state) {
      state.isLoggedIn = false
      state.userInfo = null
    }
  },
  actions: {
    // 退出登录
    async logout({ commit }) {
      try {
        // 清除本地存储
        localStorage.removeItem('token')
        localStorage.removeItem('userEmail')
        localStorage.removeItem('jurisdiction')
        
        // 清除 Vuex 状态
        commit('CLEAR_USER_DATA')
        
        // 触发全局事件，通知其他组件用户已退出
        if (Vue.prototype.$bus) {
          Vue.prototype.$bus.$emit('user-logged-out')
        }
        
        return true
      } catch (error) {
        console.error('退出登录失败:', error)
        return false
      }
    }
  },
  modules: {
  }
})
