// 评论框的组件 用于评论的输入 以及 表情 图片的输入 以及 发表按钮
<script setup lang="ts">
import RichTextarea from '../RichTextarea/index.vue'
import UploadImgIcon from '../UploadImgIcon/index.vue'
import UploadEmojiIcon from '../UploadEmojiIcon/index.vue'
import { useUploadImg } from '@/hooks'
import type { IEmoji } from '@/utils/emoji/type'

interface CommentBoxProps {
  textAreaHeight?: number
  placeholder?: string
}

const { textAreaHeight = 55, placeholder = '请输入内容' } = defineProps<CommentBoxProps>()

const inputStr = defineModel<string>('inputText', { required: true })
const imgStrs = defineModel<string>('inputImg', { required: true })

const { uploadPercent, imgList, handleFileChange, handleDeleteImg } = useUploadImg(imgStrs)
const richTextareaRef = useTemplateRef<InstanceType<typeof RichTextarea>>('richTextareaRef')

const handleSelectEmoji = async (emoji: IEmoji) => {
  const textarea = richTextareaRef.value?.getTextarea()
  if (!textarea) return

  // 当选中一段文本时 这俩值是不一样
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const value = inputStr.value

  // 插入内容（你可以是 [微笑]，也可以是 😀）
  inputStr.value = value.slice(0, start) + emoji.name + value.slice(end)

  // 插入后把光标放到表情后面
  await nextTick()
  textarea.focus()
  textarea.selectionStart = textarea.selectionEnd = start + emoji.name.length
}

defineExpose({
  focus: async () => {
    await nextTick()
    richTextareaRef.value?.getTextarea()?.focus()
  },
})
</script>

<template>
  <div>
    <RichTextarea
      ref="richTextareaRef"
      v-model="inputStr"
      :imgList="imgList"
      :uploadPercent="uploadPercent"
      @deleteImg="handleDeleteImg"
      :height="textAreaHeight"
      :placeholder="placeholder"
    />
    <div class="flex justify-between items-center mt-3">
      <div class="flex items-center gap-2">
        <UploadImgIcon @fileChange="handleFileChange" />
        <UploadEmojiIcon @selectEmoji="handleSelectEmoji" />
      </div>
      <div>
        <!-- 插槽 用于插入 发表按钮 -->
        <slot name="submit" />
      </div>
    </div>
  </div>
</template>

<style scoped></style>
