Files
yunke/yunkes/src/views/ChatTimeline.vue
T

365 lines
9.9 KiB
Vue
Raw Normal View History

<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getMessages } from '@/api'
import type { Channel, Message } from '@/api/types'
import MessageBubble from '@/components/MessageBubble.vue'
import { channelLabel, formatTime } from '@/utils/format'
import { buildMessageSections } from '@/utils/messageFields'
/**
* Chat timeline. Reused for two conversation shapes:
* * 1:1 DM — `talkerId` set; messages filtered by `talker_id`.
* * Group — `roomId` set; messages filtered by `room_id`. Group messages
* carry per-member `sender_name` / `sender_head_url`, so each
* bubble identifies its sender (handled by MessageBubble).
* Exactly one of `talkerId` / `roomId` is normally present.
*/
const props = defineProps<{
channel: string
ownerId: string
talkerId?: string
roomId?: string
}>()
const router = useRouter()
const PAGE_SIZE = 50
const messages = ref<Message[]>([])
const loading = ref(false)
const loadingOlder = ref(false)
const errorMsg = ref<string | null>(null)
// Asc-ordered pagination: page 1 = oldest 50, last page = most recent 50.
// We land on the last page (most recent activity) and walk backwards to load
// older history. `currentPage` is the smallest page number currently loaded.
const currentPage = ref(1)
const totalPages = ref(1)
const total = ref(0)
const channelTyped = computed(() => props.channel as Channel)
/** True when this timeline is a group chat (drives the query + title). */
const isGroup = computed(() => !!props.roomId)
const hasMoreOlder = computed(() => currentPage.value > 1)
const conversationTitle = computed(() => {
if (isGroup.value) {
return `群聊记录 · ${props.roomId}`
}
return `与 ${props.talkerId} 的聊天记录`
})
const subtitle = computed(
() =>
`渠道:${channelLabel(channelTyped.value)} · 归属账号:${props.ownerId}` +
(total.value > 0 ? ` · 共 ${total.value} 条` : ''),
)
const streamRef = ref<HTMLElement | null>(null)
function scrollToBottom(): void {
nextTick(() => {
const el = streamRef.value
if (el) el.scrollTop = el.scrollHeight
})
}
/** Shared query params for both DM and group timelines. */
function queryFor(pageNum: number) {
return {
channel: channelTyped.value,
owner_account_id: props.ownerId,
talker_id: isGroup.value ? undefined : props.talkerId,
room_id: isGroup.value ? props.roomId : undefined,
page: pageNum,
page_size: PAGE_SIZE,
}
}
/**
* Fetch the last page (most recent messages) on entry. Page 1 is fetched first
* purely to learn `total` so we can compute `lastPage` — the messages API
* returns asc, so the last page holds the newest slice.
*/
async function loadInitial(): Promise<void> {
loading.value = true
errorMsg.value = null
try {
const first = await getMessages(queryFor(1))
total.value = first.total
totalPages.value = Math.max(1, Math.ceil(first.total / PAGE_SIZE))
if (totalPages.value <= 1) {
messages.value = first.items
} else {
const last = await getMessages(queryFor(totalPages.value))
messages.value = last.items
}
currentPage.value = totalPages.value
scrollToBottom()
} catch (e) {
errorMsg.value = (e as Error).message
messages.value = []
} finally {
loading.value = false
}
}
/** Prepend the next older page (currentPage - 1). No-op on page 1. */
async function loadOlder(): Promise<void> {
if (loadingOlder.value || !hasMoreOlder.value) return
loadingOlder.value = true
const prevHeight = streamRef.value?.scrollHeight ?? 0
try {
const prevPage = currentPage.value - 1
const res = await getMessages(queryFor(prevPage))
// Backend returns asc, so res.items are older than everything currently
// shown — prepend them.
messages.value = [...res.items, ...messages.value]
currentPage.value = prevPage
// Keep the user's scroll anchored near where they were.
nextTick(() => {
const el = streamRef.value
if (el) el.scrollTop = el.scrollHeight - prevHeight
})
} catch (e) {
ElMessage.error(`加载更多失败:${(e as Error).message}`)
} finally {
loadingOlder.value = false
}
}
function goBack(): void {
// Prefer history back when there's somewhere to go; else the customer list.
if (window.history.length > 1) {
router.back()
} else {
router.push({ name: 'customers' })
}
}
// All-fields drawer state for the message detail view.
const drawerOpen = ref(false)
const drawerMessage = ref<Message | null>(null)
function openDetail(m: Message): void {
drawerMessage.value = m
drawerOpen.value = true
}
const drawerSections = computed(() =>
drawerMessage.value ? buildMessageSections(drawerMessage.value) : [],
)
const drawerTitle = computed(() => {
const m = drawerMessage.value
if (!m) return '消息详情'
const when = m.timestamp ? formatTime(m.timestamp) : ''
return `消息详情${when ? ` · ${when}` : ''}`
})
// Reload when the route params change (navigating between conversations).
watch(
() => [props.channel, props.ownerId, props.talkerId, props.roomId] as const,
() => {
loadInitial()
},
)
onMounted(loadInitial)
</script>
<template>
<div class="yk-chat">
<div class="yk-chat__header">
<div>
<div style="display: flex; align-items: center; gap: 8px">
<el-button text size="small" @click="goBack">
<el-icon><ArrowLeft /></el-icon>
返回
</el-button>
<h2 class="yk-chat__title">{{ conversationTitle }}</h2>
</div>
<div class="yk-chat__sub">{{ subtitle }}</div>
</div>
</div>
<el-alert
v-if="errorMsg"
:title="`聊天记录加载失败:${errorMsg}`"
type="error"
show-icon
:closable="false"
style="margin-bottom: 0"
/>
<div v-loading="loading" class="yk-chat__stream" ref="streamRef">
<div class="yk-chat__load">
<el-button
v-if="hasMoreOlder"
size="small"
plain
:loading="loadingOlder"
@click="loadOlder"
>
加载更多 / 上一页
</el-button>
<span v-else-if="!loading && messages.length > 0" class="yk-chat__end">
—— 已加载全部历史 ——
</span>
</div>
<template v-if="messages.length === 0 && !loading">
<div class="yk-empty">暂无聊天记录</div>
</template>
<MessageBubble
v-for="m in messages"
:key="m.msg_id"
:message="m"
@open-detail="openDetail"
/>
</div>
<!-- All-fields drawer for the clicked message -->
<el-drawer
v-model="drawerOpen"
:title="drawerTitle"
direction="rtl"
size="560px"
>
<template v-if="drawerMessage">
<div class="yk-drawer__topmeta">
<el-tag size="small" effect="plain">
{{ channelLabel(channelTyped) }}
</el-tag>
<el-tag
v-if="drawerMessage.type"
size="small"
type="info"
effect="plain"
>
{{ drawerMessage.type }}
<template v-if="drawerMessage.type_raw != null">
({{ drawerMessage.type_raw }})
</template>
</el-tag>
<el-tag
v-if="drawerMessage.is_send != null"
size="small"
:type="drawerMessage.is_send ? 'success' : 'warning'"
effect="plain"
>
{{ drawerMessage.is_send ? '发出' : '接收' }}
</el-tag>
</div>
<div
v-for="section in drawerSections"
:key="section.title"
class="yk-drawer__section"
>
<el-divider content-position="left">{{ section.title }}</el-divider>
<dl class="yk-drawer__kv">
<div
v-for="f in section.fields"
:key="f.key"
class="yk-drawer__kv-item"
>
<dt>{{ f.label }}</dt>
<dd v-if="f.render === 'image'" class="yk-drawer__img">
<el-image
:src="String(f.value)"
:preview-src-list="[String(f.value)]"
fit="cover"
hide-on-click-modal
/>
</dd>
<dd v-else-if="f.render === 'empty'" class="yk-drawer__empty">—</dd>
<dd v-else-if="f.render === 'object'" class="yk-drawer__pre">
<pre>{{ f.text }}</pre>
</dd>
<dd v-else>{{ f.text }}</dd>
</div>
</dl>
</div>
</template>
</el-drawer>
</div>
</template>
<style scoped>
/* Make the stream its own scroll region so scrollToBottom + load-older scroll
* anchoring target the right element. Height reserves space for the app
* header + chat header + main padding. */
.yk-chat__stream {
max-height: calc(100vh - var(--yk-header-height) - 140px);
overflow-y: auto;
}
.yk-drawer__topmeta {
display: flex;
gap: 6px;
flex-wrap: wrap;
margin-bottom: 12px;
}
.yk-drawer__kv {
margin: 0 0 8px;
}
.yk-drawer__kv-item {
display: grid;
grid-template-columns: 110px 1fr;
gap: 8px 12px;
padding: 3px 0;
}
.yk-drawer__kv dt {
color: #909399;
font-size: 13px;
word-break: break-all;
}
.yk-drawer__kv dd {
margin: 0;
font-size: 13px;
color: #303133;
word-break: break-all;
min-width: 0;
}
.yk-drawer__img :deep(.el-image) {
width: 64px;
height: 64px;
border-radius: 4px;
border: 1px solid var(--el-border-color-light, #e4e7ed);
}
.yk-drawer__empty {
color: #c0c4cc;
}
.yk-drawer__pre {
margin: 0;
min-width: 0;
}
.yk-drawer__pre pre {
margin: 0;
padding: 8px;
background: var(--el-fill-color-light, #f5f7fa);
border-radius: 4px;
font-size: 12px;
color: #303133;
white-space: pre-wrap;
word-break: break-all;
max-height: 240px;
overflow: auto;
}
</style>