uploader.js 14.7 KB
import { getOssToken } from '@/utils/ossUploadFile/uploadFile.js'
import Queue from '@/utils/Queue.js'
const interval = 60 * 5
let timer = null
export default {
  onLoad() {},
  data() {
    return {
      wv: null,
      snapshot: null
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    /**
     * 初始化函数
     * 这个函数在对象创建时被调用,它执行一系列的初始化任务
     *
     * @async
     * @returns {Promise<void>} 当初始化完成时,Promise 将解析为 undefined
     * @throws {Error} 如果初始化过程中出现错误,将抛出错误
     */
    async init() {
      this.wv = await this.initWebview()
      await this.enQueue()
      this.polling()
    },
    /**
     * 处理消息函数
     * 此函数用于处理接收到的消息
     * 它解构参数对象,获取代码、文件名、数据、记录 ID、文件路径和客户端文件路径等信息
     * 根据代码值决定下一步操作:若为 0,则上传成功,调用 uploadSuccess 函数;否则,开始轮询,调用 polling 函数
     *
     * @param {Object} result - 包含消息详情的对象
     * @throws {Error} 如果解构对象时缺少关键属性,将抛出错误
     */
    async handlerMessage(result) {
      const { code, fileName, data, recordId, filePath, filePathOnClient = filePath + fileName } = result.detail.data[0]
      try {
        if (code == 0) {
          const filePathOnServer = data.oss.res.requestUrls[0].split('?')[0]
          await this.uploadSuccess(recordId, filePathOnServer, filePathOnClient, fileName)
        } else {
          this.reportError(recordId, fileName, data)
        }
      } catch (e) {
        this.reportError(recordId, fileName, e)
      } finally {
        console.log('本次任务完成,开启下一次上传任务!')
        this.polling()
      }
    },
    /**
     * 上报文件上传失败日志
     */
    reportError(recordId, filePath, res) {
      const { customerName, phoneNumber, carModel, salesName } = uni.$recordManager.getRecordById(recordId) || {}
      const { name } = uni.$storage.get('userInfo') || {}
      this.$sendSentry(`上传失败:文件-${filePath} 手机号-${phoneNumber} 姓名-${customerName} 销售-${salesName} 车型-${carModel} 员工-${name}失败原因-${JSON.stringify(res)}`)
    },
    /**
     * 初始化 WebView 的异步函数
     * 这个函数返回一个 Promise,当初始化 WebView 完成时,它将解析为 WebView 对象。
     * 在页面初始化调用时,这个函数会延迟 1 秒,以确保 WebView 对象已经创建。
     *
     * @async
     * @returns {Promise<any>} 当初始化完成时,Promise 将解析为 WebView 对象。
     */
    initWebview() {
      return new Promise((resolve, reject) => {
        var currentWebview = this.$parent.$scope.$getAppWebview() //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
        let i = setInterval(() => {
          var wv = currentWebview.children()[0]
          if (wv) {
            clearInterval(i)
            wv.setStyle({ top: '100%', height: 300 })
            resolve(wv)
          }
        }, 100)
        // setTimeout(function () {
        //   var wv = currentWebview.children()[0]
        //   wv.setStyle({ top: '100%', height: 300 })
        //   resolve(wv)
        // }, 1000) //如果是页面初始化调用时,需要延时一下
      })
    },
    /**
     * 入列操作
     * 这个函数异步执行,目的是获取记录的快照并将其扁平化,以形成一个队列
     * 通过调用 getRecordsSnapshotFlatten 获取快照数据
     * 当所有数据准备好后,创建一个新的 Queue 实例,并将扁平化后的数据作为参数传入
     * 这样,队列就被创建并且最初是满的,其中包含了已经获取到的记录快照
     *
     * @async
     * @returns {Promise<void>} 一个 Promise,当初始化队列完成时解析,没有返回值
     * @throws {Error} 如果获取快照失败或扁平化数据失败,将抛出错误
     */
    async enQueue() {
      const _snapshot = await this.getRecordsSnapshotFlatten()
      this.snapshot = new Queue(_snapshot)
      console.log('创建任务快照.下一轮快照文件个数:', this.snapshot.size)
    },
    /**
     * 获取记录快照并展平数据
     * 此函数异步获取记录快照,然后使用flattenData函数将这些记录转换为一个文件对象列表
     * 每个文件对象都包含一个额外的recordId属性,用于指示它所属的记录
     *
     * @async
     * @returns {Promise<Array>} 一个Promise,当获取并处理完记录时,返回一个文件对象列表
     * @throws {Error} 如果在获取记录快照或展平数据的过程中出现错误,将抛出错误
     */
    async getRecordsSnapshotFlatten() {
      const _records = await this.getRecordsSnapshot()
      const _snapshot = this.flattenData(_records || [])
      return _snapshot
    },
    /**
     * 将指定记录上传到服务器
     * 此函数使用 WebView 的 evalJS 方法,将 OSS 令牌信息和记录详情传递给 UniApp 应用,以便进行文件上传
     *
     * @async
     * @param {Object} record - 要上传的记录对象,包含 fileName 和 filePath 属性
     * @returns {void} - 此函数不返回任何值
     * @throws {Error} - 如果获取 OSS 令牌的过程中出现错误,将抛出错误
     */
    async uploadRecord(record) {
      const { lsaccessKeySecret, securityToken, lsaccessKeyId } = await getOssToken()
      console.log('获取Token成功!!', `lsaccessKeySecret: ${lsaccessKeySecret},   lsaccessKeyId:  ${lsaccessKeyId}`)
      this.wv.evalJS(`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${record.fileName}','${record.filePath}','${record.recordId}')`)
    },
    /**
     * 文件上传成功后的处理逻辑
     * 这个函数在文件上传成功后执行,它接受四个参数:recordId、filePathOnServer、filePathOnClient 和 fileName
     * 函数首先获取记录锁,然后尝试获取对应的记录。如果记录存在,它将客户端路径的文件记录更新为服务器路径,并移除 client 文件。
     * 接着,它调用一个名为 _saveOrUpdate 的私有方法,这个方法可能会上传记录。
     * 无论是尝试获取记录失败,还是在处理过程中出现任何其他错误,都会被捕获并作为 error 参数传递给 Promise.reject 方法,表明发生错误。
     * 无论成功或失败,最终都会执行 finally 块中的代码。这里首先释放记录锁,然后调用 polling 方法,可能是为了继续下一次文件上传。
     *
     * @async
     * @param {string} recordId - 要更新的记录的 ID
     * @param {string} filePathOnServer - 文件在服务器上的新路径
     * @param {string} filePathOnClient - 文件在客户端的旧路径
     * @param {string} fileName - 文件的原始名称
     * @throws {Error} 如果获取记录失败或发生任何其他错误,将抛出错误
     */
    async uploadSuccess(recordId, filePathOnServer, filePathOnClient, fileName) {
      const unlock = await uni.$recordManager.lock()
      try {
        const record = uni.$recordManager.getRecordById(recordId)
        if (!record) return
        this._changeFilePathToServer(record, filePathOnClient, filePathOnServer, fileName)
        await this._saveOrUpdate(record, filePathOnClient)
      } catch (err) {
        throw new Error(err)
      } finally {
        unlock()
      }
    },
    /**
     * 将记录中的文件路径更改为服务器路径
     * 此函数遍历记录中的每个文件信息对象
     * 将文件信息对象中的 file 属性值与 filePathOnClient 或 fileName 进行比较
     * 如果匹配,则将 file 属性更新为 filePathOnServer,并删除 status 属性
     *
     * @param {Object} record - 包含文件信息列表的记录对象
     * @param {string} filePathOnClient - 需要替换的客户端文件路径
     * @param {string} filePathOnServer - 需要更新的服务器文件路径
     * @param {string} fileName - 需要替换的文件名
     * @throws {Error} 如果 record 参数无效或 recordFileList 属性不存在,将抛出错误
     */
    _changeFilePathToServer(record, filePathOnClient, filePathOnServer, fileName) {
      record.recordUrlList?.forEach(fileInfo => {
        if (fileInfo.file === filePathOnClient || fileInfo.file.endsWith(fileName)) {
          fileInfo.file = filePathOnServer
          delete fileInfo.status
        }
      })
    },
    /**
     * 从客户端移除文件
     * 此函数使用 uni.removeSavedFile 方法删除指定路径的文件。该方法是一个异步操作,完成时会调用传入的 complete 回调函数。
     *
     * @param {string} filePathOnClient - 要删除的文件在客户端的文件路径
     * @param {Object} complete - (可选) uni.removeSavedFile 完成时调用的回调函数。函数参数是一个包含 statusCode 和 errMsg 的对象。
     * @throws {Error} 如果 filePathOnClient 参数无效或文件删除过程中发生错误,将抛出错误
     */
    _removeFileOnClient(filePathOnClient) {
      //删除客户端的文件
      uni.removeSavedFile({
        filePath: filePathOnClient,
        complete: function (res) {
          console.log(res)
        }
      })
    },
    /**
     * 保存或更新记录
     * 这个函数检查记录中的文件列表,以确定是保存还是更新记录
     * 如果所有文件记录条目状态都为未定义,函数将创建一个新的记录对象,调用保存 API,并在成功时移除记录
     * 如果文件记录条目状态不全为未定义,函数将更新记录
     *
     * @async
     * @param {Object} record - 要保存或更新的记录对象
     * @throws {Error} 如果在保存或更新记录时发生错误,将抛出错误
     */
    async _saveOrUpdate(record, filePathOnClient) {
      if (record.recordUrlList?.every(i => i.status == undefined)) {
        const pathArr = record.recordUrlList.map(i => i.file)
        const params = { ...record, recordUrlList: pathArr }
        if (!params.receptionEndTime) {
          const endTime = await uni.$api.commonApi.searchRecordingEndTime({ recordUrlList: pathArr, receptionStartTime: params.receptionStartTime.replace(/\//g, '-') })
          params.receptionEndTime = endTime.replace(/\-/g, '/')
        }
        console.log(params, 'params')
        const res = await uni.$api.commonApi.saveRecCustomer(params)
        if (res) {
          uni.$recordManager.removeRecord(record.id)
          this._removeFileOnClient(filePathOnClient)
        }
      } else {
        uni.$recordManager.updateRecord(record)
        this._removeFileOnClient(filePathOnClient)
      }
    },

    /**
     * 获取记录快照的异步函数
     * 此函数获取当前记录列表的快照,并返回这些记录
     *
     * @async
     * @returns {Promise<Array>} 解析为包含记录列表的 Promise
     */
    async getRecordsSnapshot() {
      const unlock = await uni.$recordManager.lock()
      const records = uni.$recordManager.getRecords()
      unlock()
      return records
    },
    /**
     * 展开数据
     * 将嵌套的记录列表转换为平面的文件对象列表,其中每个文件对象都包含一个 recordId 属性
     *
     * @param {Array} records - 要展开的记录列表
     * @returns {Array} - 展开后包含文件对象的列表,每个文件对象都包含一个 recordId 属性
     */
    flattenData(records) {
      const result = records.reduce((acc, cur) => {
        const recordUrlList = cur.recordUrlList.map(file => {
          if (!file.status) {
            return []
          }
          const aFullPath = file.file.split('/')
          const fileName = aFullPath.pop()
          const filePath = aFullPath.join('/') + '/'
          return { ...file, recordId: cur.id, fileName, filePath }
        })
        acc = acc.concat(...recordUrlList)
        return acc
      }, [])
      return result
    },
    /**
     * 轮询函数
     * 这个函数用于检查一个队列的大小,并在需要时执行文件上传操作
     * 如果队列大小为 0,则调用 enQueue() 函数来获取新的文件进行上传,并延迟一段时间后再次轮询
     * 如果队列不为 0,则从队列中取出一个记录并调用 uploadRecord(record) 函数进行上传
     * 如果在获取网络状态或上传过程中出现错误,它将捕获错误并在指定的时间间隔后重新开始轮询
     *
     * @throws {Error} 如果在上传过程中发生错误,将抛出错误,延迟 interval 后继续 polling
     */
    polling() {
      console.log(this.snapshot.size, '当前待上传文件快照数量')
      if (this.snapshot === null) return
      // prettier-ignore
      uni.$isNetWork().then(this.upload).catch(e =>{
        console.log('网络错误',e);
        this.reportError('', '异常', e)
        this.pollingLater(interval)
      })
    },
    /**
     * 上传文件或执行队列操作
     * 检查队列大小,以确定是上传单个文件还是通过 enQueue() 函数获取新的文件进行上传
     *
     * @throws {Error} 如果在上传过程中发生错误,将抛出错误,延迟 interval 后继续 polling
     */
    async upload() {
      if (this.snapshot.size == 0) {
        this.pollingLater(interval)
        this.enQueue()
      } else {
        let record = this.snapshot.dequeue()
        await this.uploadRecord(record)
      }
    },
    /**
     * 停止轮询并清除队列
     * 这个函数用于停止轮询操作,并清除队列中的所有记录
     * 首先,它调用 snapshot.clear() 方法清除队列
     * 然后,它将 snapshot 对象设置为 null,以释放资源并停止轮询
     */
    stopPolling() {
      if (this.snapshot) {
        this.snapshot.clear()
        this.snapshot = null
      }
      if (timer) clearTimeout(timer)
    },
    /**
     * 在指定的时间间隔后启动轮询
     * 这个函数用于在指定的时间间隔后执行轮询操作
     * @param {number} [interval=60*10] - 轮询间隔(默认为10分钟)
     * @returns {void} - 此函数不返回任何值
     */
    pollingLater(interval = 60 * 10) {
      if (timer) clearTimeout(timer)
      timer = setTimeout(() => {
        this.polling()
      }, interval * 1000)
      console.log(interval + 's后开始下一轮上传!')
    }
  },
  /**
   * 在组件销毁之前执行的生命周期函数
   * 这个函数在组件被销毁之前被调用,可以在这里进行一些清理工作
   * 在这个例子中,使用 console.log 输出 'topPolling',并调用 this.stopPolling() 方法
   *
   * @private
   * @returns {void} 没有返回值
   * @throws {Error} 调用 this.stopPolling() 时可能出现的错误
   */
  beforeDestroy() {
    this.stopPolling()
  }
}