ChatAnswer.vue 10.4 KB
<template>
  <div :class="['chat-gpt-box', { guestMode: guestMode }]">
    <div :class="['view', { 'show-tips': showTips && issuesList.length }]" ref="contentView">
      <template v-for="(i, index) in contentList">
        <div :key="index">
          <template v-if="i.contentType == 1">
            <div class="content-item left">
              <div class="sprite-icon icon-ai icon"></div>
              <div class="content">
                <template v-if="!i.content">
                  <van-loading class="loading" color="#3582EE" />
                </template>
                <template v-else>
                  {{ i.content }}
                </template>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="content-item right">
              <div class="content">{{ i.content }}</div>
              <div class="sprite-icon icon-profile icon"></div>
            </div>
          </template>
        </div>
      </template>
    </div>
    <template v-if="showTips && issuesList.length">
      <div class="tips-box">
        <div class="tips-title flex">
          您可以这样向我提问
          <div class="sprite-icon icon-close" @click="showTips = false"></div>
        </div>
        <div class="tips-view">
          <template v-for="(i, index) in issuesList">
            <div :key="index" class="tips-item flex" @click="send(i)">
              {{ i }}
              <div class="sprite-icon icon-more"></div>
            </div>
          </template>
        </div>
      </div>
    </template>
    <div :class="['input-box flex isFullSucreen']">
      <template v-if="inputType == 1">
        <van-field v-model="issue" :border="false" placeholder="请输入文字向AI提问" enterKeyhint="send" @keydown="onkeydown" ref="input" maxlength="1000"></van-field>
        <van-button @click="send()">发送</van-button>
      </template>
      <template v-else>
        <div class="audio-item" @touchstart="touchstart" @touchend="touchend">按住 说话</div>
      </template>
    </div>
  </div>
</template>
<script type="text/ecmascript-6">
import { chatgptApi } from '@/api'
import * as dayjs from 'dayjs'
export default {
  name: 'ChatAnswer',
  props: {
    show: Boolean
  },
  data () {
    return {
        inputType:1,
      contentList: [{
        contentType:1,
        content:'一键提示'
      }],
      issuesList:  [],
      showTips: true,
      issue: '',
      scriptLibraryAIId: '',
      todayQuestionLeft: 0,
      questionCountTotal: 999,
      lastQuestionTime: '',
      padding: false
    }
  },
  computed: {
    guestMode () {
      return this.$store.state.app.guestMode
    }
  },
  watch: {
    // issue (newText) {
    //   this.issue = this.filterText(newText);
    // }
  },
  mounted () {
    // if (!this.guestMode) this.getAiId()
  },
  methods: {
    startRecording() {
  let recognition = new webkitSpeechRecognition(); // 创建语音识别对象
  recognition.start(); // 开始语音识别

  recognition.onresult = function(event) {
    const result = event.results[0][0].transcript; // 获取语音识别结果
    console.log(result); // 在控制台输出结果(可以根据需要进行其他处理)
  };
},
    touchstart(e){
          e.preventDefault();//阻止默认事件
          this.timeOut = setTimeout(() => {
            console.log('在这里执行长按事件---',);
            wx.startRecord({
                success: () => {
                  this.voiceTimer = setInterval(() => {
                    this.voiceTime++;
                  }, 1000);
                  this.voiceEnd();
                },
                cancel: () => {
                  Toast("用户拒绝授权录音");
                },
            });//开始录音
            this.timeOut = 0//若开始录音,timeOut=0,当结束录音时,执行停止录音函数
            this.isRecord = true
          }, 500);
        },
        touchend(e){
          e.preventDefault();
          clearTimeout(this.timeOut)//结束录音时清除定时器
          if (this.timeOut!=0) {
          //点击事件的逻辑
            this.$toast.show('长按录音')
          }else{
          //长按事件的逻辑
            if (this.isRecord) {
              this.endSpeek()
              this.isRecord=false
            } else {
              return
            }
          }
        },
    async getAiId () {
      this.showLoading()
      const { merchantId, uuid, merchantName, userName, loginList } = this.getLocalStorage('dj_scrm_userInfo')
      let { phone } = loginList.find(e => e.merchantNo == merchantId)
      try {
        const { code, data, message } = await chatgptApi.getAiId({
          merchantId,
          merchantName,
          staffUuid: uuid,
          staffName: userName,
          staffPhone: phone
        })
        if (code == 0 && data) {
          this.scriptLibraryAIId = data.scriptLibraryAIId
          this.todayQuestionLeft = data.todayQuestionLeft
          this.questionCountTotal = data.questionCountTotal
        }
        else throw message
        this.hideLoading()
      } catch (error) {
        console.log(error)
        this.showToast(error)
      }
    },
    onkeydown (e) {
      if (e.keyCode == 13) {
        this.send()
      }
    },
    send (val) {
      const { issue, todayQuestionLeft, questionCountTotal, padding, guestMode } = this,
        content = val || issue
        if (!content) return false
      const id = Date.now()
      this.contentList.push({
        contentType: 0,
        content,
        chatTime: dayjs(id).format('YYYY-MM-DD HH:mm:ss'),
        id
      })
      this.padding = true
      this.lastQuestionTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      if (!val) {
        this.issue = ''
        this.$refs.input.blur()
      }
    //   this.$nextTick(() => {
    //     this.addRecord(id)
    //     this.toQuestionChatGPT(content)
    //   })
    },
    toBottom () {
      this.$nextTick(() => {
        this.$refs.contentView.scrollTop = 999999999
      })
    },
    async toQuestionChatGPT (question) {
      const id = Date.now()
      this.contentList.push({
        contentType: 1,
        content: '',
        id
      })
      this.toBottom()
      try {
        const { response } = await chatgptApi.issueChatGpt({
          question,
          history: ''
        })
        this.padding = false
        this.contentList.find(i => i.id == id).chatTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
        let index = 0, speed = 10
        const typeWriter = () => {
          if (index < response.length) {
            this.contentList.find(i => i.id == id).content += response.charAt(index)
            index++
            setTimeout(typeWriter, speed)
            this.toBottom()
          } else this.addRecord(id)
        }
        typeWriter()
      } catch (error) {
        this.padding = false
      }
    },
    addRecord (id) {
      const { contentList, scriptLibraryAIId, lastQuestionTime } = this,
        item = contentList.find(i => i.id == id)
      if (this.guestMode) return //游客模式不上报
      delete item.id
      let params = {
        lastQuestionTime,
        aiRecordList: [item],
        scriptLibraryAIId
      }
      if (item.contentType == 1 && item.content.indexOf('很抱歉') == -1) params.questionEffectiveCount = 1
      if (item.contentType != 1) params.questionCount = 1
      chatgptApi.updatedAiRecord(params).then(res => {
        this.getAiId()
      })
    }
  }
}
</script>
<style scoped lang="scss">
.chat-gpt-box {
  height: calc(100vh - 50px - var(--constantSafeAreaInsetBottom));
  height: calc(100vh - 50px - var(--envSafeAreaInsetBottom));
  .view {
    height: calc(100% - 52px);
    overflow-y: scroll;
    position: relative;
    box-sizing: border-box;
    padding-bottom: 12px;
    background-color: #fff;
    .content-item {
      margin-top: 12px;
      padding: 4px 16px;
      display: flex;
      .icon {
        width: 20px;
        height: 20px;
        user-select: none;
      }
      .content {
        max-width: 290px;
        background: #f8f9f9;
        box-sizing: border-box;
        padding: 10px;
        font-size: 16px;
        color: #333333;
        line-height: 22px;
        word-break: break-all;
      }
    }
    @keyframes typing {
      from {
        width: 0;
      }
      to {
        width: 100%;
      }
    }
    .left {
      .icon {
        margin-right: 6px;
      }
      .content {
        border-radius: 0 10px 10px 10px;
      }
    }
    .right {
      .icon {
        margin-left: 6px;
      }
      .content {
        margin-left: auto;
        background: rgb(160, 250, 116);
        border: 1px solid #3582ee33;
        border-radius: 10px 0 10px 10px;
      }
    }
  }
  .audio-item {
    width: 300px;
    height: 40px;
    border: 1px solid #666;
    text-align: center;
    line-height: 40px;
    font-size: 16px;
    color: #333333;
  }
  .show-tips {
    height: calc(100% - 262px);
  }
  .tips-box {
    width: 100%;
    height: 210px;
    background-image: linear-gradient(180deg, #d6e6fb 0%, #ffffff 14%);
    position: relative;
    box-sizing: border-box;
    .tips-title {
      padding: 14px 16px 7px;
      font-weight: 600;
      font-size: 16px;
      color: #3582ee;
      .icon-close {
        margin-left: auto;
      }
    }
    .tips-view {
      height: calc(100% - 42px);
      overflow-y: scroll;
      padding: 0 16px;
      .tips-item {
        border-bottom: 1px solid #e4e6ee;
        line-height: 18px;
        padding: 7px 0;
        font-size: 13px;
        color: #333333;
        .icon-more {
          margin-left: auto;
          flex-shrink: 0;
          // background-position: -60px -72px;
          // transform: translateY(-2px);
        }
        &:last-of-type {
          border: none;
        }
      }
    }
  }
  .input-box {
    padding: 7px 11px 7px 16px !important;
    background: #ffffff !important;
    .van-field {
      width: 278px;
      padding: 9px 16px;
      font-size: 14px;
      color: #c8c9cc;
      line-height: 20px;
      background: #f7f8fa;
      border-radius: 19px;
    }
    .van-button {
      width: 60px;
      height: 38px;
      background: #3582ee;
      border-radius: 19px;
      margin-left: auto;
      font-weight: 500;
      font-size: 16px;
      color: #ffffff;
      padding: 0;
    }
  }
  .fixedKeyboard {
    // position: fixed;
    // width: 100%;
    // box-sizing: border-box;
    // bottom: 0;
  }
}
.guestMode {
  height: calc(100vh - var(--constantSafeAreaInsetBottom));
  height: calc(100vh - var(--envSafeAreaInsetBottom));
}
</style>