dialogue.js 15.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
// packageEquity/pages/receptionDetail/components/dialogue/dialogue.js
import api from "~/utils/request/request.js";
let thisPage = null
import watchScrollMixin from '../watchScrollMixin'
Component({
  behaviors: [watchScrollMixin],
  /**
   * 组件的属性列表
   */
  properties: {
    recordData: Object,
    batchId: Number
  },
  lifetimes: {
    ready() {
      thisPage = wx.$router.getPageInstance()
      this.innerAudioContext = thisPage.qualityAudio
      const {
        batchId
      } = this.data
      const data = {
        batchId,
        currentPage: 1,
        pageSize: 999999,
      };
      // this.innerAudioContext.onCanplay(() => {
      this.findConversationDetailByBatchId(data)
      this.findCbByBatchId(data)
    },
    detached() {
      this.IntersectionObserver?.disconnect()
    }

  },
  /**
   * 组件的初始数据
   */
  data: {
    progress: 0,
    dialogueList: []
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onTimeUpdate() {
      const {
        dialogueList
      } = this.data, {
          paused
        } = this.innerAudioContext, {
          mergedOffset
        } = this.setProgress(),
        item = dialogueList.find(e => e.mergedOffset == mergedOffset)
      if (!paused) this.setData({
        isPlayIng: true
      })
      if (this.data.isScrollling) return
      if (item && item.id) this.setTopId(item, true)
    },

    setTopId(item, scroll = false) {
      const {
        dialogueList
      } = this.data
      let centerIndex = dialogueList.findIndex(e => e.text_id == item.text_id)
      centerIndex -= 2
      if (centerIndex < 0) centerIndex = 0
      wx.nextTick(() => {
        this.setData({
          activeId: item.text_id,
        })
      })
      if (scroll) this.setData({
        toId: dialogueList[centerIndex].text_id
      })
    },
    setProgress() {
      const {
        duration,
        currentTime
      } = this.innerAudioContext,
        mergedOffset = Math.ceil(currentTime)
      this.setData({
        progress: mergedOffset / duration * 100
      })
      return {
        currentTime,
        mergedOffset
      }
    },
    toDefenceDetail(e) {
      let {
        item,
      } = e.currentTarget.dataset
      this.setData({
        toId: item.text_id
      })
      this.setData({
        isScrollling: true
      })
      this.touchend()
    },
    seekPlay(e, report = true) {
      let {
        item,
        click,
        scroll
      } = e.currentTarget.dataset, {
        activeId
      } = this.data
      if(!item) return
      thisPage.seek(item.mergedOffset)
      this.setTopId(item, scroll)
      if (report) this.setTrackData('dialogue_time_point')
      if (click && item.text_id == activeId) {
        const {
          paused
        } = this.innerAudioContext
        if (paused) this.triggerEvent('play')
        else thisPage.onPause()
        thisPage.setData({
          isOperate: !paused
        })
      } else {
        this.triggerEvent('play')
        thisPage.setData({
          isOperate: false
        })
      }
    },
    formatTime(num) {
      let minutes = Math.floor(num / 60) || '0',
        seconds = num % 60 || '0'
      seconds = seconds < 10 ? `0${seconds}` : seconds
      return `${minutes}:${seconds}`
    },
    relativeToViewport() {
      if (this.IntersectionObserver) return
      this.IntersectionObserver = this.createIntersectionObserver({
        observeAll: true
      })
      this.IntersectionObserver.relativeToViewport({
        bottom: 1000,
        top: 0,
      }).observe('.item', res => {
        const {
          index
        } = res.dataset, {
            dialogueList
          } = this.data, {
            originalList
          } = this,
          item = dialogueList[index]
        if (!item?.visible && res.intersectionRatio > 0) {
          this.setData({
            [`dialogueList[${index}]`]: originalList[index]
          })
        }
      })
    },
    /**对话列表 */
    async findConversationDetailByBatchId(params) {
      function numberToChinese(num) {
        const chineseNums = '一二三四五六七八九十'.split('')
        if (num >= 1 && num <= 10) {
          return chineseNums[num - 1];
        } else {
          throw new Error('Number must be between 1 and 10');
        }
      }
      const {
        data: dialogueList
      } = await api.post("dj.api.smartcarlife.recepiton.findConversationDetailByBatchId", params), {
          totalDuration
        } = this.data.recordData,
        userInfo = wx.$util.getUserInfo() || {}
      let defenceNum = 1,
        defenceDetailList = []
      dialogueList?.map(e => {
        e.visible = true
        e.time = this.formatTime(e.mergedOffset)
        e.text_id = `text_${e.id}`
        e.showCheckDetail = false

        if (e.defenceDetail) {
          e.defenceTitle = `第${numberToChinese(defenceNum)}次攻防`
          defenceNum++
          let {
            suggestionsForImprovement,
            refineTheExpression,
            highlight
          } = e.defenceDetail,
            highlightList = highlight ? JSON.parse(highlight) : []
          if (highlightList.length) {
            e.suggestionsText = this.highlightKeyword(suggestionsForImprovement, highlightList)
            e.refineTheExpressionText = this.highlightKeyword(refineTheExpression, highlightList)
          }
          defenceDetailList.push({
            mergedOffset: e.mergedOffset,
            text_id: e.text_id,
            top: e.mergedOffset / (totalDuration / 1000) * 100
          })

        }
        if (e?.conversationCheckDetailDTO) {
          e.conversationCheckDetailDTO = Array.isArray(e.conversationCheckDetailDTO) ? e.conversationCheckDetailDTO : [e.conversationCheckDetailDTO]
          e.conversationCheckDetailDTO.map(i => {
            let {
              suggestions,
              firstClassify
            } = i
            if (suggestions) i.suggestions = this.transitionBr(suggestions)
            if (suggestions == '-') i.suggestions = ''
            let regex = new RegExp('环节', 'g')
            i.firstClassify = firstClassify.replace(regex, '')
            if (i.firstClassify == '结束') i.firstClassify = '促成交'
          })
        } else {
          if (!userInfo.isSuper && userInfo.loginRole != 3) {
            e.appealText = e.conversationDetailAppealId ? '已申诉' : '申诉'
            e.appealClass = e.conversationDetailAppealId ? 'appeal-disabled' : ''
          }
        }
      })
      this.setData({
        flag: true,
        defenceDetailList,
      })
      this.originalList = dialogueList
      this.setDialogueData(dialogueList)
    },
    setDialogueData(dialogueList) {
      wx.$util.showLoading('加载中...')
      const batchSize = 100
      let batch = []
      // 遍历对话列表,累积数据
      for (let i = 0; i < dialogueList.length; i++) {
        batch.push({
          visible: false,
          text_id: dialogueList[i].text_id,
          id: dialogueList[i].id,
          mergedOffset: dialogueList[i].mergedOffset
        });
        // 当累积的数据达到批量大小时,执行 setData 更新
        if ((i + 1) % batchSize === 0 || i === dialogueList.length - 1) {
          this.setData({
            dialogueList: [...this.data.dialogueList, ...batch]
          });
          batch = []; // 清空累积的数据,准备下一批
        }
      }

      // // 确保最后不足100条的数据也被更新
      if (batch.length > 0) {
        this.setData({
          dialogueList: [...this.data.dialogueList, ...batch]
        })
      }
      // // 更新完成后清除加载提示
      wx.$util.hideLoading();
      this.relativeToViewport();
    },
    highlightKeyword(highlightedText, keywords) {
      keywords.forEach(keyword => {
        let regex = new RegExp(keyword, 'g')
        highlightedText = highlightedText.replace(regex, `<span style="color:#347BFF;font-weight: 500;">${keyword}</span>`)
      })
      return this.transitionBr(highlightedText)
    },
    transitionBr(text) {
      let regex = new RegExp('</br>', 'g')
      text = text.replace(regex, '<div></div>')
      return text
    },
    /** 查询质检侧边栏 (质检使用id匹配,攻防用偏移量匹配) */
    async findCbByBatchId(params) {
      const {
        data
      } = await api.post("dj.api.smartcarlife.recepiton.findCbByBatchId", params)
      let {
        totalDuration,
        receptionStaticInfoDetailDTOList
      } = this.data.recordData,
        regex = new RegExp('注意事项', 'g')
      totalDuration = totalDuration / 1000
      wx.$util.getViewInfo('.axis-bar', ({
        height: containerHeight,
        top: barTop
      }) => {
        this.barTop = barTop
        this.containerHeight = containerHeight
        let colorList = [],
          // processedTops = [],
          margin = 20,
          maxTop = containerHeight
        receptionStaticInfoDetailDTOList?.length && receptionStaticInfoDetailDTOList.map(e => {
          let keyName = e.stage,
            colorName = ''
          if (e.totalScore == 4) { // 接待环节
            colorName = e.totalGetScore <= 1 ? 'red-tag' : e.totalGetScore > 1 && e.totalGetScore < 3 ? 'yellow-tag' : 'green-tag'
          } else if (e.totalScore == 50) { // 车辆交付环节
            colorName = e.totalGetScore < 15 ? 'red-tag' : e.totalGetScore >= 15 && e.totalGetScore <= 40 ? 'yellow-tag' : 'green-tag'
          } else if (e.totalScore == 40) { // 需求挖掘环节
            colorName = e.totalGetScore <= 10 ? 'red-tag' : e.totalGetScore >= 20 && e.totalGetScore <= 30 ? 'yellow-tag' : 'green-tag'
          } else { // 结束环节
            colorName = e.totalGetScore < 6 ? 'red-tag' : 'green-tag'
          }
          colorList.push({
            keyName,
            colorName
          })
        })
        data?.sort((a, b) => a.mergedOffset - b.mergedOffset).forEach((e, index) => {
          let {
            colorName
          } = colorList.find(i => i.keyName == e.firstClassify)
          e.colorName = colorName
          if (e.conversationDetail) {
            const {
              duration: itemDuration,
              mergedOffset,
              id
            } = e.conversationDetail
            e.height = itemDuration / 1000 / totalDuration * containerHeight
            e.top = mergedOffset / totalDuration * containerHeight
            e.docTop = mergedOffset / totalDuration * containerHeight
            e.text_id = `text_${id}`
            e.mergedOffset = mergedOffset
            e.secondClassify = e.secondClassify.replace(regex, '')

            // // 检查当前元素与所有已处理元素的 top 值
            // let adjusted = false
            // for (let pt of processedTops) {
            //   if (Math.abs(e.top - pt) < margin) {
            //     e.top += margin;
            //     adjusted = true;
            //     break;
            //   }
            // }
            // // 检查是否超出最大 top 值
            // if (e.top + margin > maxTop) {
            //   e.top -= margin;
            //   if (e.top < 0) {
            //     e.top = 0;
            //   }
            // }
            // if (adjusted) {
            //   for (let pt of processedTops) {
            //     if (Math.abs(e.top - pt) < margin) {
            //       e.top += margin;
            //       if (e.top > maxTop) {
            //         e.top -= margin;
            //         if (e.top < 0) {
            //           e.top = 0;
            //         }
            //       }
            //     }
            //   }
            // }
            // // 添加当前元素的 top 值到已处理列表
            // processedTops.push(e.top);
          }
        })
        data?.map((e, index) => {
          if (e.conversationDetail) {
            // 检查并调整 top 值,避免重叠
            for (let i = 0; i < index; i++) {
              if (e.top < data[i].top + margin &&
                e.top + margin > data[i].top) {
                // 如果重叠,将当前元素的 top 设置为前一个元素的底部加上 margin
                e.top = data[i].top + margin;
              }
            }
            // if (e.top < 0) e.top = 0
            // 确保不超过最大 top 值
            // if (e.top + margin > maxTop) e.top = maxTop - margin
          }
        })
        this.setData({
          axisList: data
        })
      }, this)
    },
    switchDetail(e) {
      const {
        index,
        value,
        ind,
        key
      } = e.currentTarget.dataset
      let target = `dialogueList[${index}]`
      if (ind > -1) target = `dialogueList[${index}].conversationCheckDetailDTO[${ind}]`
      this.setTrackData(key == 'showDefenceDetail' ? 'offense_and_defense_bout' : 'dialogue_intention_matching')
      this.setData({
        [`${target}.${key}`]: !value
      })
    },
    touchstart() {
      this.setData({
        isScrollling: true
      })
      this.clearTimer()
    },
    touchend() {
      this.touchTimer = setTimeout(() => {
        this.setData({
          isScrollling: false
        })
        this.clearTimer()
      }, 3e3)
    },
    clearTimer() {
      if (this.touchTimer) {
        clearTimeout(this.touchTimer)
        this.touchTimer = null
      }
    },
    handleAppeal(e) {
      const {
        item,
        index
      } = e.currentTarget.dataset
      if (item.conversationDetailAppealId) return
      this.triggerEvent('pause')
      this.setTrackData('appeal')
      this.setData({
        chooseItem: {
          ...item,
          index
        },
        showAppeal: true
      })
    },
    confirm(e) {
      const {
        index
      } = e.detail
      wx.$util.showToast('已提交申诉')
      this.setData({
        [`dialogueList[${index}].conversationDetailAppealId`]: Date.now(),
        [`dialogueList[${index}].appealText`]: '已申诉',
        [`dialogueList[${index}].appealClass`]: 'appeal-disabled'
      })
    },
    onPause() {
      this.setData({
        isPlayIng: false
      })
    },
    practiceHandle(e) {
      const {
        stage
      } = e.currentTarget.dataset
      let thisPage = wx.$router.getPageInstance()
      thisPage.practiceHandle(stage)
    },
    toDefenceItem(mergedOffset) {
      const {
        dialogueList
      } = this.data,
        item = dialogueList.find(e => e.mergedOffset == mergedOffset)
      if (item && item.id) wx.nextTick(() => this.setData({
        toId: item.text_id,
        activeId: item.text_id
      }))
    },
    barSeek(e) {
      function findNearest(arr, target) {
        let closest = arr[0];
        let minDiff = Math.abs(target - arr[0]);

        for (let i = 1; i < arr.length; i++) {
          const diff = Math.abs(target - arr[i]);
          if (diff < minDiff) {
            minDiff = diff;
            closest = arr[i];
          }
        }

        return closest;
      }
      let [touches] = e.touches, {
        barTop,
        containerHeight
      } = this, {
        duration
      } = this.innerAudioContext, {
        dialogueList
      } = this.data
      if (touches) {
        let {
          clientY
        } = touches,
        progress = (clientY - barTop) / containerHeight * 100,
          offsetList = dialogueList.map(i => i.mergedOffset),
          mergedOffset = findNearest(offsetList, duration * progress / 100),
          item = dialogueList.find(i => i.mergedOffset == mergedOffset)
        this.setTrackData('audio_progress_bar', {
          mergedOffset
        })
        this.seekPlay({
          currentTarget: {
            dataset: {
              item,
              scroll: true
            }
          }
        }, false)
      }
    },
    /**设置埋点数据 */
    setTrackData(code, params = {}) {
      let {
        batchId
      } = this.data
      wx.$track.setTrackData(0, code, {
        ...params,
        batchId
      })
    }
  }
})