chat.js 26.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 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
// packageEquity/pages/aiCheck/chat/chat.js
import carLifeApi from "../../../carEquityApi";
import api from '~/api/api.js'
const VOICE = {
  1: "zhifeng_emo",
  2: "stanley",
  3: "rosa",
  4: "aishuo",
  5: "aiqi",
  9: "zhiyan_emo",
};
let timer = null;
let duration = 0;
import aiApi from "../../../aiApi";
const linkChainList = [{
    id: 1,
    name: "接待",
    iconUrl: "icon-reception",
    type: "reception",
    desc: "此环节模拟交付专员把客户介绍给驻店专员,建议使用敬语,尊称客户,恭喜客户提车,主动向客户介绍工作环节并进行自我介绍!",
  },
  {
    id: 2,
    name: "车辆交付",
    iconUrl: "icon-car",
    type: "delivery",
    desc: "此环节模拟驻店专员已完成对于客户的接待,即将向客户介绍新车使用注意事项、保养要求和基础质保政策,建议在介绍过程中主动了解客户的用车周期,用车环境,给介绍延保产品时进行铺垫!",
  },
  {
    id: 3,
    name: "需求挖掘",
    iconUrl: "icon-demand",
    type: "demand",
    desc: "此环节模拟驻店专员已完成了新车使用、保养要求和基础质保政策的介绍,即将向客户介绍延保产品,此环节容易触发攻防,建议多以延保相对基础质保的优势,当天购买价格有优惠,大部分客户均选择购买等为主进行推荐!",
  },
  {
    id: 4,
    name: "促成交",
    iconUrl: "icon-dear",
    type: "referral",
    desc: " 此环节模拟驻店专员已完成了延保产品的介绍,即将根据客户是否展示购买意愿进行话术演练,建议对明显展示不想购买意愿的客户使用逼单话术进行进一步沟通!",
  },
];

import {
  speechEmoji,
  soundEmoji,
  definitionEmoji,
  toneWords,
  SpeechRateValue,
  calculateStars,
  calculateEmotion,
  speechSpeed_MIN,
  speechSpeed_MAX,
  Emotion_MIN,
  Emotion_MAX,
  calculateIntonation,
} from "../contant";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isSend: true,
    productInfo: {},
    scrollTop: 0,
    defense_step: 0, //攻防步骤的编号,表示当前攻防的阶段。
    round: 0, //对练的轮次,用于记录当前对话是第几轮对练。
    step: "reception", // reception delivery  defense referral  四个环节的字典值
    navStyle: "background-color: transparent",
    showChat: false, // false 展示介绍页,true展示聊天页
    showScenePopup: false, // 场弹窗
    showSpeechPopup: false, // 语音弹窗
    popType: "", // script 话术攻防,inspiration 对话灵感,scene 场景
    controlBoxStyle: "", // 控制控制台的层级
    chatList: [],
    scriptList: [],
    inspirationContent: "",
    // 分界线
    ttsStart: false,
    saveFile: "11",
  },
  getHistoryAll() {
    const audioBox = this.selectComponent("#audioBox");
    return audioBox.getList("");
  },
  // 结束,查看报告
  toResult() {
    const audioBox = this.selectComponent("#audioBox");
    const list = audioBox.data.list;
    if (list.length == 0) {
      return this.back();
    }
    let isJump = true,
      Sentences = [];
    list.forEach((i) => {
      if (i.role == 2) {
        isJump = false;
        Sentences = [...Sentences, ...(i.Sentences ? i.Sentences : [])];
      }
    });
    if (isJump) {
      return this.back();
    }
    if (!list[list.length - 1].content) {
      wx.$util.showToast("AI还未回复");
      return;
    }
    if (Sentences.length == 0) {
      wx.$util.showToast("对话内容太短");
      return;
    }
    this.setData({
      isVisible: true,
    });
  },
  handleCancel() {
    this.setData({
      isVisible: false,
    });
  },
  handleSure: wx.$util.throttle(async function (e) {
    this.handleCancel()
    wx.$util.showLoading()
    const history_message = this.getHistoryAll();
    const sensitiveRes = await aiApi.getSensitive({
      history_message,
    });
    const {is_sensitive,sensitive_words} = sensitiveRes||{};
    const audioBox = this.selectComponent("#audioBox");
    const chatList = audioBox.data.list;
    this.handleSave(chatList, duration, is_sensitive,sensitive_words);
  }, 1000),
  convertSecondsToMinutesAndSeconds(seconds, isSymbol) {
    var minutes = Math.floor(seconds / 60); // 计算分钟数
    var remainingSeconds = seconds % 60; // 计算剩余的秒数
    // 如果剩余的秒数小于10,则前面添加0以保持格式一致
    if (remainingSeconds < 10) {
      remainingSeconds = "0" + remainingSeconds;
    }
    let res = minutes + "分" + remainingSeconds + "秒";
    if (isSymbol) {
      res = minutes + ":" + remainingSeconds;
    }
    return res;
  },
  getSentencesDetail(Sentences, totalTime, redundantWord) {
    let totalSpeed = 0;
    let totalEmotionValue = 0;
    let axisX = [];
    let axisY_SpeechRate = [];
    let axisY_EmotionValue = [];
    if (Sentences.length == 0) {
      return;
    }
    if (Sentences.length > 2) {
      Sentences.forEach((i, k) => {
        totalSpeed += i.SpeechRate;
        totalEmotionValue += i.EmotionValue;
        if (k == 0) {
          axisX.push("0:00");
        } else if (k == Sentences.length - 1) {
          axisX.push(this.convertSecondsToMinutesAndSeconds(totalTime, true));
        } else {
          axisX.push(k);
        }
        axisY_SpeechRate.push(i.SpeechRate);
        axisY_EmotionValue.push(i.EmotionValue);
      });
      if (Sentences.length == 2) {
        axisX.push(this.convertSecondsToMinutesAndSeconds(totalTime, true));
        axisY_SpeechRate.push(Sentences[1].SpeechRate);
        axisY_EmotionValue.push(Sentences[1].EmotionValue);
      }
    } else {
      axisX = [
        "0:00",
        1,
        this.convertSecondsToMinutesAndSeconds(totalTime, true),
      ];
      axisY_SpeechRate = [
        Sentences[0].SpeechRate,
        Sentences[0].SpeechRate,
        Sentences[0].SpeechRate,
      ];
      axisY_EmotionValue = [
        Sentences[0].EmotionValue,
        Sentences[0].EmotionValue,
        Sentences[0].EmotionValue,
      ];
      totalSpeed = Sentences[0].SpeechRate;
      totalEmotionValue = Sentences[0].EmotionValue;
    }
    const averageSpeed = totalSpeed / Sentences.length;
    const averageEmotionValue = totalEmotionValue / Sentences.length;
    const speechSpeed = {
      star: calculateStars(averageSpeed),
      x: axisX,
      y: axisY_SpeechRate,
      min: speechSpeed_MIN,
      max: speechSpeed_MAX,
    };
    const definition = {
      x: axisX,
      y: axisY_EmotionValue,
      star: calculateEmotion(averageEmotionValue, true),
      min: Emotion_MIN,
      max: Emotion_MAX,
    };
    const axisY_Intonation = axisY_EmotionValue.map((currentValue, index) => {
      if (index < axisY_EmotionValue.length - 1) {
        const mul = Math.ceil(axisY_EmotionValue[index + 1] - currentValue) + 1;
        return mul > 0 ? mul : 0;
      } else {
        return 1;
      }
    });
    const intonation_star = calculateIntonation(axisY_EmotionValue, true);
    let intonation_min, intonation_max;
    if (intonation_star == 1) {
      intonation_min = axisY_Intonation[0] + 3;
      intonation_max = axisY_Intonation[0] + 5;
    } else {
      intonation_min = Math.min(...axisY_Intonation);
      intonation_max = Math.max(...axisY_Intonation) + 1;
    }
    const intonation = {
      x: axisX,
      y: axisY_Intonation,
      star: intonation_star,
      min: intonation_min,
      max: intonation_max,
    };
    const redundantWords = this.getWord(redundantWord);
    return {
      speechSpeed,
      redundantWords,
      definition,
      intonation,
    };
  },
  getWord(chats) {
    let wordNum = 0;
    let content = [];
    for (let i = 0; i < chats.length; i++) {
      let chat = chats[i];
      toneWords.forEach((toneWord) => {
        let firstFound = false;
        chat = chat.replace(new RegExp(toneWord, "g"), (match) => {
          if (!firstFound) {
            firstFound = true; // 标记第一次出现
            return ""; // 不保留第一次出现
          }
          wordNum++; // 统计后续出现的次数
          return match; // 保留后续出现的
        });
      });

      let sentences = chat.split(/[,,。!?!?]/);
      for (let sentence of sentences) {
        for (let word of toneWords) {
          if (sentence.includes(word)) {
            content.push(sentence);
            break;
          }
        }
      }
    }
    let star = 5 - Math.ceil(wordNum / 2);
    if (star < 1) {
      star = 1;
    }
    return {
      star,
      content:content.join(','),
    };
  },
  getOpenId() {
    return new Promise((resolve)=>{
      wx.login({
        success({
          code
        }) {
          if (code) {
            api
              .ssoLogin({
                code,
                appId: wx.getAccountInfoSync().miniProgram.appId
              }).then(res => {
                resolve(res.data.openId)
              })
          }
        },
      })
    })

  },
  async handleSave(list, sparringDuration, triggerSensitive,sensitive_words) {
    let totalTime = 0;
    let Sentences = [];
    let content = [];
    list.forEach((i) => {
      if (i.role == 2) {
        totalTime += i.times;
        content.push(i.content);
        Sentences = [...Sentences, ...i.Sentences];
      }
    });
    const {
      speechSpeed,
      redundantWords,
      definition,
      intonation
    } =
    this.getSentencesDetail(Sentences, totalTime, content) || {};
    const {
      sparringTaskId,
      roleType,
      step:sparringLink,
      entry,
      batch_id,
      recordName,
      objection_id:objectionId
    } = this.data;
    const {
      merchantId,
      uuid
    } = wx.$util.getUserInfo();
    const fluency = {
      speechSpeed: JSON.stringify(speechSpeed),
      redundantWords: JSON.stringify(redundantWords),
    };
    const deliver = {
      definition: JSON.stringify(definition),
      intonation: JSON.stringify(intonation),
    };
    const details = list.map((i) => {
      const {
        role,
        content,
        suggestions_for_improvement: improve,
        refine_the_expression: polish,
        voiceUrl,
        times: voiceDuration,
        spkTime,
        speed,
        intonation,
        definition,
        redundant,
      } = i;
      return {
        sparringLink,
        voiceDuration,
        role,
        voiceUrl,
        content,
        improve,
        polish,
        spkTime,
        speed,
        intonation,
        definition,
        redundant,
      };
    });
    let openId = wx.$util.getOpenId();
    if(!openId) {
      openId  = await this.getOpenId()
    }
    carLifeApi
      .sparringCommit({
        openId,
        objectionId,
        sparringType:objectionId?2:1,
        staffUuid: uuid,
        recordName: recordName?recordName:'话术演练 · 驻店延保',
        sparringTaskId: sparringTaskId || -1,
        roleType,
        batchId:batch_id,
        sparringDuration: sparringDuration * 1000,
        yqMerchantId: merchantId,
        fluency,
        deliver,
        triggerSensitive,
        sensitiveList:sensitive_words,
        details: JSON.stringify(details),
      })
      .then((res) => {
        const id = res.data.sparringRecordId
        wx.$util.hideLoading()
        this.behaviorSave(1)
        wx.requestSubscribeMessage({
          tmplIds: ["WH1kEKtvU_RbHFu6_DRm3G9sqUhky_hZHjevxrz8GK8"],
          success(res) {
            wx.showToast({
              title: "订阅成功",
              icon: "none",
            });
            wx.redirectTo({
              url: `/packageEquity/pages/aiCheck/result/result?roleType=${roleType}&id=${id}&entry=${entry}`,
            });
          },
          fail(res) {
            wx.redirectTo({
              url: `/packageEquity/pages/aiCheck/result/result?roleType=${roleType}&id=${id}&entry=${entry}`,
            });
          }
        });
      });
  },
  toBottom() {
    setTimeout(() => {
      this.setData({
        scrollTop: 99999,
      });
    }, 10);
  },
  // 头部返回上一级
  back() {
    wx.$router.back();
  },
  // 打开场景设置
  selectScene() {
    this.setData({
      showScenePopup: true,
      controlBoxStyle: "z-index: 0;",
    });
  },
  //选择攻防话术
  async handleScript(message) {
    const {
      attackScript,
      scriptList,
      objection_id
    } = this.data;
    const audioBox = this.selectComponent("#audioBox");
    const list = audioBox.data.list;
    let isCan = true;
    list.forEach((i) => {
      if (!i.filePath) {
        isCan = false;
      }
    });
    if (!isCan) {
      wx.$util.showToast("语音还未识别");
      return;
    }
    this.data.isSend = false;
    const addVal = {
      role: 1,
      content: "",
      openAudio: false,
    };
    audioBox.addList(addVal, 1);
    const index = Math.floor(Math.random() * scriptList.length);
    if(!message || message.type) {
      message = scriptList[index].content;
    }else {
     const objectionPage = await carLifeApi.objectionPage({id:objection_id})
     message = objectionPage.data.list[0].commonQuestion
    }
    const Phrases = await aiApi.getPhrases({
      message,
    });
    const content = Phrases.similar_words;
    this.data.isSend = true;
    audioBox.setList({
        content,
        times: Math.ceil(content.length / 4),
        spkTime: new Date().format("yyyy-MM-dd hh:mm:ss"),
      },
      0
    );

    const chatList = audioBox.data.list;
    const point = attackScript[index].main_point;
    let main_point = "";
    point.forEach((i, k) => {
      main_point = main_point + (k + 1) + "." + i + "\r\n";
    });
    const Inspiration = attackScript[index].sale_message
    .replace(/,/g, ",")
    .replace(/。/g, "。")
    this.setData({
      reject_reason: content,
      defense_step: -1,
      defenseIndex: chatList.length - 1,
      step: "defense",
      showScenePopup: false,
      main_point,
      roleInspiration: objection_id ? '' :Inspiration,
      inspirationContent: objection_id ? '' :Inspiration,
      popType: "",
    });
  },
  // 保存场景回调
  handleScene(e) {
    this.setData({
      showScenePopup: false,
    });
  },
  // 对话灵感和话术攻防
  openPopup: wx.$util.throttle(function (e) {
    const type = e.currentTarget.dataset.type;
    if (this.data.popType == type) {
      this.setData({
        showScenePopup: false,
        popType: "",
      });
    } else {
      if (type == "inspiration" && !this.data.isSend) {
        wx.$util.showToast("AI还未回复");
        return;
      }
      let controlBoxStyle = "z-index: 0;";
      if (type != "scene") {
        controlBoxStyle = "z-index: 1000;";
      }
      this.setData({
        showScenePopup: true,
        popType: type,
        controlBoxStyle,
      });
      if (type == "inspiration") {
        this.getInspiration();
      }
    }
  }, 1000),
  // 弹窗取消
  cancel() {
    this.setData({
      popType: "",
    });
  },
  // 点击蒙层
  handleMask() {
    console.log(this.data.popType, "popType");
    if (this.data.popType == "inspiration") {
      this.setData({
        showScenePopup: false,
        popType: "",
      });
    }
  },
  send(e) {
    const {
      result: content,
      filePath,
      times
    } = e.detail;
    console.log(filePath);
    const addVal = {
      role: 2,
      content: content.replace(/\s/g, ""),
      openAudio: false,
      filePath,
      times,
      spkTime: new Date().format("yyyy-MM-dd hh:mm:ss"),
      loading: true,
      show: false,
    };
    const audioBox = this.selectComponent("#audioBox");
    const idx = audioBox.data.list.length;
    audioBox.addList(addVal);
    this.setData({
        inspirationContent: "",
        showSpeechPopup: false,
      },
      () => {
        this.getSparring(content);
        this.getEnhancement(content, idx);
      }
    );
  },
  closeSpeechPopup() {
    this.setData({
      showSpeechPopup: false,
    });
    // this.send({
    //   detail: {
    //     result: '你好欢迎光临'
    //   }
    // })
  },
  //获取改进建议和润色表达
  getEnhancement(last_message, idx, retryCount = 0) {
    const {
      batch_id,
      objection_id
    } = this.data;
    const {
      uuid,
      name
    } = wx.$util.getUserInfo();
    let api_params = 'enhancement'
    let history_message = ''
    if(objection_id) {
      api_params = 'objectionEnhancement'
      history_message = this.getHistoryAll()
    }
    aiApi[api_params]({
        last_message,
        user_id: uuid,
        history_message,
        batch_id,
        objection_id
      })
      .then((res) => {
        let {
          refine_the_expression,
          suggestions_for_improvement,
          highlight = [],
        } = res;
        // 构建正则表达式
        const pattern = new RegExp("(" + highlight.join("|") + ")", "g");
        // 使用正则表达式替换文本
        refine_the_expression = refine_the_expression.replace(
          pattern,
          function (match) {
            return '<span style="color:#3989FE;">' + match + "</span>";
          }
        );
        const audioBox = this.selectComponent("#audioBox");
        audioBox.setSuggest({
            loading: false,
            refine_the_expression,
            suggestions_for_improvement,
          },
          idx
        );
      })
      .catch((e) => {
        if (retryCount < 1) {
          // 如果重试次数小于1,则重试一次
          this.getEnhancement(last_message, idx, retryCount + 1);
        }
        wx.$sendSentry(name + "获取改进建议和润色表达" + JSON.stringify(e));
      });
  },
  getHistory() {
    let {
      step,
      defenseIndex
    } = this.data;
    const audioBox = this.selectComponent("#audioBox");
    return audioBox.getList(step, defenseIndex);
  },
  /**
   * 获取灵感建议
   * 如果进入攻防状态(defense),直接拿对应的灵感
   */
  getInspiration() {
    const {
      step,
      objection_id,
      inspirationContent,
      roleInspiration,
      attackScript,
      batch_id,
      roleDetail,
    } =
    this.data;
    console.log(inspirationContent, roleInspiration, "inspirationContent");
    if (step == "defense" && !objection_id) {
      this.setData({
        inspirationContent: roleInspiration || attackScript[0].sale_message,
      });
      return;
    }
    if (inspirationContent) return;
    const {
      uuid
    } = wx.$util.getUserInfo();
    const history_message = objection_id?this.getHistoryAll():this.getHistory();
    const user_info = JSON.stringify({
      user_sex: roleDetail.replace(/.*性别:(.).*/, "$1"),
    });
    let api_params = 'inspiration'
    if(objection_id) {
      api_params = 'objectionInspiration'
    }
    aiApi[api_params]({
        history_message,
        batch_id,
        step,
        user_id: uuid,
        inspiration: "",
        user_info,
        objection_id
      })
      .then((res) => {
        this.setData({
          inspirationContent: objection_id?res.sale_message:res,
        });
      });
  },
  //提供相应的建议
  getSparring(user_message, retryCount = 0) {
    const {
      step,
      reject_reason,
      defense_step,
      batch_id,
      main_point,
      roleInspiration,
      round,
      person_type,
      objection_id
    } = this.data;
    this.data.isSend = false;
    let history_message = this.getHistory();
    const addVal = {
      role: 1,
      openAudio: false,
      content: "",
    };
    const audioBox = this.selectComponent("#audioBox");
    if (retryCount == 0) {
      audioBox.addList(addVal);
    }
    const {
      uuid
    } = wx.$util.getUserInfo();
    let api_params = 'sparring'
    if(objection_id) {
      api_params = 'objectionSparring'
    }
    aiApi[api_params]({
        person_type,
        user_message,
        history_message,
        step,
        user_id: uuid,
        batch_id,
        reject_reason: step == "defense" ? reject_reason : "",
        main_point: step == "defense" ? main_point : "0",
        defense_step,
        inspiration: step == "defense" ? roleInspiration : "",
        round,
      })
      .then((res) => {
        const {
          sale_message,
          round,
          defense_step,
          step: next_step
        } = res;
        console.log("batch_id", batch_id, "uuid", uuid);
        audioBox.setList({
            content: sale_message.replace(/,/g, ","),
            times: Math.ceil(sale_message.length / 4),
            spkTime: new Date().format("yyyy-MM-dd hh:mm:ss"),
          },
          next_step == "over" ? 1 : 0
        );
        this.data.isSend = true;
        if (step != next_step && next_step != "defense") {
          this.setData({
            inspirationContent: "",
          });
        }
        //手动初次进入攻防状态
        if (step != "defense" && next_step == "defense") {
          this.handleScript();
        }
        this.setData({
          round,
          defense_step,
          step: next_step,
        });
      })
      .catch((e) => {
        if (retryCount < 1) {
          // 如果重试次数小于1,则重试一次
          this.getSparring(user_message, retryCount + 1);
        }
      });
  },
  handleShow(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const {
      chatList
    } = this.data;
    chatList[index].show = true;
    this.setData({
      chatList,
    });
  },
  // 点击说话
  handleSpeak() {
    if (!this.data.isSend) {
      wx.$util.showToast("AI还未回复");
      return;
    }
    const {
      speakLoading
    } = this.data;
    if (speakLoading) return;
    this.setData({
      speakLoading: true,
      popType: "",
    });
    setTimeout(() => {
      this.setData({
        speakLoading: false,
      });
    }, 2000);
    const _this = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting["scope.record"]) {
          wx.authorize({
            scope: "scope.record",
            success() {
              // 用户已同意授权
              _this.setData({
                showSpeechPopup: true,
                controlBoxStyle: "z-index: 0;",
                showScenePopup: false,
              });
            },
            fail() {
              // 用户拒绝了授权
              console.log("用户拒绝了授权");
              wx.showModal({
                title: "提示",
                content: "需要获取录音权限,请点击确定进入设置页面进行授权。",
                showCancel: false,
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success(res) {
                        console.log(res.authSetting);
                        // 用户在设置页面设置了录音权限
                        if (res.authSetting["scope.record"]) {
                          console.log("用户在设置页面设置了录音权限");
                        } else {
                          console.log("用户在设置页面未设置录音权限");
                        }
                      },
                    });
                  }
                },
              });
            },
          });
        } else {
          // 已经有录音权限
          _this.setData({
            showSpeechPopup: true,
            controlBoxStyle: "z-index: 0;",
            showScenePopup: false,
          });
        }
      },
    });
  },
  behaviorSave(sparringResult = 0) {
    if(sparringResult == 1) {
      clearInterval(this.timer_save)
    }
    const {objection_id,taskId} = this.data
    const {
      uuid
    } = wx.$util.getUserInfo();
    carLifeApi.behaviorSave({
      id: taskId,
      staffUuid:uuid,
      sparringType:objection_id?2:1,
      sparringDuration: duration*1000,
      sparringResult
    }).then(res=>{
      this.data.taskId = res.data.sparringBehaviorId
    })
  },
  setBehaviorSave() {
    this.behaviorSave()
    this.timer_save = setInterval(this.behaviorSave,10*1000)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.setBehaviorSave()
    this.getIsPlay();
    let {
      roleType: type,
      stage,
      roleName: name,
      isDemo,
      entry,
      recordName,
      objection_id,
      title,
      product_name
    } = options;
    console.log(recordName)
    let params = {
      roleType: type,
    };
    if (name) {
      params = {
        roleName: name.replace("客户", ""),
      };
      this.setData({
        entry: "other",
      });
    }
    if (entry == "other") {
      this.setData({
        entry: "other",
      });
    }
    const roleInfo = await carLifeApi.sparringRole({
      currentPage: 1,
      pageSize: 100,
      ...params,
    });
    timer = setInterval(() => {
      duration++;
    }, 1000);
    let {
      avatar,
      roleType,
      roleName,
      roleDetail,
      attackScript,
      languageStyle: person_type,
    } = roleInfo.data.list[0];
    this.getScriptList(attackScript);
    const findChain = linkChainList.find((link) => link.name == stage);
    this.setData({
      objection_id,
      stage: product_name || `${findChain.name}环节`,
      step: findChain.type,
      avatar,
      isDemo: isDemo === "true",
      person_type,
      recordName,
      voice: VOICE[roleType],
      roleDesc: findChain.desc,
      roleName,
      roleType,
      roleDetail,
      batch_id: (Math.random() + "").slice(2),
    });
    if(title) {
      this.handleScript(title)
    }
  },
  async getIsPlay() {
    const {
      merchantId,
      uuid
    } = wx.$util.getUserInfo();
    const res = await aiApi.setSparringVerify({
      staffUuid: uuid,
      yqMerchantId: merchantId,
    });
    console.log(
      res.data.sparringTaskId,
      "sparringTaskIdsparringTaskIdsparringTaskId"
    );
    this.setData({
      sparringTaskId: res.data.sparringTaskId,
    });
  },
  //获取攻防话术
  getScriptList(attackScript) {
    const list = JSON.parse(attackScript);
    const scriptList = list.map((i) => {
      return {
        content: i.attack_message.replace(/,/g, ",").replace(/。/g, "。"),
      };
    });
    this.setData({
      scriptList,
      attackScript: list,
    });
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    duration = 0;
    clearInterval(timer);
    clearInterval(this.timer_save)
    this.deleteAudio();
    wx.setKeepScreenOn({
      keepScreenOn: false,
      fail() {
        //如果失败 再进行调用
        wx.setKeepScreenOn({
          keepScreenOn: false,
        });
      },
    });
  },
  onShow: function () {
    wx.setKeepScreenOn({
      keepScreenOn: true,
      fail() {
        //如果失败 再进行调用
        wx.setKeepScreenOn({
          keepScreenOn: true,
        });
      },
    });
  },
  deleteAudio() {
    const audioBox = this.selectComponent("#audioBox");
    if (!audioBox) return;
    const chatList = audioBox.data.list;
    chatList.forEach((item) => {
      if (item.filePath) {
        wx.removeSavedFile({
          filePath: item.filePath,
        });
      }
    });
  },
});