<template>
    <div v-if="visible" class="dialog-overlay" @click.self="close">
        <div class="dialog-content">
            <!-- 右上角：一键已读 + 静音按钮 + 未读徽标 -->
            <div class="mark-all">

                <button v-if="unreadCount > 0" class="mark-all-btn" @click.stop="markAllSeen" title="一键已读">一键已读</button>
                <button class="mark-all-btn2" @click.stop="delAllSeen" title="删除已读">删除已读</button>

                <button class="mute-btn" @click.stop="toggleMute" :title="muted ? '取消静音' : '静音'">
                    <span v-if="muted">🔕</span>
                    <span v-else>🔔</span>
                </button>
            </div>
            <span v-if="unreadCount > 0" class="unread-badge">{{ unreadCount }}</span>

            <h3 style="display: flex;" class="text-lg font-bold mb-4 ">
                <img style="margin: 0 2px;" src="@/assets/video/chatMes.png" />
                <div>新消息提醒</div>
            </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>
                        <span class="sep">·</span>
                        <span class="device">{{ item.time || '未知时间' }}</span>
                    </div>

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

            </el-scrollbar>

            <!-- 可选：自定义提示音（静音时也会被静音） -->
            <audio v-if="soundSrc" ref="audioRef" :src="soundSrc" preload="auto" :muted="muted"></audio>
        </div>
    </div>
</template>

<script setup>
import { defineProps, defineEmits, ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { updatelast, deleteLast } from '@/api/ios'
const deleting = ref(false) // 防抖：删除过程中禁用按钮（可选）

const props = defineProps({
    visible: Boolean,
    messages: { type: Array, required: true, default: () => [] },
    reminderColor: { type: String, default: 'var(--el-color-warning-light-5, #ffe58f)' },
    seenColor: { type: String, default: 'var(--el-fill-color-light, #f2f3f5)' },
    soundSrc: { type: String, default: '' }
})

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

// —— 静音 —— //
const muted = ref(false)
function toggleMute() { muted.value = !muted.value }

// 过滤 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 ?? '',
                time: m?.time ?? m?.timestamp ?? '',
                text: m?.text ?? m?.content ?? '',
                // 统一转成 0/1，兼容旧的 seen/read 布尔
                status: Number(
                    m?.status ?? ((m?.seen === true || m?.read === true) ? 1 : 0)
                )
            })
        })
    return res
})

// —— 基于 status 判断 —— //
function isSeen(item) {
    // 优先读 item.raw.status，其次读规范化的 item.status
    return Number(item?.raw?.status ?? item?.status ?? 0) === 1
}

function markSeen(item) {
    if (!isSeen(item)) {
        // 标记为已读
        item.raw.status = 1
        try { updatelast(item.raw) } catch (_) { }
        emit('seen', { index: item.origIndex, message: item.raw })
    }
}

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

// —— 未读数量（status === 0）—— //
const unreadCount = computed(() =>
    normalizedMessages.value.reduce((acc, it) => acc + (isSeen(it) ? 0 : 1), 0)
)

// —— 一键已读：把所有 status=0 的设为 1 —— //
async function markAllSeen() {
    let changed = 0
    for (const it of normalizedMessages.value) {
        if (!isSeen(it)) {
            it.raw.status = 1
            try { await updatelast(it.raw) } catch (_) { }
            emit('seen', { index: it.origIndex, message: it.raw })
            changed++
        }
    }
    if (changed > 0) ElMessage.success(`已标记 ${changed} 条为已读`)
    else ElMessage.info('没有未读可标记')
}

// —— 删除已读：把所有 status=1 的抛给父组件处理 —— //
// 子组件不直接改 props.messages，向上抛事件让父组件过滤
// —— 一键删除（删除所有 status=1）—— //
async function delAllSeen() {
    // 先拍一张快照，避免删除过程中索引变化
    const readItems = normalizedMessages.value.filter(it => isSeen(it))
    if (readItems.length === 0) {
        ElMessage.info('没有已读可删除')
        return
    }

    if (deleting.value) return
    deleting.value = true
    try {
        // 并发删除（每条把“已读的消息体”传给后端）
        const results = await Promise.allSettled(
            readItems.map(it => deleteLast(it.raw))
        )

        // 统计删除成功/失败
        const okIndexes = []
        const okMessages = []
        let ok = 0, fail = 0
        results.forEach((r, i) => {
            if (r.status === 'fulfilled') {
                ok++
                okIndexes.push(readItems[i].origIndex)
                okMessages.push(readItems[i].raw)
            } else {
                fail++
                console.warn('[deleteLast] 失败:', readItems[i].raw, r.reason)
            }
        })

        // 通知父组件把成功删除的从列表移除
        if (okIndexes.length > 0) {
            emit('delete-read', { indexes: okIndexes, messages: okMessages })
        }

        if (ok > 0) ElMessage.success(`已删除 ${ok} 条${fail ? `，失败 ${fail} 条` : ''}`)
        else ElMessage.error('删除失败')
    } finally {
        deleting.value = false
    }
}

// —— 提示音 —— //
const audioRef = ref(null)
function playNotice() {
    if (muted.value) return
    if (props.soundSrc && audioRef.value) {
        audioRef.value.currentTime = 0
        audioRef.value.play().catch(() => { })
    } else {
        try {
            const Ctx = window.AudioContext || window.webkitAudioContext
            if (!Ctx) return
            const ctx = new Ctx()
            const o = ctx.createOscillator()
            const g = ctx.createGain()
            o.type = 'sine'; o.frequency.value = 880
            o.connect(g); g.connect(ctx.destination)
            const t0 = ctx.currentTime
            g.gain.setValueAtTime(0.0001, t0)
            g.gain.exponentialRampToValueAtTime(0.12, t0 + 0.02)
            g.gain.exponentialRampToValueAtTime(0.00001, t0 + 0.28)
            o.start(t0); o.stop(t0 + 0.3)
            o.onended = () => ctx.close().catch(() => { })
        } catch (_) { }
    }
}

// 未读数增加时才提示
watch(unreadCount, (now, old) => {
    if (old !== undefined && now > old) playNotice()
})

// 点击条目 => 单条已读
function onClickMessage(item) {
    markSeen(item)
    try { ElMessage.success('已读') } catch (_) { }
}
</script>


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

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

.mark-all {
    position: absolute;
    top: 20px;
    right: 5px;

    button {
        margin-right: 8px;
    }
}

/* 一键已读按钮（靠右，位于静音按钮左侧） */
.mark-all-btn {

    /* 未读徽标(10) + 静音按钮(28+间距) 预留 */
    height: 28px;
    padding: 0 10px;
    border: none;
    background: var(--el-color-primary, #409eff);
    color: #fff;
    border-radius: 9999px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, .12);
    cursor: pointer;
    font-size: 12px;
    user-select: none;
}

.mark-all-btn2 {

    /* 未读徽标(10) + 静音按钮(28+间距) 预留 */
    height: 28px;
    padding: 0 10px;
    border: none;
    background: #ff4040;
    color: #fff;
    border-radius: 9999px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, .12);
    cursor: pointer;
    font-size: 12px;
    user-select: none;
}

.mark-all-btn:hover {
    filter: brightness(0.98);
}

/* 静音按钮 */
.mute-btn {

    width: 28px;
    height: 28px;

    border: none;
    background: var(--el-fill-color, #f5f7fa);
    border-radius: 9999px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, .12);
    cursor: pointer;
    /* display: grid; */
    place-items: center;
    line-height: 1;
    font-size: 14px;
    user-select: none;
}

.mute-btn:hover {
    filter: brightness(0.98);
}

/* 未读徽标 */
.unread-badge {
    position: absolute;
    top: -10px;
    right: -10px;
    min-width: 22px;
    height: 22px;
    padding: 0 6px;
    background: var(--el-color-danger, #f56c6c);
    color: #fff;
    font-size: 12px;
    line-height: 22px;
    text-align: center;
    border-radius: 9999px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, .12);
    user-select: none;
}

.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>