<template>
  <div class="reasoning-content">
    <div
      class="content-left"
      :style="{
        width: isCollapse ? 'calc(100% - 200px)' : 'calc(100% - 7px)'
      }"
    >
      <div class="body-box" ref="container">
        <reasoning-view
          ref="reasoningRef"
          @completeFun="completeFun"
          :reasoningList="reasoningList"
        />
      </div>
      <div class="message-box">
        <div class="tip-box">
          <p class="active_item">
            <el-icon size="6" color="#fff"><Plus /></el-icon>
            {{ generateTitle('新建对话') }}
          </p>
          <div class="tip-text" v-show="disableStatus">
            {{ generateTitle('回答输出中，暂不能再次提问') }}
          </div>
        </div>
        <TextareaView ref="textareaRef" :minRows="1" @submitFun="submitFun" />
      </div>
    </div>
    <collapseView
      ref="collapseRef"
      :reasoningList="reasoningList"
      @changeStatusFun="changeStatusFun"
    />
  </div>
</template>
<script setup lang="ts">
import ReasoningView from '../../components/ReasoningView/index.vue'
import TextareaView from '../../components/TextareaView.vue'
import collapseView from '../../components/collapseView/index.vue'
import { Plus } from '@element-plus/icons-vue'
import { ref, onMounted, nextTick } from 'vue'
// import { getModelList } from '../../api/user'
import { useRoute } from 'vue-router'
import useWebSocket from '../../utils/websocket'
import { getAgent } from '../../utils/agent'
import { generateTitle } from '../../utils/i18n'
const route: any = useRoute()
const reasoningRef = ref<any>(null)
const textareaRef = ref<any>(null)
const collapseRef = ref<any>(null)
const isCollapse = ref<boolean>(true)
const changeStatusFun = (val: boolean) => {
  isCollapse.value = val
}
const reasoningList = ref<Array<any>>([])
// const getModelListFun = async () => {
//   try {
//     const { data, code } = await getModelList()
//     if (code) {
//       reasoningList.value = data
//     }
//   } catch (error) {
//     console.log(error)
//   }
// }
const submitFun = (val: any) => {
  completeFun()
  addMode(JSON.parse(val).message)
  ws.send(val)
}
const addMode = (val: any) => {
  endStatus.value = false
  reasoningList.value.push({
    title: val,
    children: []
  })
  reasoningRef.value.completeList.push({
    show: false,
    index: reasoningRef.value.completeList.length
  })
}
const disableStatus = ref(false)
const completeFun = () => {
  disableStatus.value = true
  textareaRef.value.disableStatus = true
}
const handleMessage = (e: any) => {
  getMessage(e.data)
  getHeight()
}
const startStatus = ref(false)
const contentStatus = ref(false)
const endStatus = ref(false)
const getMessage = async (e: any) => {
  // if (e.split('TERMINATE')[1]) {
  //   talkList.value += e.split('TERMINATE')[0]
  //   reasonStatus.value.show = false
  //   endShow.value = true
  //   extractSynthesisProcess()
  // } else {
  //   talkList.value += e
  // }
  reasoningRef.value.reasonStatus.show = true
  // talkList.value += e
  // console.log(talkList.value);
  let list = reasoningList.value
  let children = list[list.length - 1].children
  // if (
  //   e.includes(
  //     '--------------------------------------------------------------------------------'
  //   )
  // ) {
  //   startStatus.value = true
  // } else if (startStatus.value) {
  if (parseChatData(e)) {
    if (parseChatData(e)?.type) {
      children.push({
        title: parseChatData(e)?.title,
        content: ''
      })
      reasoningRef.value.reasonStatus.index = children.length - 1
    } else {
      if (children[children.length - 1].content) {
        children[children.length - 1].content += parseChatData(e)?.current
      } else {
        children[children.length - 1].content = parseChatData(e)?.current
      }
    }
  }

  // }
}
function parseChatData(e: any) {
  let condition =
    !e.includes(
      '--------------------------------------------------------------------------------'
    ) &&
    !e.includes(
      `********************************************************************************`
    ) &&
    !e.includes('Starting a new chat....') &&
    !e.includes('>>>>>>>>')
  let title = ''
  let current = ''
  let regex = /Next speaker: (.*)/
  if (condition) {
    if (e.includes('Planer') || e.includes('Planner')) {
      title = getAgent('Planer')
      return {
        title,
        type: true
      }
    }
    if (e.match(regex) && e.match(regex)[1]) {
      // if (!getAgent(e.match(regex)[1])) {
      //   contentStatus.value = true
      //   return
      // }
      // contentStatus.value = false
      // title = getAgent(e.match(regex)[1])
      title = getAgent(e.match(regex)[1]) || e.match(regex)[1]
      return {
        title,
        type: true
      }
    }
    if (contentStatus.value) {
      return
    }
    if (e.includes('TERMINATE')) {
      endStatus.value = true
      reasoningRef.value.reasonStatus.show = false
      reasoningRef.value.completeList[
        reasoningRef.value.completeList.length - 1
      ].show = true
      disableStatus.value = false
      textareaRef.value.disableStatus = false
      startStatus.value = false
    }
    current = e.replace(
      /(?<!`)TERMINATE(?<!\*\*)|TERMINATE(?!\*\*)|`TERMINATE`/g,
      ''
    )
    return {
      current,
      type: false
    }
  }
}
const ws = useWebSocket(handleMessage)
const sendFun = () => {
  setTimeout(() => {
    addMode(JSON.parse(route.query.message).message)
    completeFun()
    ws.send(JSON.stringify(route.query.message))
  }, 300)
}
const container = ref<any>(null)
const getHeight = () => {
  container.value.scrollTop = container.value.scrollHeight + 150
  collapseRef.value.scrollTop = collapseRef.value.scrollHeight + 50
}
onMounted(() => {
  // getModelListFun();
  nextTick(() => {
    getHeight()
    sendFun()
  })
})
</script>
<style scoped>
@import './index.less';
</style>
