<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import MessageItem from './message-item.vue'
import ContinueQuestion from './continue-question.vue'
import { useScroll } from '@/composables/useScroll'
import { useBackBottom } from '@/composables/useBackBottom'
import HitKnowledge from './hit-knowledge.vue'

interface Props {
  messageList: Map<string, ConversationMessageItem>
  continuousQuestionStatus: 'default' | 'close'
  continuousQuestionList: string[]
  isAnswerResponseLoading: boolean
  createContinueQuestionsException: boolean
}

const props = defineProps<Props>()

defineEmits<{
  audioPlay: [messageItem: ConversationMessageItem]
  audioPause: []
}>()

const { scrollRef, scrollToBottom } = useScroll()

const { visible, clickBackBottom, throttleScrollContainer } = useBackBottom(scrollRef, scrollToBottom)

const isShowKnowledgeContent = ref(false)
const currentKnowledgeContentResult = ref<KnowledgeContentResultItem[]>([])

const isShowContinueQuestion = computed(() => {
  return (
    props.continuousQuestionStatus === 'default' &&
    props.messageList.size > 1 &&
    !props.isAnswerResponseLoading &&
    !props.createContinueQuestionsException
  )
})

watch(
  () => props.messageList.size,
  () => {
    clickBackBottom()
  },
)

defineExpose({
  scrollToBottom: handleScrollToBottom,
})

function handleScrollToBottom() {
  nextTick(() => {
    !visible.value && scrollToBottom()
  })
}

function handleShowKnowledgeResult(knowledgeContentResult: KnowledgeContentResultItem[]) {
  isShowKnowledgeContent.value = true
  currentKnowledgeContentResult.value = knowledgeContentResult
}
</script>

<template>
  <main ref="scrollRef" class="h-full overflow-y-auto overflow-x-hidden px-5" @scroll="throttleScrollContainer">
    <div>
      <MessageItem
        v-for="[key, messageItem] in messageList"
        :key="key"
        :role="messageItem.role"
        :message-item="messageItem"
        @audio-play="() => $emit('audioPlay', messageItem)"
        @audio-pause="() => $emit('audioPause')"
        @show-knowledge-result="handleShowKnowledgeResult(messageItem.knowledgeContentResult)"
      />
    </div>

    <div v-show="isShowContinueQuestion">
      <ContinueQuestion :continuous-question-list="continuousQuestionList" />
    </div>

    <div
      v-show="visible"
      class="flex-center hover:text-theme-color absolute bottom-5 right-5 h-6 w-6 cursor-pointer rounded-full bg-white shadow-[0_0_0_1px_#ededed]"
      @click.stop="clickBackBottom"
    >
      <i class="iconfont icon-left rotate-270 text-sm" />
    </div>

    <HitKnowledge
      v-model:is-show-drawer="isShowKnowledgeContent"
      :knowledge-content-result="currentKnowledgeContentResult!"
    />
  </main>
</template>
