ChatGPT.vue 9.49 KB
<template>
  <div
    :class="['chat-gpt-box',{'guestMode':guestMode}]"
    v-show="show"
  >
    <div
      :class="['view',{'show-tips':showTips&& issuesList.length}]"
      ref="contentView"
    >
      <div class="content-item left">
        <div class="sprite-icon icon-ai icon"></div>
        <div class="content">
          您可以向我提问汽车后市场领域(如汽车精品/汽车保险/延保服务等)的业务相关问题,AI助手将给您提供方案建议。
        </div>
      </div>
      <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']">
      <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>
    </div>
  </div>
</template>

<script type='text/ecmascript-6'>
import { chatgptApi } from '@/api'
import * as dayjs from 'dayjs'
import emojiRegex from 'emoji-regex'
export default {
  name: 'ChatGpt',
  props: {
    show: Boolean
  },
  data () {
    return {
      contentList: [],
      issuesList: window.$fetchConfig.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: {
    filterText (text) {
      const whitespaceRegex = /^\s+$/g
      return text.replace(emojiRegex(), '').replace(whitespaceRegex, '')
    },
    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
      try {
        if (!content) throw false
        if (padding) throw '请等待回复后再试'
        //游客模式不限制次数
        if (todayQuestionLeft < 1 && !guestMode) throw `每天每个用户最多发送提问${questionCountTotal}个问题`
      } catch (error) {
        if (error) this.showToast(error)
        return
      }
      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: 0 12px;
      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: #c9e7fe;
        border: 1px solid #3582ee33;
        border-radius: 10px 0 10px 10px;
      }
    }
  }
  .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>