<script lang="ts" setup>
const props = defineProps<Props>()

interface Props {
  streamAnswer: string
}

const isShowImagesViewer = ref(false)

function formatMarkdown(str: string) {
  return str.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>').replace(/\n/g, '<br />').split('♪')[0]
}

const initialSwipeIdx = ref(0)

function generateUniqueID(length: number = 6): string {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  const charactersLength = characters.length
  for (let i = 0; i < length; i++)
    result += characters.charAt(Math.floor(Math.random() * charactersLength))

  return result
}

const imgsUrlList = ref<string[]>([])

const classKey = ref('')

function bindImgEvent() {
  nextTick(() => {
    imgsUrlList.value = []
    const imgDomList = [...document.querySelectorAll(`.event-${classKey.value} img`) as any]
    imgDomList.forEach((img, idx) => {
      imgsUrlList.value.push(img.src)
      img.addEventListener('click', () => {
        isShowImagesViewer.value = true
        initialSwipeIdx.value = idx
      })
    })
  })
}

onMounted(() => {
  // initAnswer()
  classKey.value = generateUniqueID()
  bindImgEvent()
})
</script>

<template>
  <div class="answer-shower-wrap">
    <div class="answer-shower-content" :class="[`event-${classKey}`]" v-html="formatMarkdown(props.streamAnswer || '已停止回答')" />
    <ImagesViewer v-model:show="isShowImagesViewer" :initial-swipe="initialSwipeIdx" :imgs-url-list="imgsUrlList" />
  </div>
</template>

<style lang="scss" scoped>
:deep(.answer-shower-content) {
  img {
    display: block !important;
    width: 160px;
    height: 160px;
    object-fit: cover;
    margin: 12px 0;
  }
}
.answer-shower-wrap {
  display: flex;
  align-items: flex-end;
}
</style>
