click.js 8.58 KB
/*
 * @Author: 前端 qianduan01@didihu.com.cn
 * @Date: 2024-04-08 11:28:48
 * @LastEditors: 前端 qianduan01@didihu.com.cn
 * @LastEditTime: 2024-08-30 17:49:04
 * @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')
const UPLOAD_STATUS = {
  // 上传状态
  success: 1,
  fail: 2
}
import { mapMutations, mapState } from 'vuex'
import utils from '@/utils/utils.js'
export default {
  data() {
    return {
      voicePath: '',
      timer: null,
      times: 0,
      timeout: 240,
      reaction: 1
    }
  },
  mounted() {
    // 获取当前页面栈数组
    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()
  },
  computed: {
    ...mapState('audio', ['receptionStatus', 'booksList', 'audioInfo']),
    ...mapState(['user.customerInfo'])
  },
  created() {
    console.log('created')
  },
  onHide() {
    console.log('隐藏')
    // recorderManager.stop();
    // recorderManager.start({
    //   duration: 10000,
    // });
  },
  onShow() {
    // console.log(utils.requestAndroidPermission());
  },
  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('abnormal')
      this.setReceptionStatus(0)
      this.setAudioInfo({ endReasonType: 1 })
    },
    getParams() {
      const { shopMerchantId, phone, sceneType, uuid, name, merchantId, channelType, merchantName } = uni.$storage.get('userInfo'),
        { customerName, phoneNumber, salesUuid, carModel, staffName } = this.$store.state.user.customerInfo,
        receptionCustomerPaySourceList = this.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,
        params = {
          staffUuid: uuid,
          staffName: name,
          serviceMerchantId: merchantId,
          carModel,
          endReasonType, //原因 1.异常 0.正常
          customerName,
          phoneNumber,
          appCode,
          loginPhone: phone,
          salesName: staffName,
          salesUuid,
          receptionStatus: this.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 其他
        }
        console.log(receptionTrack)
      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 == 'start') return
      this.setAudioInfo({ audioList: [], audioStatus: 'start' })
      this.setBooks([])
      this.$store.dispatch('clearCustomerInfo')
      this.setReceptionStatus(1)
      this.initTime()
      recorderManager.start({
        duration: 600000,
        sampleRate: 16000,
        numberOfChannels: 1
      })
      recorderManager.onStop(async res => {
        console.log('结束录音')
        if (this.audioInfo.audioStatus == 'start') {
          uni.getRecorderManager().start({
            duration: 600000,
            sampleRate: 16000,
            numberOfChannels: 1
          })
        }
        if (this.audioInfo.audioStatus == 'no') {
          uni.removeSavedFile({
            filePath: res.tempFilePath,
            complete: function (res) {
              console.log(res)
            }
          })
          return
        }
        const saveResult = await uni.saveFile({
          tempFilePath: res.tempFilePath
        }) // 保存文件到本地
        //删除默认文件
        uni.removeSavedFile({
          filePath: res.tempFilePath,
          complete: function (res) {
            console.log(res)
          }
        })
        const oldFilePath = saveResult[1].savedFilePath
        const { phone } = uni.$storage.get('userInfo')
        const newFileName = String(phone).slice(-4) + '_' + oldFilePath.replace(/.+\/(\d+\.mp3)/, '$1')
        const newFilePath = oldFilePath.replace(/(.+\/)(\d+\.mp3)/, '') + newFileName
        this.RenameFile(oldFilePath, newFileName)
        this.handleSave(newFilePath)
      })
    }, 300),
    handleSave(file) {
      const audioList = [...this.audioInfo.audioList, file]
      if (file) {
        this.setAudioInfo({ audioList })
      }
      if (this.audioInfo.audioStatus != 'end' && this.audioInfo.audioStatus != 'finish') {
        return
      }
      this.saveRecord()
      this.setAudioInfo({ endReasonType: 0, audioStatus: 'finish' })
    },
    /**保存记录*/
    async saveRecord() {
      const params = this.getParams()
      const unlock = await uni.$recordManager.lock()
      const path = await utils.getFileSaveFolderOnClient()
      const recordUrlList = this.audioInfo.audioList.map(i => {
        return {
          status: UPLOAD_STATUS.fail,
          file: path + i.split('/').pop()
        }
      })
      if (recordUrlList.length) {
        this.$store.dispatch('clearCustomerInfo')
      }
      uni.$recordManager.addRecord({
        ...params,
        id: utils.uuid(),
        recordUrlList
      })
      unlock()
    },
    //结束接待
    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 == 'abnormal') {
        this.setAudioInfo({ audioStatus: 'abnormal' })
        recorderManager.stop()
        return
      }
      if (this.audioInfo.audioStatus == 'abnormal' && status != true) {
        this.setAudioInfo({ audioStatus: 'end' })
        this.handleSave()
        return
      }
      if (this.audioInfo.audioStatus != 'start') {
        return
      }
      this.setAudioInfo({ audioStatus: 'end' })
      //直接退出
      uni.showLoading({
        mask: true
      })
      setTimeout(() => {
        uni.hideLoading()
        if (this.audioInfo.audioStatus == 'end') {
          this.handleSave()
        }
      }, 3000)
      this.times = 0
      clearInterval(this.timer)
      this.timer = null
      if (status) {
        this.setAudioInfo({ audioStatus: 'no' })
      }
      recorderManager.stop()
    }, 1500),
    //监听点击事件
    initTime() {
      if (this.audioInfo.audioStatus != '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
  }
}