<template>
  <div id="sender" ref="senderRef"></div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeMount } from 'vue'
import XSender, { Options } from 'x-sender'
import 'x-sender/style'

const props = defineProps({
  nodeList: {
    type: Array,
    default: () => []
  }
})

const senderRef = ref<HTMLElement | null>(null)
let sender: XSender | null = null
const options: Options = {
  placeholder: '请输入内容'
}

watch(
  () => props.nodeList,
  () => {
    sender.reset({
      clearHistory: true,
      chatNode: [props.nodeList]
    })
  },
  {
    deep: true
  }
)

const chatNode = [[]]

const createSender = () => {
  if (sender) {
    sender.destroy()
  }
  sender = new XSender(senderRef.value!, options)
  sender.reset({
    clearHistory: true,
    chatNode: [props.nodeList]
  })
}

const getContext = () => {
  const text = sender.getText()
  return text
}

onMounted(() => {
  createSender()
})

onBeforeMount(() => {
  if (sender) {
    sender.destroy()
    sender = null
  }
})

defineExpose({
  getContext
})
</script>
<style lang="less" scoped>
#sender {
  :deep(.chat-scroll) {
    font-size: 1.4rem;
    padding: 0;
    .chat-rich-text {
      padding: 0;
    }
  }
}
</style>
