<!-- 右侧聊天界面 -->
<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 }} -->
            <contentView :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> -->
            <contentView :content="item.answer" />

          </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-popover placement="top" width="400"    trigger="click" ref="popover">
        <el-select v-model="templateController" filterable placeholder="请选择"  value-key="templateId"  @change="templateControllerChange">
          <el-option v-for="item in templateControllerList" :key="item.value" :label="item.label" :value="item">
          </el-option>
        </el-select>
        <el-button slot="reference" icon="el-icon-s-opportunity" style="margin-left:10px" @click="clear" type="primary" plain>提示词</el-button>
      </el-popover> -->

      <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';
import contentView from '../contentView';

export default {
  data () {
    return {
      templateController: undefined,
      isPromptTemplate: true,
      inputContent: null,
      myHistory: [],
      heistoryRotate: null, // 历史轮数
      param: {
        query: null,
        history: [],
        prompt_template: '',
        'stream': true,
        'model_name': '',
        'temperature': 0.7
      }
    };
  },
  props: ['chatForm'],
  components: { contentView },

  computed: {

  },

  mounted () {
    this.$bus.$on('isPromptTemplate', (data) => {
      this.isPromptTemplate = data
    })
  },
  beforeDestroy () {
    // 移除监听事件 "share"
    this.$bus.$off('isPromptTemplate')
  },
  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
      this.param.prompt_template = this.isPromptTemplate ? this.chatForm.prompt_template : undefined
      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).forEach((item) => {
        this.param.history.push(...[{ role: item.role, content: item.content }, { role: 'assistant', content: item.answer + item.code?.content + item.answer2 }])
      })
      this.$emit('submit')

      let getData = new GetStreaming(apiUrl, this.param, this.onmessage)
      getData.initeventSource()
    },
    onmessage (data) {
      let nowChat = this.myHistory[this.myHistory.length - 1]
      if (this.chatForm.pattern === 'LLM 对话') {
        nowChat.answer += data
      } else if (this.chatForm.pattern === '知识库问答') {
        let temporary = JSON.parse(`[${data}]`.replace(/}{/g, '},{'))
        temporary.forEach((item) => {
          nowChat.answer += item.answer || '\n' + item.docs
        })
      } else if (this.chatForm.pattern === '搜索引擎问答') {

      }

      // 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) {
      //       code.content += data
      //     }
      //     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]
      //       }
      //     }
      //   } else {
      //     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('```', '')
    //   } else {
    //     return data.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>
