<template>
    <div class="chat-room-main">
        <!-- 聊天室头部 -->
        <header class="chat-header">
            <slot name="header">
                <div class="header-default">
                    <h3>{{ roomName }}</h3>
                </div>
            </slot>
        </header>

        <!-- 消息容器 -->
        <div ref="messagesRef" class="messages-container" @scroll="handleScroll">
            <!-- 加载更多提示 -->
            <div v-if="loadingMore" class="loading-more">加载中...</div>
            <div v-else-if="!hasMore" class="loading-more">没有更多消息了</div>

            <!-- 聊天消息列表 -->
            <div class="messages-list">
                <div
                    v-for="message in messages"
                    :key="message.messageId"
                    class="message-row"
                    :class="getMessageClass(message)"
                >
                    <!-- 系统消息（居中显示） -->
                    <template v-if="message.senderType === 'system'">
                        <div class="system-message-container">
                            <!-- 评分消息卡片 -->
                            <template v-if="message.messageType === 'comment'">
                                <CommentMessageCard
                                    :room-id="roomId"
                                    :can-comment="canComment"
                                    :initial-rating="commentLevel"
                                    @submit="handleCommentSubmit"
                                />
                            </template>
                            <!-- 其他系统消息 -->
                            <template v-else>
                                <div class="system-message-text">{{ message.content }}</div>
                            </template>
                            <div class="message-time">{{ formatTime(message.sendTime) }}</div>
                        </div>
                    </template>

                    <!-- 普通用户/客服消息 -->
                    <template v-else>
                        <div>
                            <!-- 头像 -->
                            <div class="message-avatar">
                                <img v-if="message.senderAvatar" :src="FILE_DOWNLOAD_URL + message.senderAvatar" />
                                <span v-else class="avatar-text">{{ message.senderName?.charAt(0) || '?' }}</span>
                            </div>
                            <div class="sender-name">{{ message.senderName || '未知用户' }}</div>
                        </div>

                        <!-- 消息内容 -->
                        <div class="message-content-wrapper">
                            <!-- 会议消息卡片 -->
                            <template v-if="message.messageType === 'meet'">
                                <MeetingCard :meetingId="getMeetingId(message.contentExtra)" @join="handleJoinMeeting" />
                                <div class="message-time">{{ formatTime(message.sendTime) }}</div>
                            </template>

                            <!-- 普通消息气泡 -->
                            <template v-else>
                                <div class="message-bubble">
                                    <div
                                        class="message-text"
                                        v-html="renderMarkdown(message.content || '')"
                                    ></div>

                                    <!-- 文件列表 -->
                                    <div v-if="message.files && message.files.length > 0" class="message-files">
                                        <div
                                            v-for="file in message.files"
                                            :key="file"
                                            class="file-item"
                                            @click="$emit('download-file', file)"
                                        >
                                            <div class="file-icon">
                                                <FileText :size="16" />
                                            </div>
                                            <div class="file-info">
                                                <div class="file-name">附件</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="message-time">{{ formatTime(message.sendTime) }}</div>
                            </template>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <!-- 输入区域 -->
        <footer class="input-area">
            <!-- 操作按钮区域 -->
            <div class="action-buttons">
                <!-- 发起会议按钮 -->
                <button
                    class="action-btn"
                    :disabled="meetingLoading"
                    @click="handleStartMeeting"
                >
                    <Video :size="18" />
                    发起会议
                </button>

                <!-- 额外的操作按钮插槽 -->
                <slot name="action-area"></slot>
            </div>

            <!-- 输入框 -->
            <div class="input-wrapper">
                <div class="input-card">
                    <div class="input-row">
                        <textarea
                            ref="textareaRef"
                            v-model="inputText"
                            @input="adjustHeight"
                            @keydown="handleKeyDown"
                            placeholder="输入消息..."
                            class="chat-textarea"
                        />
                    </div>
                    <div class="toolbar-row">
                        <div class="toolbar-left">
                            <button class="tool-btn" @click="selectFiles" title="上传文件">
                                <Paperclip :size="18" />
                            </button>
                            <input
                                ref="fileInputRef"
                                type="file"
                                multiple
                                style="display: none"
                                @change="handleFileSelect"
                            />
                        </div>
                        <button
                            class="send-btn"
                            :class="{ active: inputText.trim() }"
                            :disabled="!inputText.trim()"
                            @click="sendMessage"
                        >
                            <Send :size="18" />
                            发送
                        </button>
                    </div>
                </div>
            </div>
        </footer>

        <!-- 创建会议对话框 -->
        <MeetingCreate
            v-model="showMeetingCreate"
            :room-id="roomId"
            :workcase-id="workcaseId || ''"
            @success="handleMeetingCreated"
        />
    </div>
</template>

<script setup lang="ts">
import { ref, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { FileText, Video, Paperclip, Send } from 'lucide-vue-next'
import MeetingCreate from '../MeetingCreate/MeetingCreate.vue'
import MeetingCard from '../MeetingCard/MeetingCard.vue'
import CommentMessageCard from './CommentMessageCard/CommentMessageCard.vue'
import type { ChatRoomMessageVO, VideoMeetingVO } from '@/types/workcase'
import { workcaseChatAPI } from '@/api/workcase'
import { ElMessage } from 'element-plus'
import { FILE_DOWNLOAD_URL } from '@/config'
const router = useRouter()

interface Props {
    messages: ChatRoomMessageVO[]
    currentUserId: string
    roomId: string
    roomName?: string
    workcaseId?: string
    commentLevel?: number
    hasMore?: boolean
    loadingMore?: boolean
    guestId?: string  // 聊天室访客ID，用于判断评价权限
}

const props = withDefaults(defineProps<Props>(), {
    roomName: '聊天室',
    hasMore: true,
    loadingMore: false,
    guestId: ''
})


// 计算当前用户是否可以评价（只有访客可以评价）
const canComment = computed(() => {
    return props.currentUserId === props.guestId
})

const emit = defineEmits<{
    'send-message': [content: string, files: File[]]
    'download-file': [fileId: string]
    'load-more': []
    'start-meeting': []
    'submit-comment': [rating: number]
}>()

// 会议相关状态
const meetingLoading = ref(false)
const showMeetingCreate = ref(false)

// 打开创建会议对话框或直接emit事件给父组件处理
const handleStartMeeting = () => {
    // emit事件给父组件，让父组件处理会议逻辑
    // emit('start-meeting')
    showMeetingCreate.value = true

}

// 会议创建成功回调
// 定时会议创建后不自动进入，只显示成功消息
const handleMeetingCreated = async (meetingId: string) => {
    showMeetingCreate.value = false
    // 定时会议创建成功后不自动加入，用户可以在会议开始时间前后手动加入
    // 会议消息会通过后端发送到聊天室，用户可以点击消息卡片加入
}

// 滚动到顶部加载更多
const handleScroll = (e: Event) => {
    const target = e.target as HTMLElement
    if (target.scrollTop < 50 && props.hasMore && !props.loadingMore) {
        emit('load-more')
    }
}

defineSlots<{
    header?: () => any
    'action-area'?: () => any
}>()

const inputText = ref('')
const selectedFiles = ref<File[]>([])
const messagesRef = ref<HTMLElement | null>(null)
const textareaRef = ref<HTMLTextAreaElement | null>(null)
const fileInputRef = ref<HTMLInputElement | null>(null)

// 发送消息
const sendMessage = () => {
    if (!inputText.value.trim() && selectedFiles.value.length === 0) return
    
    emit('send-message', inputText.value.trim(), selectedFiles.value)
    
    inputText.value = ''
    selectedFiles.value = []
    
    if (textareaRef.value) {
        textareaRef.value.style.height = 'auto'
    }
    
    scrollToBottom()
}

// 选择文件
const selectFiles = () => {
    fileInputRef.value?.click()
}

// 处理文件选择
const handleFileSelect = (e: Event) => {
    const files = (e.target as HTMLInputElement).files
    if (!files || files.length === 0) return
    
    selectedFiles.value = Array.from(files)
}

// 滚动到底部
const scrollToBottom = () => {
    nextTick(() => {
        if (messagesRef.value) {
            // 使用 smooth 滚动到底部
            messagesRef.value.scrollTo({
                top: messagesRef.value.scrollHeight,
                behavior: 'instant'
            })

            // 延迟再次确保滚动到底部（处理内容动态渲染的情况）
            setTimeout(() => {
                if (messagesRef.value) {
                    messagesRef.value.scrollTo({
                        top: messagesRef.value.scrollHeight,
                        behavior: 'instant'
                    })
                }
            }, 100)

            // 最后一次确保（处理图片等异步内容加载）
            setTimeout(() => {
                if (messagesRef.value) {
                    messagesRef.value.scrollTo({
                        top: messagesRef.value.scrollHeight,
                        behavior: 'instant'
                    })
                }
            }, 300)
        }
    })
}

// 自动调整输入框高度
const adjustHeight = () => {
    const el = textareaRef.value
    if (el) {
        el.style.height = 'auto'
        el.style.height = Math.min(el.scrollHeight, 150) + 'px'
    }
}

// 键盘事件
const handleKeyDown = (e: KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault()
        sendMessage()
    }
}

// 格式化时间
const formatTime = (time?: string) => {
    if (!time) return ''
    const date = new Date(time)
    const now = new Date()
    const diff = now.getTime() - date.getTime()

    if (diff < 60000) return '刚刚'
    if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
    if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'

    return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
}

// 处理从MeetingCard发出的加入会议事件
const handleJoinMeeting = async (meetingId: string) => {
    try {
        meetingLoading.value = true
        // 调用加入会议接口获取会议页面URL
        const joinRes = await workcaseChatAPI.joinVideoMeeting(meetingId)
        if (joinRes.success && joinRes.data) {
            // 检查会议状态
            const meetingData = joinRes.data
            if (meetingData.status === 'ended') {
                // 会议已结束，提示用户
                ElMessage.warning('该会议已结束')
                return
            }

            if (!meetingData.iframeUrl) {
                console.error('加入会议失败: 未获取到会议地址')
                ElMessage.error('加入会议失败：未获取到会议地址')
                return
            }

            // 使用router跳转到JitsiMeetingView页面，附加roomId参数用于返回
            const meetingUrl = meetingData.iframeUrl + `&roomId=${props.roomId}`
            router.push(meetingUrl)
        } else {
            console.error('加入会议失败:', joinRes.message)
            ElMessage.error(joinRes.message || '加入会议失败')
        }
    } catch (error) {
        console.error('加入会议失败:', error)
        ElMessage.error('加入会议失败，请稍后重试')
    } finally {
        meetingLoading.value = false
    }
}

// 获取会议数据（将contentExtra转换为VideoMeetingVO）
// 从消息extra中提取meetingId
function getMeetingId(contentExtra: Record<string, any> | undefined): string {
	if (!contentExtra || !contentExtra.meetingId) {
		console.warn('[ChatRoom] contentExtra中没有meetingId:', contentExtra)
		return ''
	}
	return contentExtra.meetingId as string
}

// 获取消息的CSS类
const getMessageClass = (message: ChatRoomMessageVO) => {
    if (message.senderType === 'system') {
        return 'is-system'
    }
    return message.senderId === props.currentUserId ? 'is-me' : 'other'
}

// 处理评分提交
const handleCommentSubmit = async (rating: number) => {
    try {
        emit('submit-comment', rating)
        ElMessage.success('感谢您的评分！')
    } catch (error) {
        console.error('提交评分失败:', error)
        ElMessage.error('提交评分失败，请稍后重试')
    }
}

// Markdown渲染函数
const renderMarkdown = (text: string): string => {
    if (!text) return ''

    // 转义HTML标签
    let html = text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')

    // 处理代码块（```语法）
    html = html.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, lang, code) => {
        return `<pre class="code-block"><code class="language-${lang || 'text'}">${code.trim()}</code></pre>`
    })

    // 处理行内代码（`语法）
    html = html.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>')

    // 处理粗体（**语法）
    html = html.replace(/\*\*([^\*]+)\*\*/g, '<strong>$1</strong>')

    // 处理斜体（*语法）
    html = html.replace(/\*([^\*]+)\*/g, '<em>$1</em>')

    // 处理链接（[text](url)语法）
    html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" class="md-link">$1</a>')

    // 处理标题（# ## ###等）
    html = html.replace(/^### (.+)$/gm, '<h3 class="md-h3">$1</h3>')
    html = html.replace(/^## (.+)$/gm, '<h2 class="md-h2">$1</h2>')
    html = html.replace(/^# (.+)$/gm, '<h1 class="md-h1">$1</h1>')

    // 处理无序列表（- 或 * 开头）
    html = html.replace(/^[*-] (.+)$/gm, '<li class="md-li">$1</li>')
    html = html.replace(/(<li class="md-li">.*<\/li>)/s, '<ul class="md-ul">$1</ul>')

    // 处理有序列表（数字. 开头）
    html = html.replace(/^\d+\. (.+)$/gm, '<li class="md-li">$1</li>')

    // 处理换行
    html = html.replace(/\n/g, '<br>')

    return html
}

// 暴露方法给父组件
defineExpose({
    scrollToBottom,
    handleStartMeeting
})
</script>

<style scoped lang="scss">
@import url("./ChatRoom.scss");
</style>