click.js 9.93 KB
/*
 * @Author: 前端 qianduan01@didihu.com.cn
 * @Date: 2024-04-08 11:28:48
 * @LastEditors: 前端 qianduan01@didihu.com.cn
 * @LastEditTime: 2024-10-23 17:23:29
 * @FilePath: \gl_tape\mixin\click.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const recorderManager = uni.getRecorderManager()
const plug = uni.requireNativePlugin('html5app-recordaudio')
import interruptRecord from '@/utils/recordManager/interruptRecord'
const UPLOAD_STATUS = {
  // 上传状态
  success: 1,
  fail: 2
}
const AUDIO_STATUS = {
  START: 'start', //开始
  END: 'end', //结束
  ABNORMAL: 'abnormal' //异常
}
const audioTime = 10 * 60 * 1000
import { mapMutations, mapState } from 'vuex'
import utils from '@/utils/utils.js'
export default {
  data() {
    return {
      voicePath: '',
      timer: null,
      times: 0,
      timeout: 240,
      reaction: 1
    }
  },
  async mounted() {
    this.handleSave(false)
    // 获取当前页面栈数组
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const route = currentPage.route
    const url = ['pages/equity/index', 'pages/boutique/index']
    if (url.includes(route)) return
    this.initTime()
  },
  watch: {
    changeData: {
      handler(val) {
        console.log(val, 'val', this.audioInfo.audioStatus)
        if (this.audioInfo.audioStatus != AUDIO_STATUS.START) return
        const { customerInfo, booksList, receptionStatus } = val
        const params = this.getParams(customerInfo, booksList, receptionStatus)
        interruptRecord.updatePreRecords(params)
      },
      deep: true
    }
  },
  computed: {
    ...mapState('audio', ['receptionStatus', 'booksList', 'audioInfo']),
    ...mapState(['user.customerInfo']),
    changeData() {
      const customerInfo = this.$store?.state?.user?.customerInfo || {}
      const booksList = this.booksList || []
      const receptionStatus = this.receptionStatus
      return { customerInfo, booksList, receptionStatus }
    }
  },
  methods: {
    ...mapMutations('audio', ['setReceptionStatus', 'setBooks', 'setAudioInfo']),
    // //关闭提示
    tipCancel() {
      this.stopAudio()
      this.setReceptionStatus(0)
      this.setAudioInfo({ endReasonType: 1 })
      if (this.$refs.tipBox) {
        this.$refs.tipBox.close()
        let { sceneType } = uni.$storage.get('userInfo')
        uni.reLaunch({
          url: sceneType == 0 ? '/pages/equity/index' : '/pages/boutique/index'
        })
      }
    },
    //结束提示
    tipConfirm() {
      this.times = 0
      this.$refs.tipBox?.close()
    },
    closeAudio() {
      this.times = 0
      clearInterval(this.timer)
      this.timer = null
      this.stopAudio(AUDIO_STATUS.ABNORMAL)
      this.setReceptionStatus(0)
      this.setAudioInfo({ endReasonType: 1 })
    },
    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
    },
    /**
     * 修改文件名。
     * @param {旧的文件路径} oldFilePath
     * @param {新的文件名} newFileName
     */
    RenameFile(oldFilePath, newFileName) {
      plus.io.resolveLocalFileSystemURL(oldFilePath, entry => {
        entry.getParent(_oldFile => {
          entry.moveTo(_oldFile, '/' + newFileName, newFilePath => {
            console.log('newFilePath', newFilePath.fullPath)
          })
        })
      })
    },

    //开始录音
    startAudio: utils.throttle(async function () {
      if (this.audioInfo.audioStatus == AUDIO_STATUS.START) return
      this.setBooks([])
      this.$store.dispatch('clearCustomerInfo')
      this.setReceptionStatus('')
      this.initTime()
      this.setAudioInfo({ audioList: [], audioStatus: AUDIO_STATUS.START })
      recorderManager.onStart(() => {
        setTimeout(() => {
          const params = this.getParams(this.$store.state.user.customerInfo, this.booksList, this.receptionStatus)
          interruptRecord.addPreRecords(params)
        }, 1000)
      })
      recorderManager.start({
        duration: audioTime,
        sampleRate: 16000,
        numberOfChannels: 1
      })
      recorderManager.onStop(async res => {
        if (this.audioInfo.audioStatus == AUDIO_STATUS.START) {
          uni.getRecorderManager().start({
            duration: audioTime,
            sampleRate: 16000,
            numberOfChannels: 1
          })
        }
      })
    }, 300),
    /**
     * 保存记录
     * @params {boolean} isNormal 是否是正常保存
     * @returns {void}
     */
    async handleSave(isNormal = true) {
      const records = interruptRecord.getPreRecord()
      console.log(records, 'records')
      if (!records) return
      if (isNormal) {
        Object.assign(records, this.getParams(this.$store.state.user.customerInfo, this.booksList, this.receptionStatus))
      }
      const audioPath = records.audioPath
      const recordUrlList = []
      for (let i = 0; i < audioPath.length; i++) {
        console.log(audioPath[i], 'audioPath[i]')
        const saveResult = await uni.saveFile({
          tempFilePath: audioPath[i]
        })
        const oldFilePath = saveResult[1].savedFilePath
        console.log(oldFilePath, 'oldFilePath')
        const { phone } = uni.$storage.get('userInfo')
        const newFileName = String(phone).slice(-4) + '_' + oldFilePath.replace(/.+\/(\d+\.mp3)/, '$1')
        const newFilePath = oldFilePath.replace(/(.+\/)(\d+\.mp3)/, '') + newFileName
        const path = await utils.getFileSaveFolderOnClient()
        recordUrlList.push({ status: UPLOAD_STATUS.fail, file: path + newFilePath })
        this.RenameFile(oldFilePath, newFileName)
      }
      delete records.audioPath
      let saveRecords = Object.assign(records, { recordUrlList })
      if (isNormal) {
        this.saveRecord(saveRecords)
      } else {
        interruptRecord.updatePreRecords(saveRecords, true)
      }
    },
    removeRecords() {
      const records = interruptRecord.getPreRecord()
      interruptRecord.removePreRecord(records.id)
    },
    /**保存记录*/
    async saveRecord(record) {
      const unlock = await uni.$recordManager.lock()
      console.log('record', record)
      uni.$recordManager.addRecord(record)
      interruptRecord.removePreRecord(record.id)
      unlock()
    },
    /**
     * 结束接待
     * @params {boolean} status true 不保存记录/AUDIO_STATUS.ABNORMAL 只要断开录音
     * @returns {void}
     */
    stopAudio: utils.throttle(async function (status) {
      console.log('结束')
      //   const result = await this.$permision.requestAndroidPermission(
      //     "android.permission.RECORD_AUDIO"
      //   );
      //   if (result !== 1) {
      //     uni.showToast({
      //       title: "为了记录语音通话,请打开录音权限",
      //       icon: "none",
      //     });
      //     return;
      //   }
      if (status == AUDIO_STATUS.ABNORMAL) {
        this.setAudioInfo({ audioStatus: AUDIO_STATUS.ABNORMAL })
        recorderManager.stop()
        return
      }
      if (this.audioInfo.audioStatus == AUDIO_STATUS.ABNORMAL && status != true) {
        this.setAudioInfo({ audioStatus: AUDIO_STATUS.END })
        this.handleSave()
        return
      }
      if (this.audioInfo.audioStatus != AUDIO_STATUS.START) {
        return
      }
      this.setAudioInfo({ audioStatus: AUDIO_STATUS.END })
      //直接退出
      uni.showLoading({
        mask: true
      })
      setTimeout(() => {
        uni.hideLoading()
        if (this.audioInfo.audioStatus == AUDIO_STATUS.END) {
          this.handleSave()
        }
      }, 3000)
      this.times = 0
      clearInterval(this.timer)
      this.timer = null
      if (status) {
        this.removeRecords()
      }
      recorderManager.stop()
    }, 1500),
    //监听点击事件
    initTime() {
      if (this.audioInfo.audioStatus != AUDIO_STATUS.START) return
      this.timer = setInterval(() => {
        // console.log(this.times);
        this.times++
        if (this.times >= this.timeout) {
          //关闭录音
          this.closeAudio()
          clearInterval(this.timer)
        }
      }, 1000 * 10)
    },
    handleTouchStart() {
      this.times = 0
    }
  },
  beforeCreate() {
    clearInterval(this.timer)
    this.timer = null
  }
}