<!-- 右侧聊天界面 -->
<template>
  <div class="box">

      <!-- {{ this.extractContent( item.answer, '```', '```') }} -->
    <div class="contentBox" ref="contentBox" v-if="myHistory.length>0">
      <div v-for="(item,index) in myHistory" :key="index">
        <div class="userBox">
          <div class="content">
            {{ item.content }}
          </div>
          <div class="icon">
            {{ item.role }}
          </div>
        </div>
        <div v-if="item.answer" class="gptBox">
          <div class="icon">
            GPT
          </div>
          <div class="content">
            <span v-if="item.answer">{{ item.answer }}</span>
          
            <codePreview v-if="item.code.content" :type="item.code.language" :code="getcode(item.code.content)"/>
            <span v-if="item.answer2">{{ item.answer2 }}</span>
            
          </div>
        </div>
      </div>
    </div>
    <div class="initBox" v-else>
      <div class="text">
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;你好，<br>
      我是人工智能语言模型<br>
      我可以回答你的问题，为你提供有用信息，帮助你完成创作。<br>
      </div>
    </div>
    <div class="inputBox">
      <el-input placeholder="请输入内容" v-model="inputContent" class="input-with-select" @keyup.enter.native="submit">
        <el-button slot="append" icon="el-icon-position" @click="submit"></el-button>
      </el-input>
      <el-button   icon="el-icon-delete" style="margin-left:10px" @click="clear" type="danger" plain></el-button>

    </div>
  </div>
</template>

<script>
import { GetStreaming } from '@/utils/getStreaming.js';
import codePreview from '../codePreview';
export default {
  data () {
    return {
      x: '当然可以，以下是使用JavaScript编写的“Hello World”示例代码： ```javascript console.log("Hello World"); ``` 将此代码复制并粘贴到浏览器的控制台或Node.js环境中，按下回车键，你将看到控制台输出 “Hello World”。',
      inputContent: null,
      myHistory: [],
      heistoryRotate: null, // 历史轮数
      param: {
        query: null,
        history: [],
        'stream': true,
        'model_name': '',
        'temperature': 0.7
      }
    };
  },
  props: ['chatForm'],
  components: {codePreview},

  computed: {

  },

  mounted () {
    // this.myHistory.push({
    //   'role': 'user',
    //   'content': this.inputContent,
    //   'answer': '',
    //   'code': {
    //     temporary: '',
    //     language: undefined,
    //     content: ''
    //   },
    //   'answer2': ''
       
    // })
    // let a = '当然可以，以下是使用JavaScript编写的“Hello World”示例代码： ```javascript console.log("Hello World"); ``` 将此代码复制并粘贴到浏览器的控制台或Node.js环境中，按下回车键，你将看到控制台输出 “Hello World”。'

    // for (let index = 0; index < a.length; index++) {
    //   setTimeout(() => {
    //     // b += a[index]
    //     this.onmessage(a[index])
    //   }, 100 * index);
    // }
  },

  methods: {

    getCode (answer) {
      return this.extractContent(answer, '```', '```')
    },
    clear () {
      this.param.query = null
      this.param.history = []
      this.inputContent = null
      this.myHistory = []
    },
    submit () {
      this.param.model_name = this.chatForm.model_name
      this.param.temperature = this.chatForm.temperature
      this.heistoryRotate = this.chatForm.heistoryRotate
      let apiUrl
      if (this.chatForm.pattern === 'LLM 对话') {
        apiUrl = '/2api/chat/chat'
      } else if (this.chatForm.pattern === '知识库问答') {
        apiUrl = '/2api/chat/knowledge_base_chat'
        this.param = { ...this.param, ...this.chatForm.knowledgeConfige }
      } else if (this.chatForm.pattern === '搜索引擎问答') {
        apiUrl = '/2api/chat/search_engine_chat'
        this.param = { ...this.param, ...this.chatForm.searchConfige }
      }
      if (!this.inputContent) return
      this.param.query = this.inputContent;
      this.myHistory.push({
        'role': 'user',
        'content': this.inputContent,
        'answer': '',
        'code': {
          temporary: '',
          language: undefined,
          content: ''
        },
        'answer2': ''
       
      })
      this.inputContent = null;
      this.param.history = this.myHistory.slice(0, -1).slice(-this.heistoryRotate).map((item) => { return { role: item.role, content: item.content } })
      this.$emit('submit')

      let getData = new GetStreaming(apiUrl, this.param, this.onmessage)
      getData.initeventSource()
    },
    onmessage (data) {
      let nowChat = this.myHistory[this.myHistory.length - 1]
      let code = nowChat.code
      let languages = ['javascript', 'php', 'java', 'css', 'python', 'html', 'c', 'c++', 'c#']

      if (nowChat.answer.indexOf('```') === -1) {
        nowChat.answer += data
      } else {
        if (code.content.indexOf('```') === -1) {
          if (code.temporary.indexOf('```') === -1) {
            nowChat.code.content += data
          }
          nowChat.code.temporary += data
          if (code.temporary.split(' ').length > 1) {
            if (languages.indexOf(code.temporary.split(' ', 1)[0].toLowerCase()) === -1) {
              code.language = undefined
            } else {
              code.language = code.temporary.split(' ')[0]
            }
          }
          console.log(code);
        } else {
          console.log(data);
          nowChat.answer2 += data
        }
      }
  
      this.$nextTick(() => {
        this.$refs.contentBox.scrollTo(0, this.$refs.contentBox.scrollHeight)
      })
    },
    getcode (data) {
      if (this.myHistory[this.myHistory.length - 1].code.language) {
        
      }
      return data.split(' ').slice(1).join('').replace('```', '')
    }

  }
}

</script>
<style scoped>
.contentBox {
  height: 100%;
  box-sizing: border-box;
  padding-bottom: 20px;
  overflow-y: auto;
  overflow-x: hidden;
}
.initBox .text{
  background-color: #f3f3f3;
  padding: 10px;
  border-radius: 10px;
  width: 100%;
  line-height: 23px;
  font-size: 14px;
}
.initBox{
  height: 100%;
  box-sizing: border-box;
  padding-bottom: 20px;
}
.box {
  height: 100%;
  padding: 10px;
  position: relative;
  display: flex;
  flex-direction: column;
  background-image: url('~@/assets/img/ai.png');
  background-repeat: no-repeat;
  background-position: center center;
  background-size: auto  50%;

}
.icon {
  height: 32px;
  width: 32px;
  border-radius: 50%;
  text-align: center;
  overflow: hidden;
  line-height: 32px;

  flex-shrink: 0;
  color: #fff;
}

.userBox,
.gptBox {
  display: flex;
  margin-bottom: 20px;
  width: 100%;
}
.userBox {
  justify-content: flex-end;
}
.userBox .icon {
  margin-left: 10px;
  background-color: #4754b1;
}
.gptBox .icon {
  margin-right: 10px;
  background-color: #363c6e;
}
.content {
  background-color: #f3f3f3;
  padding: 10px;
  border-radius: 10px;
  height: fit-content;
}
.inputBox{
  display: flex;
}
</style>
