<script lang="ts" setup>
import { onMounted, provide } from 'vue'
import { showToast } from 'vant'
import MessageBox from './MessageBox.vue'
import { fetchToolList } from '@/api/config'
import { removeToken, removeUserInfo } from '@/utils/user'
import { createConversation, fetchSceneConfig, fetchUserQaRecordRage, fetchCurrentConversation, fetchTerminateQuestion } from '@/api/conversation'
import { checkTokenApi } from '@/api/config'
import moment from 'moment'
import { useRoute, useRouter } from 'vue-router'
import { debounce } from '@/utils/debounce';

const route = useRoute()
const router = useRouter()

const emits = defineEmits(['scrollToBottom', 'onShowWelcome', 'onHidenWelcome'])

const props = defineProps({
  showQuickToBottom: {
    type: Boolean,
    default: false
  }
})

const currentTimer = ref<any>(null)
const curQuestion = ref('')
const curGroupId = ref('')
const MessageBoxRef = ref<any>(null)
const textarea = ref<any>(null)

const addBtnShow = ref(false)

// 停止生成
async function onClickStop() {
  const res = await fetchTerminateQuestion({
    conversationId: submitParams.conversationId,
    question: curQuestion.value,
    groupId: curGroupId.value
  })
  if(res) {
    clearInterval(scrollerTimer.value)
    sendLoading.value = false
  }
}

// 重新生成
async function onClickReload(e: any) {
  curQuestion.value = e.data.question
  curGroupId.value = e.data.curGroupId
  let curIndex = -1
  if (messageList.value.length) {
    curIndex = messageList.value.findIndex((item: any) =>  item.groupId === e.data.groupId)
  } else {
    curIndex = messageListHistory.value.length - 1
  }

  await checkTokenApi()
  // console.log(textarea.value.style.height)
  textarea.value.style.height = 'auto'
  // textarea.value.style.height = '40px'
  sendLoading.value = true
  
  let fetchUrl = `/conversation/api/conversation/mobile/v1/submit_question_stream`
  const proxy = process.env.VITE_NODE_ENV === 'dev' ? '/api' : '/sdream-api'
  fetchUrl = proxy + fetchUrl

  if (messageList.value.length) {
    messageList.value[curIndex].showIndex = messageList.value[curIndex].answerList.length
    messageList.value[curIndex].answerList.push({
      question: e.data.question,
      isShow: false,
      terminateFlag: false,
      groupId: '',
      conversationId: '',
      streamData: []
    })
  } else {
    messageListHistory.value[curIndex].showIndex = messageListHistory.value[curIndex].answerList.length
    messageListHistory.value[curIndex].answerList.push({
      question: e.data.question,
      isShow: false,
      terminateFlag: false,
      groupId: '',
      conversationId: '',
      streamData: []
    })
  }
  autoBottom()
  useAi().callBaiduWorkshopSSE(
    fetchUrl,
    {...submitParams, question: e.data.question, groupId: e.data.groupId, productCode: e.data.productCode},
    (msg) => {
      if (msg.content && msg.content.code === '00000005') {
        sendLoading.value = false
        removeToken()
        removeUserInfo()
        window.location.reload()
        return
      }
      if (msg.content && msg.content.code !== '00000000') {
        showToast(msg.content.message)
        sendLoading.value = false
        clearInterval(scrollerTimer.value)
        messageList.value.pop()
        return
      }
      if (msg.type === 'DATA') {
        toolName.value = msg?.content?.data?.toolName || ''
        if (messageList.value.length) {
          messageList.value[curIndex].answerList[messageList.value[curIndex].answerList.length - 1].streamData.push(msg.content.data)
          messageList.value[curIndex].answerList[messageList.value[curIndex].answerList.length - 1].groupId = msg.content.data.groupId
          messageList.value[curIndex].answerList[messageList.value[curIndex].answerList.length - 1].conversationId = msg.content.data.conversationId
          messageList.value[curIndex].answerList[messageList.value[curIndex].answerList.length - 1].recordId = msg.content.data.recordId
        } else {
          messageListHistory.value[curIndex].answerList[messageListHistory.value[curIndex].answerList.length - 1].streamData.push(msg.content.data)
          messageListHistory.value[curIndex].answerList[messageListHistory.value[curIndex].answerList.length - 1].groupId = msg.content.data.groupId
          messageListHistory.value[curIndex].answerList[messageListHistory.value[curIndex].answerList.length - 1].conversationId = msg.content.data.conversationId
          messageListHistory.value[curIndex].answerList[messageListHistory.value[curIndex].answerList.length - 1].recordId = msg.content.data.recordId
        }
      }
      if (msg.type === 'END') {
        // sendLoading.value = false
        resetLastAnswer()
        // messageList.value[curIndex].answerList[e.curAnswerIdx + 1].isShow = true
      }
    }
  )
  return true
}

function diffShowTimer() {
  if (!currentTimer.value) {
    currentTimer.value = moment()
    return moment().format('HH:mm')
  } else {
    console.log(moment().diff(currentTimer.value, 'minute'))
    if (moment().diff(currentTimer.value, 'minute') >= 5) {
      currentTimer.value = moment()
      return moment().format('HH:mm')
    } 
  }
}

// 提交问题参数
let submitParams = {
  conversationId: '',
  sceneCode: '',
  toolName: '',
  productCode: '',
}

function scrollToBottom() {
  emits('scrollToBottom')
}

// 查询当前会话
async function getCurrentConversation() {
  const res = await fetchCurrentConversation()
  submitParams.conversationId = res.data.conversationId
  pageNum.value = 1
  MessageBoxRef.value.loadMoreCompleted('PROCESS')
  getSceneList(res.data.sceneCode)
  getUserQaRecordRage(res.data.conversationId)
}

// 创建新会话
function createNewConversation() {
  if (sendLoading.value) return
  showToast('当前已是新对话')
  pageNum.value = 1
  question.value = ''
  MessageBoxRef.value.loadMoreCompleted('PROCESS')
  initConversation()
  emits('onShowWelcome')
  getSceneList()
}

const messageList = ref<any[]>([])
const messageListHistory = ref<any[]>([])

async function initConversation() {
  const res = await createConversation()
  conversationInfo.value = res.data
  submitParams = {
    conversationId: conversationInfo.value.conversationId,
    sceneCode: '',
    toolName: '',
    productCode: '',
  }
  messageList.value = []
  messageListHistory.value = []
}

// 人物场景值设定
const sceneList = ref<SceneItem[]>([])

interface SceneItem {
  sceneName: string
  sceneCode: string
  icon: string
  comments: string
  activeFlag: boolean | undefined
}

async function getSceneList(sceneCode?: string) {
  const res = await fetchSceneConfig()
  sceneList.value = res.data ? res.data : []
  if (sceneCode) {
    sceneList.value.map((item: SceneItem) => {
      item.activeFlag = sceneCode === item.sceneCode
    })
    submitParams.sceneCode = sceneCode
  }
}

function changeSceneStatus(item: SceneItem) {
  if (sendLoading.value) return
  item.activeFlag = !item.activeFlag
  submitParams.sceneCode = item.activeFlag ? item.sceneCode : ''
  messageList.value.push({
    role: 'scene',
    select: item.activeFlag
  })
  setTimeout(() => {
    emits('scrollToBottom')
  }, 500)
}

// 工具
const toolListShow = ref(false)
const toolList = ref<ToolItem[]>([])

interface ToolItem {
  toolName: string
  toolIcon: string
  toolType: string
  toolContent: string
}

async function getToolList() {
  const res = await fetchToolList()
  toolList.value = res.data ? res.data : []
}

function onClickToolItem(item: ToolItem) {
  if (item.toolType === '01')
    window.location.href = item.toolContent
}

// 会话信息
const conversationInfo = ref({
  conversationId: '',
  conversationTitle: '',
  startTime: '',
})

// 查询历史问答记录
const pageNum = ref(1)
const showBox = ref(true)
async function getUserQaRecordRage(conversationId: string, pull?: boolean) {
  showBox.value = false
  const params = {
    conversationId,
    pageNum: pageNum.value++,
    pageSize: 10,
  }
  const res = await fetchUserQaRecordRage(params)
  if (pull) {
    if (res.data.length) {
      res.data.forEach((i: any) => {
        const answerList = i.answerList.map((item: any) => {
          return {
            question: item.question,
            isShow: true,
            groupId: item.groupId,
            conversationId: item.conversationId,
            streamData: item
          }
        })
        // 增加一条答案
        messageListHistory.value.unshift({
          role: 'system',
          groupId: i.groupId,
          showIndex: i.answerList.length,
          answerList: answerList
        })
        // 增加一条问题
        messageListHistory.value.unshift({
          qaTime: i.qaTime,
          role: 'user',
          message: i.question,
        })
      })
      // messageList.value.map((i: any) => {
      //   if (i.role === 'system') {
      //     i.isShow = true
      //   }
      // })
      MessageBoxRef.value.loadMoreCompleted('PROCESS')
      console.log('process')
    } else {
      console.log('end')
      MessageBoxRef.value.loadMoreCompleted('END')
    }
  } else {
    if (res.data.length) {
      getSceneList(res.data[0].sceneCode)
      res.data.forEach((i: any) => {
        // 增加一条问题
        messageListHistory.value.push({
          qaTime: i.qaTime,
          role: 'user',
          message: i.question.replace(/\n/g, "<br>")
        })
        // 增加一条答案
        const _answerList = i.answerList.map((item: any, index: number) => {
          return {
            question: item.question,
            isShow: true,
            groupId: item.groupId,
            productCode: item.productCode,
            conversationId: item.conversationId,
            streamData: [i.answerList[index]]
          } 
        })
        messageListHistory.value.push({
          role: 'system',
          isLastAnswer: false,
          groupId: i.groupId,
          showIndex: i.answerList.length - 1,
          answerList: _answerList
        })
      })
      resetLastAnswer()
      scrollToBottom()
      setTimeout(() => {
        showBox.value = true      
      }, 1000);
    } else {
      setTimeout(() => {
        showBox.value = true
      }, 800);
      emits('onShowWelcome')
    }
  }
}

// 获取更多历史记录
function refreshList() {
  getUserQaRecordRage(submitParams.conversationId, true)
}

// 点击提交输入框问题
const question = ref('')
const sendLoading = ref(false)
async function submitQuestion() {
  if (sendLoading.value) return
  sendLoading.value = true
  if (!question.value.trim()) {
    showToast('请输入您的问题')
    sendLoading.value = false
    return
  }
  messageList.value.push({
    qaTime: diffShowTimer(),
    role: 'user',
    message: question.value.replace(/\n/g, "<br>")
  })
  scrollToBottom()
  queryBaidu(question.value)
  question.value = ''
}

/**
 * 向百度发起提问
 */
async function queryBaidu(question: string) {
  curQuestion.value = question
  await checkTokenApi()
  // console.log(textarea.value.style.height)
  textarea.value.style.height = 'auto'
  // textarea.value.style.height = '40px'
  sendLoading.value = true

  let fetchUrl = `/conversation/api/conversation/mobile/v1/submit_question_stream`
  const proxy = process.env.VITE_NODE_ENV === 'dev' ? '/api' : '/sdream-api'
  fetchUrl = proxy + fetchUrl

  messageList.value.push({
    role: 'system',
    groupId: '',
    showIndex: 0,
    isLastAnswer: true,
    answerList: []
  })

  messageList.value[messageList.value.length - 1].answerList.push({
    question: question,
    productCode: submitParams.productCode,
    isShow: false,
    isLastAnswer: true,
    groupId: '',
    conversationId: '',
    terminateFlag: false,
    streamData: []
  })

  autoBottom()

  useAi().callBaiduWorkshopSSE(
    fetchUrl,
    {...submitParams, question},
    (msg) => {
      if (msg.content && msg.content.code === '00000005') {
        sendLoading.value = false
        removeToken()
        removeUserInfo()
        window.location.reload()
        return
      }
      if (msg.content && msg.content.code !== '00000000') {
        showToast(msg.content.message)
        sendLoading.value = false
        clearInterval(scrollerTimer.value)
        messageList.value.pop()
        return
      }
      if (msg.type === 'DATA') {
        toolName.value = msg?.content?.data?.toolName || ''
        messageList.value[messageList.value.length - 1].groupId = msg.content.data.groupId
        messageList.value[messageList.value.length - 1].answerList[0].streamData.push(msg.content.data)
        messageList.value[messageList.value.length - 1].answerList[0].groupId = msg.content.data.groupId
        messageList.value[messageList.value.length - 1].answerList[0].conversationId = msg.content.data.conversationId
        messageList.value[messageList.value.length - 1].answerList[0].recordId = msg.content.data.recordId
      }
      if (msg.type === 'END') {
        // sendLoading.value = false
        // messageList.value[messageList.value.length - 1].answerList[0].isShow = true
        resetLastAnswer()
      }
    }
  )
  return true
}

// 直接提问
function extraQuestion(params: any) {
  if (sendLoading.value) return
  if (params.type === 'rec') {
    messageList.value.push({
      role: 'user',
      message: params.question
    })
    scrollToBottom()
    queryBaidu(params.question)
  }
}

// 更新当前会话
function updateCurConversation(id: string) {
  emits('onHidenWelcome')
  pageNum.value = 1
  submitParams.sceneCode = ''
  MessageBoxRef.value.loadMoreCompleted('PROCESS')
  submitParams.conversationId = id
  messageList.value = []
  messageListHistory.value = []
  getUserQaRecordRage(id)
}

// 猜你喜欢
function onClickLikeItem(q: string) {
  console.log('回答状态', sendLoading.value)
  if (sendLoading.value) return
  messageList.value.push({
    role: 'user',
    message: q
  })
  scrollToBottom()
  queryBaidu(q)
}

// 结束答案
function onFullEnd() {
  sendLoading.value = false
  clearInterval(scrollerTimer.value)
  scrollToBottom()
}

// 点击产品
const toolName = ref('')
function onClickBoxProductItem(productInfo: {productCode: string, productName: string}) {
  if (sendLoading.value) return
  messageList.value.push({
    role: 'user',
    message: productInfo.productName
  })
  submitParams.productCode = productInfo.productCode
  submitParams.toolName = toolName.value
  scrollToBottom()
  queryBaidu(productInfo.productName)
  setTimeout(() => {
    submitParams.productCode = ''
    submitParams.toolName = ''
  }, 500)
}

const scrollerTimer = ref<any>(null)
function autoBottom() {
  scrollerTimer.value = setInterval(() => {
    scrollToBottom()
  }, 500)
}

function changeToolListShow() {
  router.push('/more')
  // toolListShow.value = !toolListShow.value
  scrollToBottom()
}

function autoResize() {
  if (textarea.value.scrollHeight > 68) {
    textarea.value.style.height = 68
    textarea.value.style.overflow = 'scroll'
    return
  }
  textarea.value.style.height = 'auto';
  textarea.value.style.height = `${textarea.value.scrollHeight}px`;
}

function textareaFocus() {
  toolListShow.value = false
}

function onQuickToBottom() {
  scrollToBottom()
}

function resetLastAnswer() {
  messageListHistory.value.concat(messageList.value).map((i: any, index: number) => {
    i.isLastAnswer = index === messageListHistory.value.concat(messageList.value).length - 1
  })
}

// provide stopAnswerCount
const stopAnswerCount = ref(0)
function stopAnswer() {
  stopAnswerCount.value++
}
provide('stopAnswerCount', stopAnswerCount)

// 使用示例
// function handleAction() {
//   console.log('Action performed');
// }

const debouncedAction = debounce(() => {
  addBtnShow.value = false
}, 3000);

function pageScroll() {
  addBtnShow.value = true
  debouncedAction()
}

defineExpose({
  extraQuestion,
  updateCurConversation,
  pageScroll
})

onMounted(() => {
  if(route.query.conversationId) {
    updateCurConversation(route.query.conversationId as string)
    getSceneList(route.query.sceneCode as string)
  } else {
    getCurrentConversation()
  }
  getToolList()
  autoResize()
})

onBeforeUnmount(() => {
  textarea.value.removeEventListener('input', autoResize); // 移除监听
})
</script>

<template>
  <!-- <div class="mask" v-if="sendLoading"></div> -->
  <MessageBox :class="{'h-hidden': !showBox}" :historyMode="true" ref="MessageBoxRef" @refreshList="refreshList" :toolListShow="toolListShow" @onFullEnd="onFullEnd" @onClickLikeItem="onClickLikeItem" @onClickBoxProductItem="onClickBoxProductItem" :message-list="messageListHistory" @onClickStop="onClickStop" @onClickReload="onClickReload" />
  <MessageBox :historyMode="false" :toolListShow="toolListShow" @onFullEnd="onFullEnd" @onClickLikeItem="onClickLikeItem" @onClickBoxProductItem="onClickBoxProductItem" :message-list="messageList" @onClickStop="onClickStop" @onClickReload="onClickReload" />
  <div class="cps-op-init-container">
    <div v-if="showQuickToBottom" class="down" @click="onQuickToBottom">
      <img src="./images/down.png" alt="">
    </div>
    <div class="add">
      <img v-if="addBtnShow" class="add-plus-icon" src="./images/add-plus.png" alt="" @click="createNewConversation">
      <img v-else class="add-icon" src="./images/add.png" alt="" @click="addBtnShow = true">
    </div>
    <!-- <div class="character">
      <div v-for="(item, index) in sceneList" :key="index" class="tag" :class="{ active: item.activeFlag }" @click="changeSceneStatus(item)">
        <img :src="item.icon" alt="">
        <div class="txt">
          {{ item.sceneName }} <span v-if="item.activeFlag"><span style="color: #E9EBF1;">|</span> <span style="font-size: 11px;color: #B2B8C1;">退出</span></span> 
        </div>
      </div>
    </div> -->
    <div class="input-box">
      <img src="./images/more.png" class="more-icon" @click="changeToolListShow">
      <textarea @focus="textareaFocus" rows="1" v-model="question" :disabled="sendLoading" class="input" placeholder="您可以随时问我..." ref="textarea" @input="autoResize" maxlength="3000"></textarea>
      <img v-if="sendLoading" src="./images/stop-icon.png" class="send-btn" alt="" @click="stopAnswer">
      <img v-else src="./images/send.png" class="send-btn" @click="submitQuestion">
      <!-- <img v-if="!toolListShow" src="./images/more.png" class="more-icon" @click="changeToolListShow">
      <img v-else src="./images/more-2.png" class="more-icon" @click="changeToolListShow"> -->
    </div>
    <div v-if="toolListShow" class="tool">
      <div v-for="(item, index) in toolList" :key="index" class="item" @click="onClickToolItem(item)">
        <img class="icon" :src="item.toolIcon" alt="">
        <div class="name">
          {{ item.toolName }}
        </div>
      </div>
    </div>
    <div class="safe-box"></div>
  </div>
</template>

<style lang="scss" scoped>

textarea {
  width: 100%;
  resize: none; /* 防止用户调整大小 */
  box-sizing: border-box;
  overflow: hidden; /* 隐藏滚动条 */
}
 
textarea:focus {
  outline: none;
}

.cps-op-init-container {
  border-radius: 24px 24px 0px 0px;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  z-index: 3;
  .safe-box {
    background: #f6f7f9;
    height: calc(constant(safe-area-inset-bottom));
    height: calc(env(safe-area-inset-bottom));
  }
  .down {
    position: relative;
    img {
      position: absolute;
      width: 40px;
      height: 40px;
      bottom: 68px;
      right: 8px;
    }
  }
  .add {
    position: relative;
    .add-plus-icon {
      position: absolute;
      width: 94px;
      height: 34px;
      bottom: 20px;
      right: 0;
    }
    .add-icon {
      position: absolute;
      width: 34px;
      height: 34px;
      bottom: 20px;
      right: 0;
    }
  }
  .character {
    background: #f6f7f9;
    display: flex;
    padding: 0 15px;
    padding-bottom: 8px;
    padding-top: 8px;
    .title {
      font-size: 14px;
      color: #393d46;
      line-height: 20px;
      font-weight: 600;
      font-weight: bolder;
      margin-right: 12px;
      margin-top: 4px;
    }
    .tag {
      background: rgba(255, 255, 255, 0.8);
      border-radius: 16px;
      border: 1px solid #ffffff;
      padding: 4px 12px;
      display: flex;
      &.active {
        border-color: #15bda5;
        .txt {
          color: #15bda5;
          span {
            display: inline-block;
            line-height: 16px;
          }
        }
      }
      img {
        width: 16px;
        height: 16px;
        margin-right: 8px;
        margin-top: 2px;
      }
      .txt {
        font-size: 13px;
        color: #393d46;
        line-height: 20px;
      }
    }
  }
  .input-box {
    background: #F6F7F9;
    // box-shadow: 0px 0px 0px 0px #f4f4f4;
    border-radius: 24px 24px 0px 0px;
    padding: 6px 16px;
    display: flex;
    .input {
      box-sizing: border-box;
      // width: 299px;
      background: #fff;
      border-radius: 8px;
      padding: 10px 34px 10px 12px;
      font-size: 13px;
      line-height: 20px;
      border-radius: 20px;
      &::placeholder {
        color: #b2b8c1;
      }
    }
    .send-btn {
      position: absolute;
      top: 8px;
      right: 12px;
      width: 28px;
      height: 28px;
      margin: 4px 12px;
    }
    .more-icon {
      width: 32px;
      height: 32px;
      margin-top: 4px;
      margin-right: 10px;
    }
  }
  .tool {
    background: #f6f7f9;
    padding: 24px 32px;
    display: flex;
    justify-content: space-between;
    .item {
      .icon {
        width: 32px;
        height: 32px;
        margin: 0 auto 6px;
        display: block;
      }
      .name {
        height: 16px;
        font-weight: 400;
        font-size: 11px;
        color: #393d46;
        line-height: 16px;
        text-align: center;
      }
    }
  }
}

.mask {
  position: fixed;
  z-index: 999999;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: #000;
  opacity: 0;
}

.h-hidden {
  opacity: 0;
}

</style>
