AiChatWsService.js 2.8 KB
/*
 * 接待场景 AI 对话 WebSocket(跟随接待会话建连/断连)
 */
import NativeWsClient from '@/utils/socket/NativeWsClient.js'
import { getNativeWsBase } from '@/utils/socket'

class AiChatWsService {
  static _instance = null

  constructor() {
    this._connectPromise = null
    /** 是否由接待会话托管(仅此种情况在 stopAudio 时断开) */
    this._receptionBound = false
    /** 只有明确配置了该 url 才会发起 WebSocket 连接 */
    this._wsUrl = ''
  }

  static getInstance() {
    if (!AiChatWsService._instance) {
      AiChatWsService._instance = new AiChatWsService()
    }
    return AiChatWsService._instance
  }

  getClient() {
    return NativeWsClient.getInstance()
  }

  /** 显式设置 AI 对话 WS 地址;未设置时不会自动连接 */
  setWsUrl(url) {
    this._wsUrl = url || ''
  }

  isConnected() {
    return this.getClient().isConnected
  }

  /**
   * 建立 AI 对话 WS
   * @param {{ fromReception?: boolean }} [options] fromReception=true 时跟随接待生命周期断连
   */
  connectForReception(options = {}) {
    // #ifndef APP-PLUS
    return Promise.resolve(false)
    // #endif

    // #ifdef APP-PLUS
    const wsUrl = (getNativeWsBase() || '').trim()
    if (!wsUrl) {
      // 未配置 WS 地址时直接跳过(本项目可纯 HTTP 模式运行)
      return Promise.resolve(false)
    }
    if (options.fromReception) {
      this._receptionBound = true
    }
    if (this.isConnected()) {
      return Promise.resolve(true)
    }
    if (this._connectPromise) {
      return this._connectPromise
    }

    this._connectPromise = (async () => {
      try {
        uni.$logger?.local?.info(`[AiChatWs] 接待开始,连接 ${wsUrl}`)
        await this.getClient().connectDirect(wsUrl)
        return true
      } catch (e) {
        uni.$logger?.local?.warn(`[AiChatWs] 连接失败: ${e.message || e}`)
        return false
      } finally {
        this._connectPromise = null
      }
    })()

    return this._connectPromise
    // #endif
  }

  /** 结束接待:断开并停止自动重连 */
  async disconnectReception() {
    // #ifndef APP-PLUS
    return
    // #endif

    // #ifdef APP-PLUS
    if (!this._receptionBound) {
      return
    }
    this._receptionBound = false
    this._connectPromise = null
    const client = this.getClient()
    try {
      uni.$logger?.local?.info('[AiChatWs] 接待结束,断开 WS')
      await client.close(1000, 'reception end', true)
    } catch (e) {
      uni.$logger?.local?.warn(`[AiChatWs] 断开异常: ${e.message || e}`)
    }
    // #endif
  }

  /** 求助前确保已连接(接待开始时通常已连好,此处作兜底) */
  async ensureConnected() {
    if (this.isConnected()) {
      return true
    }
    return this.connectForReception()
  }
}

export default AiChatWsService