<template>
  <div class="p-base scroll-y-auto message-history-container">
    <template v-if="!history?.length">
      <empty></empty>
    </template>
    <template v-else>
      <div v-for="(message, index) in history" :key="index" class="m-b-base message-info">
        <div class="m-b-mini message-header">
          <span class="m-r-base user-name">{{ message.sendUserName }}</span>
          <span class="message-time">{{ message.sendTime }}</span>
        </div>
        <pre class="message-info-content" @click="onContentClick" v-html="message.content"></pre>
      </div>
    </template>
  </div>
  <image-preview v-model="previewModalVisible" :url="paperPath"></image-preview>
</template>

<script setup lang="ts" name="MessageHistory">
/** 历史消息 */
import { watch, ref } from 'vue'
import useFetch from '@/hooks/useFetch'
import Empty from '@/components/common/Empty.vue'
import ImagePreview from '../ImagePreview.vue'

const props = defineProps<{ sendUserId?: number }>()

/** 图片预览 */
const previewModalVisible = ref<boolean>(false)

/** 图片路径 */
const paperPath = ref<string>('')

const { fetch: getMessageHistory, result: history } = useFetch('getMessageHistory')

watch(
  () => props.sendUserId,
  () => {
    if (props.sendUserId) {
      getMessageHistory({ sendUserId: props.sendUserId })
    }
  },
  { immediate: true }
)

const onContentClick = (e: Event) => {
  const target = e.target as HTMLButtonElement
  const path = target.getAttribute('data-path')
  if (path) {
    previewModalVisible.value = true
    paperPath.value = path
  }
}
</script>

<style scoped lang="scss">
.message-history-container {
  max-height: 400px;
  border-top: $OnePixelLine;
  border-radius: 0 0 6px 6px;
  background-color: $color--white;
  .message-info {
    .message-header {
      color: $color--primary;
    }
    .message-info-content {
      white-space: pre-wrap;
    }
  }
}
</style>
