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)

function normalizeLiveId(liveId) {
  return liveId == null ? '' : String(liveId)
}

function getLiveWs(state, liveId) {
  const key = normalizeLiveId(liveId)
  return state.liveWs[key] || state.liveWs[liveId] || null
}

const store = new Vuex.Store({
  modules: {
    app,
    user,
    tagsView,
    permission,
    settings
  },
  getters,
  state: {
    liveWs: {},
    // { [liveId]: { console: true, config: true } }
    liveWsOwners: {}
  },
  mutations: {
    // 更新为支持多个 WebSocket 连接
    setLiveWs(state, { ws, liveId }) {
      const key = normalizeLiveId(liveId)
      Vue.set(state.liveWs, key, ws);
    },
    // 添加移除 WebSocket 连接的 mutation
    removeLiveWs(state, liveId) {
      const key = normalizeLiveId(liveId)
      Vue.delete(state.liveWs, key);
    },
    addLiveWsOwner(state, { liveId, owner }) {
      const key = normalizeLiveId(liveId)
      if (!state.liveWsOwners[key]) {
        Vue.set(state.liveWsOwners, key, {})
      }
      Vue.set(state.liveWsOwners[key], owner, true)
    },
    removeLiveWsOwner(state, { liveId, owner }) {
      const key = normalizeLiveId(liveId)
      if (!state.liveWsOwners[key]) return
      Vue.delete(state.liveWsOwners[key], owner)
      if (Object.keys(state.liveWsOwners[key]).length === 0) {
        Vue.delete(state.liveWsOwners, key)
      }
    }
  },
  actions: {
    /**
     * 获取/复用直播间 WebSocket。同一 liveId 多页面共享一条连接。
     * owner: 'console' | 'config' | 其它业务标识
     */
    acquireLiveWs({ commit, state }, { liveWsUrl, liveId, userId, owner }) {
      const key = normalizeLiveId(liveId)
      if (!key) {
        console.error('[liveWs] acquireLiveWs: liveId is empty')
        return null
      }
      let ws = getLiveWs(state, key)
      const needCreate = !ws || ws.isManualClose
      if (needCreate) {
        ws = new LiveWS(liveWsUrl, key, userId)
        commit('setLiveWs', { ws, liveId: key })
      }
      if (owner) {
        commit('addLiveWsOwner', { liveId: key, owner })
      }
      return ws
    },
    /**
     * 释放占用。当该 liveId 已无任何 owner 时真正关闭连接。
     */
    releaseLiveWs({ commit, state, dispatch }, { liveId, owner }) {
      const key = normalizeLiveId(liveId)
      if (!key) return
      if (owner) {
        commit('removeLiveWsOwner', { liveId: key, owner })
      }
      const owners = state.liveWsOwners[key]
      if (!owners || Object.keys(owners).length === 0) {
        dispatch('closeLiveWs', key)
      }
    },
    // 兼容旧调用：不再强行重连；已有连接则复用
    initLiveWs({ dispatch }, { liveWsUrl, liveId, userId, owner = 'legacy' }) {
      return dispatch('acquireLiveWs', { liveWsUrl, liveId, userId, owner })
    },
    // 添加关闭特定 WebSocket 连接的 action
    closeLiveWs({ commit, state }, liveId) {
      const key = normalizeLiveId(liveId)
      const ws = getLiveWs(state, key)
      if (ws) {
        ws.close();
        commit('removeLiveWs', key);
      }
      if (state.liveWsOwners[key]) {
        Vue.delete(state.liveWsOwners, key)
      }
    }
  }
})

export default store
