TempRecord.js 17.1 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 519 520 521 522 523 524 525 526
/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: limin
 * @Date: 2025-01-02 18:49:17
 * @LastEditors: limin
 * @LastEditTime: 2025-12-25 09:07:31
 * @FilePath: \simgle_app\utils\recordManager\TempRecord.js
 */
import utils from '../utils'
import helpler from './helpler'
import { FileStatus } from '../common/constants'
class TempRecord {
  timer = null
  timer_interval = 30 * 1000
  record = null
  path = ''
  newRecord = null
  onTempRecordNumberChanged = null
  /**
   * 构造函数
   * @param {Object} record - 新建接待记录的初始字段(如客户信息等)
   * @param {Function} onTempRecordNumberChanged - 临时记录数量变化时的回调
   */
  constructor(record, onTempRecordNumberChanged) {
    this.newRecord = record
    this.recordManager = uni.$dbTempRecord
    this.dbRecord = uni.$dbRecord
    this.onTempRecordNumberChanged = onTempRecordNumberChanged
  }
  /**
   * 获取全部临时记录
   * @returns {Array} 临时记录列表
   */
  getRecords() {
    return this.recordManager.getRecords()
  }
  /**
   * 根据 id 获取单条临时记录
   * @param {string} id - 临时记录的唯一标识
   * @returns {Object|null} 找到则返回记录,否则返回 null
   */
  getRecord(id) {
    return this.recordManager.getRecordById(id)
  }
  /**
   * 添加一条临时记录并触发数量变化通知
   * @param {Object} [record=this.record] - 要添加的记录对象
   * @returns {Promise<void>}
   */
  async addRecord(record = this.record) {
    await this.recordManager.addRecord(record)
    uni.$logger.local.info('〖接待记录Record〗 == 新增临时记录 id: ' + record.id)
    this.triggleRecordNumChanged()
  }
  /**
   * 更新临时记录(部分字段)
   * @param {Object} item - 需要更新的字段键值对
   * @param {Object} where - 更新条件(一般为 { id })
   * @returns {Promise<void>}
   */
  updateRecord(item, where) {
    return this.recordManager.updateRecord(item, where)
  }
  /**
   * 删除一条临时记录并触发数量变化通知
   * @param {string} id - 临时记录 id
   * @returns {Promise<void>}
   */
  async removeRecord(id) {
    await this.recordManager.removeRecord(id)
    uni.$logger.local.info('〖接待记录Record〗 == 删除临时记录 id: ' + id)
    this.triggleRecordNumChanged()
  }
  /**
   * 更新当前内存中的记录并同步到数据库(值未变则跳过)
   * @param {string} key - 字段名
   * @param {*} value - 字段值
   * @returns {Promise<void>|undefined} 值未变化时返回 undefined
   */
  async __update(key, value) {
    if (this.record[key] === value) return
    this.record[key] = value
    return this.updateRecord({ [key]: value }, { id: this.record.id })
  }
  /**
   * 获取客户端文件保存基础路径(带缓存)
   * @returns {Promise<string>} 保存路径(例如 `_doc/`)
   */
  async getFilePath() {
    if (!this.path) {
      this.path = await utils.getFileSaveFolderOnClient()
      uni.$logger.local.info('〖接待记录Record〗 == 初始化文件保存路径 -> ' + this.path)
    }
    return this.path
  }
  /**
   * 将当前临时记录持久化到正式记录表,并清理本地数据
   * - 开始前会停止轮询
   * - 会对过长的录音列表进行截断
   * @param {Object} [record=this.record] - 要保存的记录
   * @returns {Promise<void>}
   */
  async save(record = this.record) {
    try {
      if (!record) throw new Error('记录对象为空')
      uni.$logger.local.info('〖接待记录Record〗 == 开始持久化记录 ==' + JSON.stringify(record))
      this.clearLoopTimer()
      await this.saveTempFile(record)
      const { urlList, tempFilePath, endReasonType, ...__record } = record
      const recordLongList = await this.__analysisUrlList(urlList)
      const { maxUploadNum = 10 } = uni.$storage.get('mock_data')
      if (recordLongList.length > maxUploadNum) {
        const userInfo = uni.$storage.get('userInfo')
        const { customerName, phoneNumber, carModel, salesName } = record || {}
        const { name } = userInfo || {}
        uni.$logger.error({
          msg: `员工: ${name}, 客户: ${customerName}`,
          extra: {
            '手机号: ': phoneNumber,
            '姓名: ': customerName,
            '销售: ': salesName,
            '车型: ': carModel,
            '原因: ': '录音文件过长,数量' + recordLongList.length
          }
        })
      }
      __record.urlList = recordLongList.slice(0, maxUploadNum)
      uni.$logger.local.info('〖接待记录Record〗 == 更新文件,保存记录!')
      await this.dbRecord.addRecord(__record)
      await this.clearLocalRecord(record)
    } catch (error) {
      uni.$logger.local.error('〖接待记录Record〗 == 保存记录异常' + error.message)
    }
  }
  async clearLocalRecord(record = this.record) {
    const { id, tempFilePath } = record || {}
    uni.$logger.local.info('〖接待记录Record〗 == 删除临时文件' + tempFilePath)
    await this.removeFile(tempFilePath)
    if (id) {
      await this.removeRecord(id)
    }
    this.record = null
    this.path = ''
    uni.$logger.local.info('〖接待记录Record〗 == 置空接待记录')
  }
  /**
   * 清除已保存的录音文件
   * @param {Object} options - 配置参数
   * @param {Array} options.urlList - 录音文件列表,默认为当前记录的urlList
   */
  clearSavedFiles({ urlList = [] } = this.record) {
    // 遍历录音文件列表并删除每个文件
    urlList.forEach(item => {
      uni.$logger.local.warn('〖接待记录Record〗 == 清除已保存文件 -> ' + item.file)
      this.removeFile(item.file)
    })
  }
  /**
   * 将已保存的文件列表映射为上传列表(统一拼接基础保存路径)
   * @param {Array} urlList - 已保存文件路径列表(形如 { file })
   * @returns {Promise<Array>} 规范化后的上传列表(形如 { status, file })
   */
  async __analysisUrlList(urlList) {
    if (!urlList?.length) return []
    try {
      const basePath = await this.getFilePath()
      const list = []
      for (const item of urlList) {
        const filePath = item?.file
        if (typeof filePath === 'string' && filePath.length > 0) {
          const baseName = filePath.split('/').pop()
          list.push({
            status: FileStatus.Waiting,
            file: basePath + baseName
          })
        } else {
          uni.$logger.local.warn('〖接待记录Record〗 == 有文件为空路径,舍弃!! ==')
        }
      }
      return list
    } catch (error) {
      uni.$logger.local.error('〖接待记录Record〗 == 解析接待文件列表异常' + error.message)
      throw new Error(error.message)
    }
  }
  /**
   * 添加新的接待记录
   * - 创建内存中的记录对象
   * - 同步写入临时记录数据库
   * - 启动音频处理流程
   * @returns {Promise<void>}
   */
  async add() {
    this.reset()
    // 创建一个新的记录对象
    this.record = this.__createNewRecord()
    // 异步添加新创建的记录对象
    await this.addRecord(this.record)
    // 添加音频资源
    this.addAudio()
  }
  reset() {
   this._isDestroyed = false
  }
  /**
   * 构造一条新的接待记录的初始对象
   * @returns {Object} 新记录对象(含 id、开始时间、空的录音列表等)
   */
  __createNewRecord() {
    return {
      id: utils.uuid(),
      ...this.newRecord,
      startTime: this.getTimeNow(),
      endTime: '',
      urlList: []
    }
  }

  /**
   * 添加音频
   * @param {Object} isUpdate - 是否更新音频
   * @returns {void}
   */
  // Update the record with the new information
  async addAudio() {
    this.clearLoopTimer()
    await this.processPreviousAudio()
    await helpler.sleep(1500)
    await this.addNewAudioAndStartLoop()
  }

  /**
   * 处理上一个临时文件
   * 1. 持久化保存上一个临时文件并更新本地路径到数据库
   * 2. 删除上一个临时文件
   */
  async processPreviousAudio() {
    try {
      uni.$logger.local.info('〖接待记录Record〗 == 保存上一个临时文件!')
      await this.saveLastAudio()
      await this.removeOldTempAudio()
    } catch (e) {
      uni.$logger.local.error('〖接待记录Record〗 == 处理上一个录音失败' + e)
    }
  }

  /**
   * 添加新录音并启动保存循环
   * 1. 添加新录音
   * 2. 更新数据库路径
   * 3. 启动保存循环
   */
  async addNewAudioAndStartLoop() {
    try {
      await this.addNewAudioAndUpdate()
    } catch (e) {
      uni.$logger.local.error('〖接待记录Record〗 == 添加/更新新录音失败' + e)
    } finally {
      this.startSaveAudioLoop()
    }
  }
  /**
   * 添加新录音并同步更新数据库
   * - 在内存中成功添加临时路径后,调用 `updatePath` 持久化到临时表
   * @returns {Promise<void>}
   */
  async addNewAudioAndUpdate() {
    await this.addNewAudio()
    // 只有在内存中成功添加了录音路径,才去更新数据库
    if (this.record?.tempFilePath) {
      await this.updatePath()
      uni.$logger.local.info('〖接待记录Record〗 == 同步数据库路径成功 id: ' + this.record.id)
    }
  }

  /**
   * 读取最新的录音临时文件并尝试保存
   * - 支持重试机制
   * - 成功后更新内存状态与录音列表
   * @returns {Promise<void>}
   */
  async addNewAudio() {
    try {
      const lastAudio = await this.getLastAudioWithRetry()
      if (!lastAudio) {
        uni.$logger.local.warn('〖接待记录Record〗 == 未找到录音文件,跳过添加')
        return
      }
      uni.$logger.local.warn('〖接待记录Record〗 == 添加一个新的录音' + lastAudio)
      const savedPath = await this.saveFilePath(lastAudio)
      if (savedPath && this.record) {
        this.record.tempFilePath = lastAudio
        const last = this.record.urlList[this.record.urlList.length - 1]
        if (last && last.file === savedPath) {
          uni.$logger.local.warn('〖接待记录Record〗 == 录音未变化,跳过添加 -> ' + savedPath)
        } else {
          this.record.urlList.push({ file: savedPath })
          uni.$logger.local.warn('〖接待记录Record〗 == 添加新录音成功:' + savedPath)
        }
      }
    } catch (e) {
      uni.$logger.error(`〖接待记录Record〗 == 添加一个新的录音失败'  ${e.message} ${JSON.stringify(e)}`)
    }
  }
  /**
   * 重试读取最近一次录音临时文件路径
   * @param {number} [maxRetries=3] - 最大重试次数
   * @param {number} [delayMs=500] - 每次重试的等待毫秒数
   * @returns {Promise<string>} 找到则返回路径,否则返回空字符串
   */
  async getLastAudioWithRetry(maxRetries = 3, delayMs = 500) {
    let lastAudio = ''
    for (let i = 0; i < maxRetries; i++) {
      lastAudio = await helpler.getLatestAudioFilePath()
      if (lastAudio) break
      await helpler.sleep(delayMs)
    }
    return lastAudio
  }

  /**
   * 删除上一个临时录音文件并重置路径
   * @returns {Promise<void>}
   */
  async removeOldTempAudio() {
    const { tempFilePath } = this.record
    uni.$logger.local.info('〖接待记录Record〗 == 删除上一个临时文件 -> ' + tempFilePath)
    await this.removeFile(tempFilePath)
    // 删除文件后,显式置空路径,防止干扰后续逻辑
    this.record.tempFilePath = ''
    return
  }

  /**
   * 将当前内存中的临时路径与录音列表同步到数据库临时表
   * @returns {Promise<void>}
   */
  updatePath() {
    const { id, tempFilePath, urlList } = this.record
    return this.updateRecord({ tempFilePath, urlList }, { id })
  }
  /**
   * 保存文件
   * @param {Object} record - 接待记录对象
   * @returns  - 返回保存后的文件路径
   */
  async saveTempFile(record = this.record) {
    let { tempFilePath, urlList } = record
    if (!tempFilePath || urlList.length === 0) {
      if (!this.timer) {
        uni.$logger.local.warn('〖接待记录Record〗 == 无可保存的临时录音,当前未在轮询中,跳过自动补录')
        return
      }
      uni.$logger.local.warn('〖接待记录Record〗 == 无可保存的临时录音,轮询中尝试添加新录音')
      await this.addNewAudioAndUpdate()
      return
    }
    const lastIndex = urlList.length - 1
    if (lastIndex < 0 || !tempFilePath) return
    const { file } = urlList[lastIndex]
    const saveResultPath = await this.saveFilePath(tempFilePath)
    if (saveResultPath) {
      uni.$logger.local.info('〖接待记录Record〗 == 删除上一次保存的文件 ' + file)
      await this.removeFile(file)
      record.urlList[lastIndex].file = saveResultPath
    }
    return saveResultPath
  }
  /**
   * 将临时文件保存到持久化目录(兼容不同返回结构)
   * @param {string} tempFilePath - 临时文件路径
   * @returns {Promise<string|undefined>} 保存成功返回持久化路径,失败返回 undefined
   */
  async saveFilePath(tempFilePath) {
    uni.$logger.local.info('〖接待记录Record〗 == 开始保存临时录音 tempFilePath-> ' + tempFilePath)
    if (!tempFilePath) return
    try {
      const saveResult = await uni.saveFile({
        tempFilePath
      })
      // 兼容 uni.saveFile 可能返回数组 [err, res] 或直接返回对象的情况
      let saveResultPath = ''
      if (Array.isArray(saveResult)) {
        saveResultPath = saveResult[1]?.savedFilePath
      } else {
        saveResultPath = saveResult?.savedFilePath
      }
      if (!saveResultPath) {
        uni.$logger.local.error('〖接待记录Record〗 == 保存文件失败,路径为空')
        return
      }
      uni.$logger.local.info('〖接待记录Record〗 == 保存后的文件路径 saveResultPath ->' + saveResultPath)
      return saveResultPath
    } catch (e) {
      uni.$logger.local.error('〖接待记录Record〗 == 保存文件异常: ' + e.message)
      return
    }
  }
  /**
   * 删除文件(持久化路径使用 `uni.removeSavedFile`)
   * @param {string} filePath - 要删除的文件路径(可能为 `_doc/...` 或其他)
   * @returns {Promise<void>}
   */
  removeFile(filePath) {
    if (!filePath) return
    return new Promise(resolve => {
      try {
        uni.removeSavedFile({ filePath, complete: resolve })
      } catch (e) {
        resolve()
      }
    })
  }
  /**
   * 在轮询中保存最后一个临时录音并更新列表
   * @returns {Promise<void>}
   */
  async saveLastAudio() {
    try {
      const __path = await this.saveTempFile()
      __path && this.updateUrlList()
    } catch (e) {
      uni.$logger.local.error('〖接待记录Record〗 == 轮询保存异常: ' + e.message)
    }
  }

  /**
   * 将当前内存的 `urlList` 写回数据库
   * @returns {Promise<void>}
   */
  updateUrlList() {
    const { id, urlList } = this.record
    return this.updateRecord({ urlList }, { id })
  }
  /**
   * 启动保存临时录音的轮询
   * - 若已启动则跳过
   * @returns {void}
   */
  startSaveAudioLoop() {
    if (this.timer) {
      uni.$logger.local.info('〖接待记录Record〗 == 轮询已启动,跳过')
      return
    }
    if(this._isDestroyed) {
      uni.$logger.local.warn('〖接待记录Record〗 == 组件已销毁,忽略 startSaveAudioLoop')
      return
    }
    uni.$logger.local.info('〖接待记录Record〗 == 启动轮询 ' + this.timer_interval + 'ms')
    this.timer = setInterval(this.saveLastAudio.bind(this), this.timer_interval)
  }
  async destroy() {
    this._isDestroyed = true
    this.clearLoopTimer()
    // await this.clearLocalRecord()
    uni.$logger.local.info('〖接待记录Record〗 == TempRecord 实例已销毁')
  }

  /**
   * 停止保存轮询并清理定时器句柄
   * @returns {void}
   */
  clearLoopTimer() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
      uni.$logger.local.info('〖接待记录Record〗 == 停止轮询 (定时器已清除)')
    } else {
      uni.$logger.local.info('〖接待记录Record〗 == 停止轮询 (无定时器)')
    }
  }

  /**
   * 获取当前内存中的接待记录对象
   * @returns {Object|null} 当前记录,可能为空
   */
  get currentRecord() {
    return this.record
  }
  /**
   * 设置接待结束时间为当前时间并同步到数据库
   * @returns {Promise<void>}
   */
  setReceptionEndTime() {
    return this.__update('endTime', this.getTimeNow())
  }
  /**
   * 获取当前时间字符串(格式化)
   * @returns {string} 形如 `YYYY/MM/DD HH:mm:ss`
   */
  getTimeNow() {
    return utils.convertDateTimeFormat(new Date(), '-')
  }
  /**
   * 标记记录为错误结束原因
   * @returns {Promise<void>}
   */
  withError() {
    return this.__update('endReasonType', 1)
  }
  /**
   * 批量更新当前记录的多个预填字段
   * @param {Object} items - 需要更新的键值对
   * @returns {Promise<Object>} 返回更新后的记录对象
   */
  async updatePreRecords(items) {
    if (items) {
      for (const key of Object.keys(items)) {
        await this.__update(key, items[key])
      }
    }
    return this.record
  }
  /**
   * 触发临时记录数量变化通知
   * @returns {Promise<void>|void}
   */
  async triggleRecordNumChanged() {
    if (this.onTempRecordNumberChanged) {
      this.onTempRecordNumberChanged()
      uni.$logger.local.info('〖接待记录Record〗 == 通知临时记录数变化')
    }
  }
}
export default TempRecord