import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
import user from './modules/user'
import tagsView from './modules/tagsView'
import permission from './modules/permission'
import settings from './modules/settings'
import getters from './getters'
import {LiveWS} from "@/utils/liveWS";

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    app,
    user,
    tagsView,
    permission,
    settings
  },
  getters,
  state: {
    liveWs: {}
  },
  mutations: {
    // 更新为支持多个 WebSocket 连接
    setLiveWs(state, { ws, liveId }) {
      // 使用 liveId 作为键来存储不同的 WebSocket 连接
      Vue.set(state.liveWs, liveId, ws);
    },
    // 添加移除 WebSocket 连接的 mutation
    removeLiveWs(state, liveId) {
      Vue.delete(state.liveWs, liveId);
    }
  },
  actions: {
    // 修改 action 以正确传递参数
    initLiveWs({ commit, state, rootState }, { liveWsUrl, liveId, userId }) {
      // 如果已经存在对应 liveId 的连接，先关闭它
      if (state.liveWs[liveId]) {
        state.liveWs[liveId].close();
      }

      // 读取登录时的 tenantCode
      const tenantCode = rootState.user.tenantCode || null

      // 创建新的 WebSocket 连接
      const ws = new LiveWS(liveWsUrl, liveId, userId, tenantCode);

      // 提交到 mutation
      commit('setLiveWs', { ws, liveId });

      return ws;
    },
    // 添加关闭特定 WebSocket 连接的 action
    closeLiveWs({ commit, state }, liveId) {
      if (state.liveWs[liveId]) {
        state.liveWs[liveId].close();
        commit('removeLiveWs', liveId);
      }
    }
  }
})

export default store
