Record.js 7.59 KB
import { getRecords } from "../cache/storageApi"

class Record {
  key = 'preRecord'
  timer = null
  timer_interval
  constructor() {
    this.recordManager = uni.$recordManager
    this.dbManager = uni.$dbManager
  }

  getRecords(){
    return this.recordManager.getRecords(this.key)
  }
  getRecord() {
    return this.recordManager.getRecord(this.key)
  }
  addRecord(record) {
    this.recordManager.addRecord(record, this.key)
  }
  updateRecord(record) {
    this.recordManager.updateRecord(record, this.key)
  }
  removeRecord(id) {
    this.recordManager.removeRecord(id,this.key)
  }
  async save(record) {
    const __record = await this.saveTempFile(record)
    await this.dbManager.addRecord(__record)
    this.removeRecord(record.id)
  }
  addOrUpdate(record) {
    const record = this.recordManager.getRecordById(record.id, this.key)
    if (record) {
      this.updateRecord(record)
    } else {
      this.addRecord(record)
    }
  }
  async add(customerInfo, booksList, receptionStatus) {
    const params = this.getParams(customerInfo, booksList, receptionStatus)
    const id = utils.uuid()
    this.record = {
      id,
      ...params,
      recordUrlList: []
    }
    return this.addAudio()
  }

  async saveTempFile(record) {
    const lastIndex = record.recordUrlList.length - 1
    if (lastIndex < 0) return
    const filePath = record.recordUrlList[lastIndex]
    const saveResult = await uni.saveFile({
      tempFilePath: filePath
    })
    if (filePath) {
      uni.removeSavedFile({
        filePath,
        complete: () => console.log('complete')
      })
    }
    record.recordUrlList[lastIndex] = saveResult[1].savedFilePath
    return record
  }

  async saveLastVideo() {
    const record = this.preRecord
    const __record = await this.saveTempFile(record)
    this.updateRecord(__record)
  }

  setLoopAudio() {
    this.timer = setInterval(() => {
      this.saveLastVideo()
    }, 1000 * 30)
  }

  get preRecord() {
    return this.record
  }

  async addAudio() {
    clearInterval(this.timer)
    await this.saveTempFile()
    const lastAudio = await this.getAudioFilePath()
    this.record.recordUrlList.push(lastAudio)
    this.addOrUpdate(this.record)
    this.setLoopAudio()
  }

  async getAudioPathName() {
    return new Promise(async (resolve, reject) => {
      const path = await utils.getAudioFilePath()
      plus.io.resolveLocalFileSystemURL(
        path,
        e => {
          var dirR = e.createReader()
          dirR.readEntries(
            function (er) {
              Promise.all(
                er.map((item, index) => {
                  console.log(item, 'item')
                  return new Promise(resolve => {
                    item.getMetadata(metadata => {
                      resolve({
                        index: index,
                        name: item.name,
                        modificationTime: new Date(metadata.modificationTime).getTime()
                      })
                    })
                  })
                })
              ).then(results => {
                console.log(results, 'results')
                results = results.filter(i => i.name.startsWith('uniapp_temp'))
                // 找到修改时间最晚的文件
                const latest = results.reduce(
                  (acc, current) => {
                    if (current.modificationTime > acc.modificationTime) {
                      return current
                    }
                    return acc
                  },
                  { modificationTime: 0 }
                )
                // 修改时间最晚的文件名
                resolve(latest.name)
              })
            },
            err => {
              reject(err)
            }
          )
        },
        err => {}
      )
    })
  }

  async getAudioFilePath() {
    const pathName = await this.getAudioPathName()
    return this.getAudioFilePath(pathName)
  }
  async getAudioPath(name) {
    console.log(name, 'name')
    return new Promise(async (resolve, reject) => {
      const path = await utils.getAudioFilePath(name + '/recorder')
      console.log(path, 'path')
      plus.io.resolveLocalFileSystemURL(
        path,
        e => {
          var dirR = e.createReader()
          dirR.readEntries(
            function (er) {
              Promise.all(
                er.map((item, index) => {
                  return new Promise(resolve => {
                    item.getMetadata(metadata => {
                      resolve({
                        index: index,
                        name: item.name,
                        modificationTime: new Date(metadata.modificationTime).getTime()
                      })
                    })
                  })
                })
              ).then(results => {
                console.log(results, 'results')
                // 找到修改时间最晚的文件
                const latest = results.reduce(
                  (acc, current) => {
                    if (current.modificationTime > acc.modificationTime) {
                      return current
                    }
                    return acc
                  },
                  { modificationTime: 0 }
                )
                // 修改时间最晚的文件名
                resolve(path + '/' + latest.name)
              })
            },
            err => {
              reject(err)
            }
          )
        },
        err => {}
      )
    })
  }

  updatePreRecords(customerInfo, booksList, receptionStatus) {
    const params = this.getParams(customerInfo, booksList, receptionStatus)
    const updateParams = { ...this.record, ...params }
    console.log(updateParams, 'updateParams')
    this.updateRecord(updateParams)
  }
  setRecords(records) {
    this.recordManager.setRecords(records, 'preRecordList')
    console.log(records, 'records')
    store.dispatch('audio/setPerRecordNumber', records.length)
  }

  getParams(customerInfo = {}, booksList, receptionStatus) {
    const { shopMerchantId, phone, sceneType, uuid, name, merchantId, channelType, merchantName } = uni.$storage.get('userInfo'),
      { customerName, phoneNumber, salesUuid, carModel, staffName } = customerInfo,
      receptionCustomerPaySourceList = booksList.map(item => {
        return {
          id: item.id,
          sourceType: item.id,
          sourceUrl: item.imgUrl
        }
      }),
      { receptionStartTime, receptionEndTime, endReasonType } = this.audioInfo,
      { deviceId: appCode } = uni.getDeviceInfo(),
      receptionTrack = this.$store.state.user.receptionTrack,
      receptionCustomerMaterialPointList = []
    Object.keys(receptionTrack).map(key => {
      receptionCustomerMaterialPointList.push({
        ...receptionTrack[key],
        merchantId: shopMerchantId,
        businessScene: sceneType,
        staffUuid: uuid,
        staffName: name
      })
    })
    let params = {
      staffUuid: uuid,
      staffName: name,
      serviceMerchantId: merchantId,
      carModel,
      endReasonType, //原因 1.异常 0.正常
      customerName,
      phoneNumber,
      appCode,
      loginPhone: phone,
      salesName: staffName,
      salesUuid,
      receptionStatus, //接待结果 1.成交 0.战败
      receptionStartTime,
      receptionEndTime,
      receptionCustomerPaySourceList, //1.付款凭证文件路径 2.客户购车发票文件路径 3.客户延保合同文件路径
      merchantId: shopMerchantId,
      merchantName,
      bussinessType: sceneType == 0 ? 1 : 2, // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
      channelType: channelType || 1, //1问界 2 比亚迪 3 其他
      receptionCustomerMaterialPointList
    }
    return params
  }
}
export default Record