<template>
    <div v-if="visible" class="dialog-overlay" @click.self="close">
        <div class="dialog-content">
            <h3 class="text-lg font-bold mb-4">
                <img style="margin: 0 15px;" src="@/assets/video/chatMes.png" />
                新消息提醒
            </h3>

            <el-scrollbar class="chat-box">
                <div v-for="(item, idx) in normalizedMessages" :key="idx" class="msg-item">
                    <div class="meta" @click="onClickMessage(item)">
                        <span class="name">{{ item.sender || '未知用户' }}</span>
                        <span class="sep">·</span>
                        <span class="device">{{ item.device || '未知设备' }}</span>
                    </div>

                    <div class="bubble" :class="isSeen(item) ? 'seen' : 'unread'" :style="bubbleStyle(item)"
                        @click="onClickMessage(item)">
                        {{ item.text }}
                    </div>
                </div>
            </el-scrollbar>
        </div>
    </div>
</template>

<script setup>
import { defineProps, defineEmits, ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
    visible: Boolean,
    messages: {
        type: Array,
        required: true,
        default: () => []
    },
    // 可自定义颜色
    reminderColor: {
        type: String,
        // Element Plus 警告浅色（看起来像“提醒”）
        default: 'var(--el-color-warning-light-5, #ffe58f)'  // 更深一点
    },
    seenColor: {
        type: String,
        // EP 填充浅色（更“平静”的已读态）
        default: 'var(--el-fill-color-light, #f2f3f5)'
    }
})

const emit = defineEmits(['close', 'seen'])
const close = () => emit('close')

// 记录哪些消息已读（用原始索引做 key，避免过滤后索引错位）
const seenSet = ref(new Set())

// 规范化并带上原始索引，过滤掉 type === 'time'
const normalizedMessages = computed(() => {
    const res = []
        ; (props.messages || []).forEach((m, i) => {
            if (m?.type === 'time') return
            res.push({
                origIndex: i,
                raw: m,
                sender: m?.sender ?? m?.name ?? m?.user ?? m?.from ?? '',
                device: m?.device ?? m?.deviceName ?? m?.udid ?? '',
                text: m?.text ?? m?.content ?? ''
            })
        })
    return res
})

// 初始化：如果消息本身标注了 seen/read，则置为已读
watch(
    () => props.messages,
    (list) => {
        const s = new Set()
        list?.forEach((m, i) => {
            if (m && (m.seen === true || m.read === true)) s.add(i)
        })
        seenSet.value = s
    },
    { immediate: true }
)

function isSeen(item) {
    return seenSet.value.has(item.origIndex)
}

function markSeen(item) {
    if (!isSeen(item)) {
        seenSet.value.add(item.origIndex)
        // 通知父组件（可选）：你也可以在父里把 messages[item.origIndex].seen = true 持久化
        emit('seen', { index: item.origIndex, message: item.raw })
    }
}

function bubbleStyle(item) {
    return {
        backgroundColor: isSeen(item) ? props.seenColor : props.reminderColor,
        color: '#333'
    }
}

// 点击：标记已读 + 复制文本
function onClickMessage(item) {
    markSeen(item)
    fallbackCopyTextToClipboard(item.text)
}

// 兜底复制
function fallbackCopyTextToClipboard(text) {
    // const textArea = document.createElement('textarea')
    // textArea.value = text || ''
    // textArea.style.position = 'fixed'
    // textArea.style.left = '-999999px'
    // textArea.style.top = '-999999px'
    // document.body.appendChild(textArea)
    // textArea.focus()
    // textArea.select()

    try {
        // const ok = document.execCommand('copy')
        // ok ? ElMessage.success('已读') : ElMessage.error('复制失败1')
        ElMessage.success('已读')
    } catch (err) {
        // ElMessage.error('复制失败2')
    } finally {
        // document.body.removeChild(textArea)
    }
}
</script>

<style scoped>
.dialog-overlay {
    display: flex;
    justify-content: center;
    align-items: center;
}

.dialog-content {
    margin-top: 3vh;
    background: rgb(246, 246, 246);
    padding: 0 20px 20px 20px;
    border-radius: 12px;
    width: 320px;
}

.chat-box {
    display: flex;
    flex-direction: column;
    gap: 10px;
    height: 35vh;
}

/* 全部左对齐 */
.msg-item {
    align-self: flex-start;
    width: 100%;
    margin-bottom: 12px;
}

.meta {
    font-size: 12px;
    color: #666;
    margin: 2px 0 6px;
    display: flex;
    align-items: center;
    gap: 6px;
}

.meta .name {
    font-weight: 600;
    color: #333;
}

.meta .sep {
    color: #999;
}

.meta .device {
    color: #555;
}

.bubble {
    padding: 10px 14px;
    border-radius: 12px;
    max-width: 90%;
    display: inline-block;
    word-break: break-word;
}

/* 颜色通过内联样式控制（.unread/.seen 仅用于语义钩子） */
.bubble.unread {}

.bubble.seen {}
</style>