RecordService.js 9.23 KB
import { AudioManager, RecordDto, helpler, StrategyFactory, TimeoutService } from './index.js'
import { storageApi } from '@/utils/cache'
import { getOAID } from '@/utils/deviceInfo'
import permision from '@/js_sdk/wa-permission/permission.js'
import store from '@/store'

class RecordService {
  static instance = null

  constructor() {
    this.audioManager = null
    this.recorder = null
    this.tempRecord = null
    this._startAudioPromise = null
    // init 是 async,但构造函数不能 await;用 Promise 让外部在 start 前等待初始化完成
    this._initPromise = null
    this.timeoutService = null
    // 初始化
    this._initPromise = this.init()
  }

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

  async init() {
    if (this.audioManager) return // 避免重复初始化

    this.audioManager = new AudioManager(this.onAudioStart.bind(this), this.onAudioStop.bind(this), this.onAudioError.bind(this))
    await this.initDto()
    this.recorder = StrategyFactory.getSaveStrategy(this.tempRecord, this.triggleTempNumber.bind(this), this.attributesProvider.bind(this))
    this.timeoutService = new TimeoutService(this.onTimeOut.bind(this))
    this.triggleTempNumber()
    this.initWatchers()
  }

  initWatchers() {
    // 监听 customerKey
    this.unwatchCustomer = store.watch(
      (state, getters) => getters.customerKey,
      () => {
        this.handler(this.customerInfo, this.updateCustomerInfo)
      },
      { immediate: true }
    )

    // 监听 receptionStatus
    this.unwatchStatus = store.watch(
      (state, getters) => getters.receptionStatus,
      val => {
        this.handler(val, this.updateReceptionStatus)
      },
      { immediate: true }
    )
  }

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

  // --- 状态与属性 Getter ---

  get getters() {
    return store.getters
  }

  // 模拟 mixin 中的 computed 映射
  get customerInfo() {
    return this.getters.customerInfo
  }
  get receptionStatus() {
    return this.getters.receptionStatus
  }
  // get receptionTrack() { return this.getters.receptionTrack }
  // get receptionKey() { return this.getters.receptionKey }
  get customerKey() {
    return this.getters.customerKey
  }
  get typeCode() {
    return this.getters.typeCode
  }
  get materialId() {
    return this.getters.materialId
  }

  // 模拟 mixin 中的 mutations
  commit(type, payload) {
    store.commit(type, payload)
  }

  setReceptionStatus(status) {
    this.commit('audio/setReceptionStatus', status)
  }

  setPerRecordNumber(number) {
    this.commit('audio/setPerRecordNumber', number)
  }

  clearCustomerInfo() {
    this.commit('clearCustomerInfo')
  }

  // --- 核心业务逻辑 ---

  async initDto() {
    const userInfo = storageApi.getUserInfo() || {}
    const { userId, userName } = userInfo
    const machineCode = await getOAID()
    const dto = new RecordDto({
      userId,
      userName,
      machineCode
    })
    this.tempRecord = dto
  }

  /**
   * 获取动态属性,用于 TempRecord 创建新记录时回调
   */
  attributesProvider() {
    const typeItem = uni.$storage.get('typeItem') || {}
    const { storeCode } = uni.$storage.get('storeInfo') || {}
    const dynamicAttrs = {
      typeCode: typeItem.typeCode || '',
      materialId: this.materialId || '',
      merchantId: storeCode || '',
    }
    uni.$logger.local.warn(`〖RecordService〗 == 创建新记录,注入动态属性: ${JSON.stringify(dynamicAttrs)}`)
    return dynamicAttrs
  }

  initReception() {
    this.clearCustomerInfo()
  }

  // --- 音频回调处理 ---

  async onAudioStart(res) {
    try {
      if (this.audioManager.counter === 0) {
        uni.$logger.local.info('〖RecordService〗 == First audio segment, adding record...')
        await this.recorder.add(res)
        uni.$logger.local.info('〖RecordService〗 == Record added successfully.')
      } else {
        this.recorder.addAudio(res)
      }
    } catch (e) {
      uni.$logger.local.error('〖RecordService〗 == onAudioStart error: ' + e.message)
    }
  }

  async onAudioStop() {
    if (this.audioManager.isRecording) {
      uni.$logger.local.warn('〖RecordService〗 == 接待中,再次开启录音! ')
      this.audioManager.start()
    } else {
      uni.$logger.local.warn('〖RecordService〗 == 断开录音! ')
    }
  }

  onAudioError(error) {
    const message = error.message
    this.reportError(`录音异常: error: ${message}`, message)
  }

  reportError(title, message) {
    // 这里需要根据实际情况实现错误上报,或者通过事件通知外部
    uni.$logger.local.error(`${title}: ${message}`)
    // 如果有全局的错误处理机制,可以在这里调用
  }

  // --- 录音控制 ---

  async startAudio(isInitData = true) {
    // 确保 init 完成后再启动计时/录音
    await this._initPromise
    if (this._startAudioPromise) return this._startAudioPromise
    this._startAudioPromise = (async () => {
      try {
        console.warn('[record] startAudio enter')
        const isPermission = await this.checkBeforeStart()
        console.warn('[record] checkBeforeStart result =', isPermission)
        if (!isPermission) return false // 返回 false 表示未成功启动
        uni.$logger.local.warn('〖RecordService〗 == 开始接待 ')

        isInitData && this.initReception()
        this.audioManager.start()
        this.timeoutService.start()
        console.warn('[record] startAudio started')
        return true // 返回 true 表示成功启动
      } catch (e) {
        console.error('[record] startAudio failed', e)
        return false
      } finally {
        this._startAudioPromise = null
      }
    })()
    return this._startAudioPromise
  }

  async stopAudio(isNotSave = false) {
    if (!this.isReceptioning()) {
      uni.$logger.local.warn('〖RecordService〗 == 未开始接待,不能结束接待! ')
      return
    }
    uni.$logger.local.info('〖RecordService〗 == 结束接待! ')
    this.stop()
    try {
      await this.saveAndClearRecord(isNotSave)
    } catch (error) {
      uni.$logger.local.error(`〖RecordService〗 == 结束接待保存失败: ${error.message}`)
      this.reportError('结束接待保存失败', error.message)
    }
  }

  async saveAndClearRecord(isNotSave = false) {
    if (isNotSave) {
      uni.$logger.local.warn('〖RecordService〗 == 不保存记录! ')
      await this.recorder.clearSavedFiles()
      await this.recorder.clearLocalRecord()
      return
    }
    await this.recorder.setReceptionEndTime() // 设置接待结束时间
    // 如果不需要保存记录
    await this.recorder.save()
  }

  stop() {
    this.recorder?.clearLoopTimer()
    this.stopAudioRecord()
  }
  onTimeOut() {
    store.commit('audio/setReceptionStatus', 0)
    this.recorder.withError()
    this.stopAudioRecord()
  }
  stopAudioRecord() {
    this.audioManager?.stop()
    this.timeoutService?.stop()
  }

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

  reset() {
    this.audioManager = null
    this.recorder = null
    this.tempRecord = null
    this.timeoutService = null
  }

  destroy() {
    this.unwatchCustomer?.()
    this.unwatchStatus?.()
    this.recorder?.destroy()
    this.stop()
    this.reset()
  }

  // --- 数据更新 ---

  updateCustomerInfo(customerInfo = {}) {
    const { customerName, customerPhone, customerType, carType } = customerInfo
    const params = {
      customerName,
      customerPhone,
      customerType,
      carType
    }
    this.recorder?.updatePreRecords(params)
  }

  updateReceptionStatus(status) {
    this.recorder?.updatePreRecords({ result: status })
  }

  // --- 权限检查 ---

  async isPermission(hintText = '为了记录语音通话,请打开录音权限') {
    // #ifdef APP-PLUS
    try {
      const osName = typeof plus !== 'undefined' && plus && plus.os ? plus.os.name : ''
      if (osName === 'Android') {
        const result = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO')
        await helpler.sleep(0)
        if (result !== 1) {
          uni.showToast({
            title: hintText,
            icon: 'none'
          })
        }
        return result === 1
      }

      if (osName === 'iOS') {
        const granted = typeof permision.judgeIosPermission === 'function' ? permision.judgeIosPermission('record') : true
        if (!granted) {
          uni.showToast({
            title: hintText,
            icon: 'none'
          })
        }
        return !!granted
      }
    } catch (e) {
      uni.$logger?.local?.warn?.(`〖RecordService〗 == 权限检查异常,降级放行: ${e.message || e}`)
      return true
    }
    // #endif

    return true
  }

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

  // --- 辅助方法 ---

  async triggleTempNumber(records) {
    if (!this.recorder) return
    const _records = records || (await this.recorder.getRecords())
    this.setPerRecordNumber(_records.length)
  }

  getRecorder() {
    return this.recorder
  }
}

export default RecordService