var a=Object.defineProperty;var h=(r,e,t)=>e in r?a(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var n=(r,e,t)=>h(r,typeof e!="symbol"?e+"":e,t);import{v as l}from"./index-CkzfmDGw.js";class w{constructor(){n(this,"ws",null);n(this,"reconnectTimer",null);n(this,"heartbeatTimer",null);n(this,"handlers",new Map);n(this,"reconnectAttempts",0);n(this,"maxReconnectAttempts",5);n(this,"reconnectDelay",3e3)}connect(){const e=l();if(!e.token){console.warn("[WebSocket] 未登录，无法连接");return}if(this.ws&&this.ws.readyState===WebSocket.OPEN){console.log("[WebSocket] 已连接");return}const t=window.location.protocol==="https:"?"wss:":"ws:",o=window.location.host,c=`${t}//${o}/ws/message?token=${e.token}`;console.log("[WebSocket] 正在连接..."),this.ws=new WebSocket(c),this.ws.onopen=()=>{console.log("[WebSocket] 连接成功"),this.reconnectAttempts=0,this.startHeartbeat()},this.ws.onmessage=s=>{try{const i=JSON.parse(s.data);console.log("[WebSocket] 收到消息:",i),this.dispatch(i.type,i)}catch(i){console.error("[WebSocket] 消息解析失败",i)}},this.ws.onclose=s=>{console.log("[WebSocket] 连接关闭",s.code,s.reason),this.stopHeartbeat(),this.tryReconnect()},this.ws.onerror=s=>{console.error("[WebSocket] 连接错误",s)}}disconnect(){this.stopHeartbeat(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.reconnectAttempts=0}send(e,t={}){this.ws&&this.ws.readyState===WebSocket.OPEN?this.ws.send(JSON.stringify({type:e,...t})):console.warn("[WebSocket] 未连接，无法发送消息")}on(e,t){this.handlers.has(e)||this.handlers.set(e,[]),this.handlers.get(e).push(t)}off(e,t){if(!t)this.handlers.delete(e);else{const o=this.handlers.get(e);if(o){const c=o.indexOf(t);c>-1&&o.splice(c,1)}}}dispatch(e,t){const o=this.handlers.get(e);o&&o.forEach(s=>s(t));const c=this.handlers.get("*");c&&c.forEach(s=>s(t))}startHeartbeat(){this.heartbeatTimer=window.setInterval(()=>{this.send("ping")},3e4)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}tryReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){console.log("[WebSocket] 达到最大重连次数，停止重连");return}this.reconnectAttempts++,console.log(`[WebSocket] ${this.reconnectDelay/1e3}秒后尝试第${this.reconnectAttempts}次重连...`),this.reconnectTimer=window.setTimeout(()=>{this.connect()},this.reconnectDelay)}isConnected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}}const m=new w;export{m as w};
