<template>
    <div class="chat-message-container">
        <!-- 头部信息 -->
        <header class="chat-header">
            <div class="header-content">
                <div class="header-title">{{ chatRoom?.workcaseId || '' }} 对话详情</div>
                <div class="header-subtitle">
                    <span>客户：{{ chatRoom?.guestName || '未知' }}</span>
                    <span class="separator">　</span>
                    <span>聊天室：{{ chatRoom?.roomName || '未知' }}</span>
                </div>
            </div>
        </header>

        <!-- Tab 切换 -->
        <div class="tabs-container">
            <div class="tabs-wrapper">
                <button 
                    class="tab-button"
                    :class="{ active: activeTab === 'record' }"
                    @click="activeTab = 'record'"
                >
                    对话记录
                </button>
                <button 
                    class="tab-button"
                    :class="{ active: activeTab === 'summary' }"
                    @click="activeTab = 'summary'"
                >
                    对话纪要
                </button>
            </div>
        </div>

        <!-- 内容区域 -->
        <main class="chat-main">
            <!-- 对话记录 -->
            <div v-if="activeTab === 'record'" class="messages-container" ref="messagesContainerRef" @scroll="handleScroll">
                <!-- 加载更多提示 -->
                <div v-if="loadingMore" class="loading-more">
                    <span>加载中...</span>
                </div>
                <div v-else-if="!hasMore && messages.length > 0" class="no-more">
                    <span>没有更多消息了</span>
                </div>

                <div class="messages-list">
                    <div v-for="message in messages" :key="message.messageId" 
                         class="message-item"
                         :class="message.senderType === 'guest' ? 'message-right' : 'message-left'"
                    >
                        <!-- 客服/AI消息（左侧） -->
                        <template v-if="message.senderType !== 'guest'">
                            <div class="avatar avatar-ai">{{ getAvatarText(message) }}</div>
                            <div class="message-content">
                                <div class="message-meta">{{ message.senderName || '小电' }} {{ formatTime(message.sendTime) }}</div>
                                <div class="message-bubble message-bubble-left">
                                    {{ message.content }}
                                </div>
                            </div>
                        </template>

                        <!-- 客户消息（右侧） -->
                        <template v-else>
                            <div class="message-content">
                                <div class="message-meta message-meta-right">{{ message.senderName || '客户' }} {{ formatTime(message.sendTime) }}</div>
                                <div class="message-bubble message-bubble-right">
                                    {{ message.content }}
                                </div>
                            </div>
                            <div class="avatar avatar-guest">{{ getAvatarText(message) }}</div>
                        </template>
                    </div>

                    <!-- 空状态 -->
                    <div v-if="messages.length === 0 && !loading" class="empty-state">
                        <div class="empty-text">暂无对话记录</div>
                    </div>
                </div>
            </div>

            <!-- 对话纪要 -->
            <div v-else class="summary-container">
                <div class="summary-content">
                    <div class="summary-section">
                        <div class="summary-title">问题概述</div>
                        <div class="summary-text">
                            {{ summary.overview || '暂无概述' }}
                        </div>
                    </div>
                    <div class="summary-section">
                        <div class="summary-title">客户诉求</div>
                        <div class="summary-text">
                            {{ summary.demand || '暂无诉求' }}
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import type { ChatRoomVO, ChatRoomMessageVO } from '@/types/workcase/chatRoom'
import { workcaseChatAPI } from '@/api/workcase/workcaseChat'

interface Summary {
    overview?: string
    demand?: string
}

interface Props {
    chatRoom?: ChatRoomVO
    roomId?: string
}

const props = withDefaults(defineProps<Props>(), {
    chatRoom: undefined,
    roomId: ''
})

const activeTab = ref<'record' | 'summary'>('record')
const messages = ref<ChatRoomMessageVO[]>([])
const loading = ref(false)
const loadingMore = ref(false)
const summary = ref<Summary>({
    overview: '',
    demand: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = 20
const total = ref(0)
const hasMore = computed(() => messages.value.length < total.value)

// 滚动容器引用
const messagesContainerRef = ref<HTMLElement | null>(null)

// 计算目标 roomId
const targetRoomId = computed(() => props.roomId || props.chatRoom?.roomId || '')

// 格式化时间
const formatTime = (timeStr?: string) => {
    if (!timeStr) return ''
    try {
        const date = new Date(timeStr)
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })
    } catch {
        return timeStr
    }
}

// 获取头像文本
const getAvatarText = (message: ChatRoomMessageVO) => {
    if (message.senderType === 'guest') {
        return message.senderName?.charAt(0) || '客'
    }
    return message.senderName?.charAt(0) || '电'
}

// 加载消息数据（首次加载，获取最新消息）
const loadMessages = async () => {
    if (!targetRoomId.value) return

    loading.value = true
    currentPage.value = 1
    try {
        const res = await workcaseChatAPI.getChatMessagePage({
            filter: { roomId: targetRoomId.value },
            pageParam: { page: 1, pageSize }
        })
        
        if (res.success && res.dataList) {
            // 后端降序返回（最新在前），需要反转显示（最新在下）
            messages.value = [...res.dataList].reverse()
            total.value = res.total || 0
            
            // 滚动到底部
            await nextTick()
            scrollToBottom()
        }
    } catch (error) {
        console.error('加载消息失败:', error)
    } finally {
        loading.value = false
    }
}

// 加载更多历史消息（滚动到顶部时触发）
const loadMoreMessages = async () => {
    if (!targetRoomId.value || loadingMore.value || !hasMore.value) return

    loadingMore.value = true
    const container = messagesContainerRef.value
    const oldScrollHeight = container?.scrollHeight || 0
    
    try {
        currentPage.value++
        const res = await workcaseChatAPI.getChatMessagePage({
            filter: { roomId: targetRoomId.value },
            pageParam: { page: currentPage.value, pageSize }
        })
        
        if (res.success && res.dataList && res.dataList.length > 0) {
            // 后端降序返回，反转后插入到消息列表前面
            const olderMessages = [...res.dataList].reverse()
            messages.value = [...olderMessages, ...messages.value]
            
            // 保持滚动位置（新内容加载后保持原来的可视区域）
            await nextTick()
            if (container) {
                const newScrollHeight = container.scrollHeight
                container.scrollTop = newScrollHeight - oldScrollHeight
            }
        }
    } catch (error) {
        console.error('加载更多消息失败:', error)
        currentPage.value-- // 回退页码
    } finally {
        loadingMore.value = false
    }
}

// 滚动到底部
const scrollToBottom = () => {
    const container = messagesContainerRef.value
    if (container) {
        container.scrollTop = container.scrollHeight
    }
}

// 处理滚动事件
const handleScroll = () => {
    const container = messagesContainerRef.value
    if (!container) return
    
    // 滚动到顶部附近时加载更多（距离顶部50px以内）
    if (container.scrollTop < 50 && hasMore.value && !loadingMore.value) {
        loadMoreMessages()
    }
}

// 生成对话纪要（可以后续接入AI生成）
const generateSummary = () => {
    if (messages.value.length === 0) return
    
    // 简单提取第一条和最后一条消息作为概述
    const firstMsg = messages.value[0]
    const lastMsg = messages.value[messages.value.length - 1]
    
    summary.value = {
        overview: `客户反馈：${firstMsg.content?.substring(0, 50) || ''}`,
        demand: lastMsg.content?.substring(0, 100) || ''
    }
}

onMounted(async () => {
    await loadMessages()
    generateSummary()
})

// 监听 roomId 变化，重新加载数据
watch(targetRoomId, async (newVal) => {
    if (newVal) {
        messages.value = []
        summary.value = { overview: '', demand: '' }
        currentPage.value = 1
        total.value = 0
        await loadMessages()
        generateSummary()
    }
})
</script>
<style scoped lang="scss">
@import url("./ChatMessage.scss");

.loading-more,
.no-more {
    text-align: center;
    padding: 12px;
    color: #909399;
    font-size: 12px;
}

.loading-more span {
    display: inline-block;
    animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
    0%, 100% { opacity: 0.5; }
    50% { opacity: 1; }
}
</style>