RecordService.js 17.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: limin
 * @Date: 2026-01-14 16:22:23
 * @LastEditors: limin
 * @LastEditTime: 2026-06-11 17:23:17
 * @FilePath: \gl_tape\utils\recordManager\RecordService.js
 */
import { AudioManager, RecordDto, helpler, StrategyFactory, TimeoutService } from './index.js'
import { storageApi } from '@/utils/cache'
import permission from '@/js_sdk/wa-permission/permission.js'
import store from '@/store'
import PathUtils from './PathUtils.js'
import AudioFramePool from './AudioFramePool.js'
import NativeChannelClient, { TransportType, getNativeWsBase } from '@/utils/socket'
class RecordService {
  static instance = null

  constructor() {
    this.audioManager = null
    this.record = null
    this.tempRecord = null
    this.debounceTimers = {}
    this._startAudioPromise = null
    this.timeoutService = null
    this._initDone = false
    /** AI 通道:接待开始时确定(默认 HTTP;配置了 NATIVE_WS_BASE 则走 WS) */
    this._aiClient = null
    // 音频帧缓冲池,保留最近 60 秒的 PCM 数据
    this.framePool = new AudioFramePool({ maxSeconds: 60, sampleRate: 16000 })
    // 保存初始化 Promise,startAudio 会等待
    this._initPromise = this.init()
  }

  static getInstance() {
    if (!RecordService.instance) {
      RecordService.instance = new RecordService()
    }
    return RecordService.instance
  }

  async init() {
    try {
      uni.$logger.local.info('【录音服务RecordService】 == 初始化')

      const saveDir = await PathUtils.getFilePath()
      // const saveDir = ''
      uni.$logger.local.info(`【接待录音】初始化: saveDir=${saveDir}`)
      this.audioManager = new AudioManager(this.onAudioStart.bind(this), this.onAudioStop.bind(this), this.onAudioError.bind(this), this.onFrameRecorded.bind(this), this.onFrameRecordedEnd.bind(this), saveDir)
      this.initDto()
      this.record = StrategyFactory.getSaveStrategy(this.tempRecord, this.triggerTempNumber.bind(this), this.attributesProvider.bind(this))
      this.timeoutService = new TimeoutService(this.onTimeOut.bind(this))
      this.triggerTempNumber()

      // 启动状态监听
      // this.startStateListener()
      this.initWatchers()
    } catch (e) {
      uni.$logger.local.error(`【录音服务RecordService】 == 初始化异常: ${e.message}\n${e.stack}`)
    }
  }
  initWatchers() {
    // 监听 customerKey
    this.unwatchCustomer = store.watch(
      (state, getters) => getters.customerKey,
      () => {
        const customerInfo = store.getters.customerInfo
        this.handler(customerInfo, this.updateCustomerInfo, 1000)
      },
      { immediate: true }
    )
    // 监听 receptionStatus
    this.unwatchStatus = store.watch(
      (state, getters) => getters.receptionStatus,
      val => {
        this.handler(val, this.updateReceptionStatus, 200)
      },
      { immediate: true }
    )
    this.unwatchBookList = store.watch(
      (state, getters) => getters.booksList,
      val => {
        this.handler(val, this.updateBookList, 1500)
      },
      { immediate: true }
    )
    this.unwatchReceptionKey = store.watch(
      (state, getters) => getters.receptionKey,
      () => {
        const receptionTrack = store.getters.receptionTrack
        this.handler(receptionTrack, this.updateMaterialPointList, 1000)
      },
      { immediate: true }
    )
  }

  // --- 业务逻辑 (从 recorder.js 迁移) ---

  async startAudio(isInitData = true) {
    // 等待初始化完成
    if (this._initPromise) {
      await this._initPromise
      this._initPromise = null
    }
    if (!this.audioManager) {
      uni.$logger.local.error('【录音服务RecordService】 == audioManager 未初始化,无法启动录音')
      return false
    }
    if (this._startAudioPromise) return this._startAudioPromise
    this._startAudioPromise = (async () => {
      try {
        const isPermission = await this.checkBeforeStart()
        if (!isPermission) return
        uni.$logger.local.info('【录音服务RecordService】 == 开始接待 ')
        if (isInitData) {
          this.initReception()
        }
        this.audioManager.start()
        this.timeoutService.start()
        await this._ensureAiClientForReception()
        return true // 返回 true 表示成功启动
      } catch (e) {
        uni.$logger.local.error(`【录音服务RecordService】 == startAudio 异常: ${e.message}\n${e.stack}`)
      } finally {
        this._startAudioPromise = null
      }
    })()
    return this._startAudioPromise
  }

  getBussinessType(sceneType) {
    return sceneType == 0 ? 1 : 2 // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
  }

  attributesProvider() {
    const { shopMerchantId, phone, sceneType, uuid, name, merchantId, channelType, merchantName } = storageApi.getUserInfo() || {}
    const dynamicAttrs = {
      staffUuid: uuid,
      staffName: name,
      serviceMerchantId: merchantId,
      loginPhone: phone,
      merchantId: shopMerchantId,
      merchantName,
      bussinessType: this.getBussinessType(sceneType),
      channelType: channelType || 1 //1问界 2 比亚迪 3 其他
    }
    // uni.$logger.local.warn(`【录音服务RecordService】 == 创建新记录,注入动态属性: ${JSON.stringify(dynamicAttrs)}`)
    return dynamicAttrs
  }

  initReception() {
    store.commit('audio/setBooks', [])
    store.commit('clearCustomerInfo')
    store.commit('audio/setReceptionStatus', '')
  }

  async onAudioStart(res) {
    try {
      const filePath = res?.filePath || res?.tempFilePath || ''
      const recordId = this.record?.currentRecord?.id || ''
      uni.$logger.local.info(`【接待录音】onAudioStart: counter=${this.audioManager.counter}, recordId=${recordId || '待创建'}, filePath=${filePath}`)
      // 重置帧缓冲池,开始新的录音周期
      this.framePool.reset()

      if (this.audioManager.counter === 0) {
        uni.$logger.local.info('〖RecordService〗 == First audio segment, adding record...')
        await this.record.add(res)
        uni.$logger.local.info('〖RecordService〗 == Record added successfully.')
      } else {
        uni.$logger.local.info(`【接待录音】续录分段: counter=${this.audioManager.counter}, filePath=${filePath}`)
        this.record.addAudio(res)
      }
      // setTimeout(() => {
      //   this.uploadRecentAudio({url:"http://192.168.1.203:8000/audio/chat",seconds:5})
      // }, 6000)
    } catch (e) {
      uni.$logger.local.error('〖RecordService〗 == onAudioStart error: ' + e.message)
    }
  }

  async onAudioStop() {
    if (!this.audioManager) return
    if (this.audioManager.isRecording) {
      uni.$logger.local.info(`【接待录音】录音分段结束,自动续录 counter=${this.audioManager.counter}, recordId=${this.record?.currentRecord?.id || ''}`)
      uni.$logger.local.info('【录音服务RecordService】 == 接待中,再次开启录音! ')
      this.audioManager.start()
    } else {
      uni.$logger.local.info(`【接待录音】录音停止,不再续录 recordId=${this.record?.currentRecord?.id || ''}`)
      uni.$logger.local.info('【录音服务RecordService】 == 断开录音! ')
    }
  }

  onAudioError(error) {
    const message = error.message
    this.reportError(`录音异常: error: ${message}`, message)
  }
  /**
   * 实时音频帧回调 (仅 APP-PLUS 平台有效)
   * @param {Object} data - 包含 base64 字符串和是否为最后一帧的布尔值
   */
  onFrameRecorded(data) {
    // 将帧数据推入缓冲池
    if (data && data.base64) {
      this.framePool.push(data.base64)
    }
  }
  /**
   * 实时音频帧结束回调 (仅 APP-PLUS 平台有效)
   * @param {Object} data - 包含 base64 字符串和是否为最后一帧的布尔值
   */
  onFrameRecordedEnd(data) {
    console.log(data)
  }

  /**
   * 截取最近 N 秒的音频数据(纯 PCM / WAV 格式)
   * @param {number} [seconds=30] - 截取最近多少秒,默认 30 秒
   * @returns {ArrayBuffer|null} PCM / WAV 格式的 ArrayBuffer,失败返回 null
   */
  captureRecentAudio(seconds = 30, format = 'pcm') {
    const status = this.framePool.getStatus()
    uni.$logger.local.info(`【录音服务RecordService】 == 截取音频: 缓冲池状态 ${JSON.stringify(status)}`)
    return this.framePool.capture(seconds, format)
  }

  /**
   * 截取并上传最近 N 秒的音频到服务器(纯 PCM / WAV 格式)
   * @param {Object} options
   * @param {string} options.url - 上传接口地址
   * @param {number} [options.seconds=30] - 截取最近多少秒
   * @returns {Promise<Object>} 服务器响应
   */
  // async uploadRecentAudio(options) {
  //   const { url, seconds = 30 } = options
  //   uni.$logger.local.info(`【录音服务RecordService】 == 开始上传最近 ${seconds} 秒音频到 ${url}`)
  //   try {
  //     const result = await this.framePool.upload({ url, seconds, format: 'pcm' })
  //     uni.$logger.local.info(`【录音服务RecordService】 == 音频上传成功: ${result.text}`)
  //     return result
  //   } catch (e) {
  //     uni.$logger.local.error(`【录音服务RecordService】 == 音频上传失败: ${e.message}`)
  //     throw e
  //   }
  // }

  /**
   * 获取帧缓冲池状态
   * @returns {Object} 缓冲池状态信息
   */
  getFramePoolStatus() {
    return this.framePool.getStatus()
  }

  async stopAudio(isNotSave = false) {
    if (!this.isReceptioning()) {
      uni.$logger.local.warn('【录音服务RecordService】 == 未开始接待,不能结束接待! ')
      return
    }
    const record = this.record?.currentRecord
    const fileCount = record?.recordUrlList?.length || 0
    uni.$logger.local.info(`【接待录音】结束接待: recordId=${record?.id || ''}, fileCount=${fileCount}, isNotSave=${isNotSave}`)
    uni.$logger.local.info('【录音服务RecordService】 == 结束接待! ')
    this.stop()
    await this._teardownAiClientForReception().catch(() => {})
    try {
      await this.saveAndClearRecord(isNotSave)
    } catch (error) {
      uni.$logger.local.error(`【录音服务RecordService】 == 结束接待保存失败: ${error.message}`)
      this.reportError('结束接待保存失败', error.message)
    }
  }

  async saveAndClearRecord(isNotSave = false) {
    const record = this.record?.currentRecord
    const files = (record?.recordUrlList || []).map(i => i.file).join(', ')
    uni.$logger.local.info(`【接待录音】保存记录: recordId=${record?.id || ''}, files=[${files}], isNotSave=${isNotSave}`)
    if (isNotSave) {
      //如果不需要保存记录
      uni.$logger.local.info('【录音服务RecordService】 == 不保存记录! ')
      await this.record.clearSavedFiles()
      await this.record.clearLocalRecord()
      return
    }
    await this.record.setReceptionEndTime() //设置接待结束时间
    await this.record.save()
  }

  stop() {
    this.record?.clearLoopTimer()
    this.stopAudioRecord()
  }
  onTimeOut() {
    uni.$logger.local.warn(`【接待录音】闲置超时自动停止: recordId=${this.record?.currentRecord?.id || ''}`)
    store.commit('audio/setReceptionStatus', 0)
    this.record.withError()
    this.stopAudioRecord()
  }
  stopAudioRecord() {
    this.audioManager?.stop()
    this.timeoutService?.stop()
  }

  /** 获取当前接待的 AI client(可能为 null,表示未开始接待或初始化失败) */
  getAiClient() {
    return this._aiClient
  }

  async _ensureAiClientForReception() {
    const wsBase = (getNativeWsBase() || '').trim()
    const useWs = !!wsBase
    const transport = useWs ? TransportType.WEBSOCKET : TransportType.HTTP
    // HTTP 服务端固定为 /health(可在 AiAssistantBall 内按需覆盖)
    const httpBaseUrl = 'https://lightmodification.glsx.com.cn'

    const client = new NativeChannelClient(useWs ? { transport } : { transport, baseUrl: httpBaseUrl })
    this._aiClient = client

    if (useWs) {
      try {
        uni.$logger?.local?.info(`[AI] 接待开始,使用 WS: ${wsBase}`)
        await client.connectDirect(wsBase)
      } catch (e) {
        uni.$logger?.local?.warn(`[AI] WS 连接失败,回退 HTTP: ${e.message || e}`)
        this._aiClient = new NativeChannelClient({ transport: TransportType.HTTP, baseUrl: httpBaseUrl })
      }
    } else {
      uni.$logger?.local?.info(`[AI] 接待开始,使用 HTTP: ${httpBaseUrl}`)
    }
  }

  async _teardownAiClientForReception() {
    const client = this._aiClient
    this._aiClient = null
    if (!client) return
    if (client.transport === TransportType.WEBSOCKET) {
      await client.close(1000, 'reception end', true).catch(() => {})
    } else {
      await client.close().catch(() => {})
    }
  }

  handler(params, fn, delay = 0) {
    if (this.isReceptioning()) {
      fn.call(this, params)
    }
  }

  isReceptioning() {
    return this.audioManager?.isRecording || this.record?.currentRecord?.endReasonType == 1
  }

  reset() {
    // this.flushAllDebounceTimers()
    this.audioManager = null
    this.record = null
    this.tempRecord = null
    this.framePool.reset()
  }

  initDto() {
    const { shopMerchantId, phone, sceneType, uuid, name, merchantId, channelType, merchantName } = storageApi.getUserInfo() || {}
    const { deviceId: appCode } = uni.getDeviceInfo()
    const dto = new RecordDto({
      staffUuid: uuid,
      staffName: name,
      serviceMerchantId: merchantId,
      endReasonType: 0, //原因 1.异常 0.正常
      loginPhone: phone,
      appCode,
      merchantId: shopMerchantId,
      merchantName,
      bussinessType: this.getBussinessType(sceneType),
      channelType: channelType || 1 //1问界 2 比亚迪 3 其他
    })
    this.tempRecord = dto
  }

  updateUserInfo() {
    try {
      uni.$logger.local.info('【录音服务RecordService】 == 更新用户信息')
      this.initDto()
      // 重新生成保存策略实例,以绑定新的 tempRecord (DTO)
      this.record = StrategyFactory.getSaveStrategy(this.tempRecord, this.triggerTempNumber.bind(this), this.attributesProvider.bind(this))
      this.triggerTempNumber()
    } catch (e) {
      uni.$logger.local.error(`【录音服务RecordService】 == 更新用户信息异常: ${e.message}`)
    }
  }

  // debounce(key, fn, delay) {
  //   if (this.debounceTimers[key]) {
  //     clearTimeout(this.debounceTimers[key].timer)
  //   }
  //   this.debounceTimers[key] = {
  //     fn,
  //     timer: setTimeout(() => {
  //       fn()
  //       delete this.debounceTimers[key]
  //     }, delay)
  //   }
  // }
  // flushAllDebounceTimers() {
  //   if (this.debounceTimers) {
  //     Object.keys(this.debounceTimers).forEach(key => {
  //       const item = this.debounceTimers[key]
  //       if (item) {
  //         clearTimeout(item.timer)
  //         try {
  //           item.fn()
  //           uni.$logger.local.info(`【录音服务RecordService】 == 强制执行防抖任务: ${key}`)
  //         } catch (e) {
  //           uni.$logger.local.error(`【录音服务RecordService】 == 强制执行防抖任务失败: ${key}, error: ${e.message}`)
  //         }
  //       }
  //     })
  //     this.debounceTimers = {}
  //   }
  // }

  updateCustomerInfo(customerInfo = {}) {
    const { customerName, phoneNumber, salesUuid, carModel, staffName: salesName, carBrand, carBrandId, oneCarBrand, oneCarBrandId } = customerInfo
    this.record.updatePreRecords({
      customerName,
      phoneNumber,
      carModel,
      salesUuid,
      salesName,
      carBrand,
      carBrandId,
      oneCarBrand,
      oneCarBrandId
    })
  }

  updateBookList(booksList) {
    const receptionCustomerPaySourceList = booksList.map(item => {
      return {
        id: item.id,
        sourceType: item.id,
        sourceUrl: item.imgUrl
      }
    })
    this.record.updatePreRecords({ receptionCustomerPaySourceList })
  }

  updateMaterialPointList(receptionTrack) {
    const { merchantId, staffUuid, staffName } = this.tempRecord || {}
    const { sceneType } = uni.$storage.get('userInfo') || {}
    let receptionCustomerMaterialPointList = []
    Object.keys(receptionTrack).map(key => {
      receptionCustomerMaterialPointList.push({
        ...receptionTrack[key],
        merchantId,
        staffUuid,
        staffName,
        businessScene: sceneType
      })
    })
    // 优化:将高频更新的物料点数据存入 LocalStorage
    if (this.record) {
      this.record.cacheMaterialPoints(receptionCustomerMaterialPointList)
    }
  }

  updateReceptionStatus(status) {
    this.record.updatePreRecords({ receptionStatus: status })
  }

  getRecorder() {
    return this.record
  }

  async triggerTempNumber() {
    if (!this.record) return
    const _records = await this.record.getRecords()
    store.commit('audio/setPerRecordNumber', _records.length)
  }

  async isPermission(hintText = '为了记录语音通话,请打开录音权限') {
    const result = await permission.requestAndroidPermission('android.permission.RECORD_AUDIO')
    await helpler.sleep(0)
    if (result !== 1) {
      uni.showToast({
        title: hintText,
        icon: 'none'
      })
    }
    return result === 1
  }

  async checkBeforeStart() {
    const isPermission = await this.isPermission()
    const isRecording = this.audioManager.isRecording
    return isPermission && !isRecording
  }

  reportError(msg, errorMsg) {
    uni.$logger.local.error(`【录音服务RecordService】 == ${msg}`)
    // TODO: 如果有统一的上报机制,可以在这里调用
  }

  destroy() {
    this.unWatch()
    this.record?.destroy()
    this.stop()
    this.reset()
  }

  unWatch() {
    this.unwatchBookList?.()
    this.unwatchCustomer?.()
    this.unwatchReceptionKey?.()
    this.unwatchStatus?.()
  }
}

export default RecordService