recordingDetail.js 8.85 KB
// packageCrew/pages/recordingDetail/recordingDetail.js
import {getRecordDetailList, getShortUrl, findCheckResultByBatchId } from "~/api/crew/index"

import dayjs from 'dayjs'
const IMG_URL = 'https://img02.glsx.com.cn/weapp/resource/miniprogram/regional-assistant/'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    IMG_URL,
    navBarHeight: 113.5,
    typeLists: ['对话', '质检'],
    qualityAudio: '',
    activeIndex: 0,
    status: 'pause',
    currentTime: '00:00', //当前音频的播放位置
    isOperate: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
		console.log(options)
    if (Object.keys(options).length) {
      // 调用接口获取详情,默认取第一条
      let {
        receptionStartTime
      } = options
      const time = dayjs(receptionStartTime).format('YYYY-MM-DD')
      const params = {
        batchId: options.batchId,
        merchantNo: options.merchantNo,
        startDateTime: time,
        endDateTime: time
      }
      const res = await getRecordDetailList(params)
      let {
        code,
        data,
        message
      } = res
      if (code == 0) {
				console.log(data)
				const detailInfo = data.list[0] || {}
        if (Object.keys(detailInfo).length) {
          detailInfo.staticDate = new Date(detailInfo.staticDate).format('MM月dd日')
          this.setData({
            record: detailInfo,
          }, () => {
            wx.$util.getViewInfo('.reception-wrap', ({
              height
            }) => {
              this.setData({
                receptionWrapHeight: `${height * 2}rpx`
              })
            })
            this.findCheckResultByBatchId(detailInfo.batchId)
            this.setAudio()
          })
        }
      }
    }
  },
  async findCheckResultByBatchId(batchId) {
    try {
      const {
        code,
        data,
        message
      } = await findCheckResultByBatchId({
        batchId
      })
      if (code == 0) {
        data.map(item => {
          item.formatScore = `${item.score || item.score === 0 ? item.score : '-'}/${item.sumScore || item.sumScore === 0 ? item.sumScore : '-'}`
          let hitTextList = JSON.parse(item.hitText),
            matchedClass = 'no-hit',
            matchedText = '意图不匹配'
          if (hitTextList && hitTextList.length) {
            item.hitTextList = hitTextList.map(e => e.replace(/\n/g, '<br>'))
            matchedClass = 'hit'
            matchedText = '意图匹配'
          }
          item.matchedClass = matchedClass
          item.matchedText = matchedText
          let [scriptRec] = JSON.parse(item.scriptRec)
          if (scriptRec) scriptRec = scriptRec.replace(/\n/g, '<br>')
          if (item.conversationDetailDTOList && item.conversationDetailDTOList.length) {
            item.conversationDetailDTOList.map(e => {
              e.time = this.formatTime(e.mergedOffset)
              e.text_id = `text_${e.mergedOffset}`
              if (e.mergedOffset == item.offset && !item.matched) {
                e.scriptRec = scriptRec
                item.matched = true
              }
            })
            if (item.conversationDetailDTOList.findIndex(e => e.scriptRec) == -1) {
              /**时间戳都对不上时 话术推荐加到最后 */
              item.conversationDetailDTOList[item.conversationDetailDTOList.length - 1].scriptRec = scriptRec
            }
          } else item.conversationDetailDTOList = [{
            scriptRec: scriptRec || '暂无建议'
          }]
        })
        this.setData({
          qualityData: data
        })
      } else throw message
    } catch (error) {
      wx.$util.showToast(error)
    }
  },
  back() {
    if (this.qualityAudio) this.qualityAudio.pause()
    wx.navigateBack().catch(()=>{
      wx.reLaunch({
        url: '/pages/loading/loading',
      })
    })
  },
  onHandle(e) {
    let {
      isOperate
    } = this.data;
    if (isOperate) {
      this.play()
    } else {
      this.onPause()
    }
    this.setData({
      isOperate: !isOperate
    })
  },
  //音频暂停
  onPause() {
    this.dialogueRef().onPause()
    this.qualityAudio.pause()

  },
  //播放
  play() {
    if (!this.data.showPlayControl) {
      return wx.showToast({
        title: '音频暂不能播放,稍等...',
        icon: 'none'
      })
    }
    const {
      paused
    } = this.qualityAudio
    if (paused) this.qualityAudio.play()
  },
  //跳转到指定位置
  seek(time) {
    this.qualityAudio.seek(time)
  },
  setAudio() {
    this.qualityAudio = wx.createInnerAudioContext({
      useWebAudioImplement: true
    })
    this.qualityAudio.src = this.data.record.fileUrl
    this.qualityAudio.onPause(() => {
      this.setData({
        status: 'pause'
      })
      this.setKeepScreenOn()
    })
    //监听音频的播放事件
    this.qualityAudio.onPlay(() => {
      this.setData({
        status: 'start'
      })
      this.setKeepScreenOn(true)
    })
    this.qualityAudio.onCanplay(() => {
      this.setData({
        showPlayControl: true
      })
    })
    this.qualityAudio.onTimeUpdate(this.onTimeUpdate)
    this.qualityAudio.onEnded(() => {
      this.setData({
        status: 'ending',
        currentTime: this.formatTime(this.qualityAudio.duration),
        isOperate: true
      })
      this.dialogueRef().setData({
        isPlayIng: false
      })
      this.setKeepScreenOn()
    })
  },
  onTimeUpdate() {
    this.setData({
      currentTime: this.formatTime(this.qualityAudio.currentTime)
    })
    this.dialogueRef().onTimeUpdate()
    this.qualityRef().onTimeUpdate()
  },
  formatTime(seconds) {
    let minutes = Math.floor(seconds / 60);
    let remainingSeconds = Math.floor(seconds % 60); // 直接取整  

    minutes = minutes.toString().padStart(2, '0');
    remainingSeconds = remainingSeconds.toString().padStart(2, '0');

    return `${minutes}:${remainingSeconds}`;
  },
  changeType(e) {
    let {
      index
    } = e.currentTarget.dataset
    this.setData({
      activeIndex: index
    })
  },
  navbarReady(e) {
    let navBarHeight = e.detail.height;
    this.setData({
      navBarHeight,
    });
  },
  dialogueRef() {
    return this.selectComponent('#dialogue')
  },
  qualityRef() {
    return this.selectComponent('#quality')
  },
  async share(e) {
    let userInfo = wx.$util.getUserInfo() || {}
    const {
      record
    } = this.data,
      receptionStatus = {
        1: '成交',
        2: '战败',
        3: '未知'
      } [record.orderStatus], {
        endTime,
        totalDuration,
        startTime,
        merchantNo,
        batchId,
        receptionStartTimeTamp
      } = record
    console.log(record, 'record')
    // 获取短链地址
    const res = await getShortUrl({
      merchantNo,
      batchId,
      receptionStartTime: receptionStartTimeTamp
    })
    console.log(res, 'res')
    if (res.code == '0') {
      // 门店 - 接待开始时间 - 接待时长 - 员工标记的接待结果 - 接待录音mp3地址(更换成短链)
      let text = [record.merchantName, wx.$util.tsFormatTime(startTime, 'Y年M月D日 h:m:s'), wx.$util.tsFormatTime(endTime, 'Y年M月D日 h:m:s'), this.format(totalDuration), receptionStatus, res.data].join(' - ')
      wx.$util.setCopyData(text)
    } else {
      wx.$util.showToast('获取短链失败')
    }
    // wx.$util.showToast('复制成功')
	},
	// 下载录音
	async download(e) {
		let { record } = this.data
		wx.showModal({
      title: '温馨提示',
      content: '如需下载录音,请复制下载地址后到手机浏览器中打开。',
      confirmText: '复制地址',
      confirmColor: '#2C66F7',
      success(res) {
        if (res.confirm) {
          wx.setClipboardData({
            data: record.fileUrl
          })
        }
      }
    })
	},
  format(seconds) {
    seconds = Math.floor(seconds / 1000)
    let formattedTime = ''
    if (seconds < 60) return seconds + '秒'
    else {
      let hours = Math.floor(seconds / 3600),
        minutes = Math.floor((seconds % 3600) / 60),
        remainingSeconds = seconds % 60
      if (hours > 0) formattedTime += hours + '小时'
      if (minutes > 0 || hours > 0) formattedTime += minutes + '分'
      if (remainingSeconds > 0) formattedTime += remainingSeconds + '秒'
      return formattedTime
    }
  },
  //屏幕是否常亮
  setKeepScreenOn(keepScreenOn = false) {
    wx.setKeepScreenOn({
      keepScreenOn
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.qualityAudio.stop()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.qualityAudio.stop()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})