<template>
    <div class="notification-center">
        <!-- 消息图标入口 -->
        <div class="layout-navbars-breadcrumb-user-icon" @click="openDrawer">
            <el-badge :value="unreadCount" :max="99" :hidden="!hasUnread">
                <el-icon title="消息通知">
                    <ele-Bell />
                </el-icon>
            </el-badge>
        </div>

        <!-- 消息通知抽屉 -->
        <el-drawer
            v-model="state.drawerVisible"
            title="消息通知中心"
            direction="rtl"
            size="450px"
            :destroy-on-close="false"
        >
            <!-- 消息类型标签页 -->
            <el-tabs v-model="state.activeTab" @tab-change="handleTabChange">
                <el-tab-pane label="全部" name="all">
                    <template #label>
                        <span>全部</span>
                        <el-badge :value="unreadCount" :max="99" :hidden="!hasUnread" class="tab-badge" />
                    </template>
                </el-tab-pane>
                <el-tab-pane label="系统通知" name="1">
                    <template #label>
                        <span>系统通知</span>
                        <el-badge :value="unreadCountByType[1]" :max="99" :hidden="!unreadCountByType[1]" class="tab-badge" />
                    </template>
                </el-tab-pane>
                <el-tab-pane label="站内信" name="2">
                    <template #label>
                        <span>站内信</span>
                        <el-badge :value="unreadCountByType[2]" :max="99" :hidden="!unreadCountByType[2]" class="tab-badge" />
                    </template>
                </el-tab-pane>
                <el-tab-pane label="待办事项" name="3">
                    <template #label>
                        <span>待办事项</span>
                        <el-badge :value="unreadCountByType[3]" :max="99" :hidden="!unreadCountByType[3]" class="tab-badge" />
                    </template>
                </el-tab-pane>
                <el-tab-pane label="公告" name="4">
                    <template #label>
                        <span>公告</span>
                        <el-badge :value="unreadCountByType[4]" :max="99" :hidden="!unreadCountByType[4]" class="tab-badge" />
                    </template>
                </el-tab-pane>
            </el-tabs>

            <!-- 操作栏 -->
            <div class="action-bar">
                <el-button type="primary" link @click="markAllRead" :disabled="!hasCurrentUnread">
                    <el-icon><ele-Check /></el-icon>
                    全部已读
                </el-button>
                <el-button type="danger" link @click="deleteSelected" :disabled="state.selectedIds.length === 0">
                    <el-icon><ele-Delete /></el-icon>
                    删除选中 ({{ state.selectedIds.length }})
                </el-button>
            </div>

            <!-- 消息列表 -->
            <div class="message-list" v-loading="loading">
                <template v-if="messageList.length > 0">
                    <el-checkbox-group v-model="state.selectedIds">
                        <div 
                            v-for="message in messageList" 
                            :key="message.id" 
                            class="message-item"
                            :class="{ 'is-unread': message.status === 0 }"
                            @click="handleMessageClick(message)"
                        >
                            <div class="message-checkbox" @click.stop>
                                <el-checkbox :label="message.id" />
                            </div>
                            <div class="message-content">
                                <div class="message-header">
                                    <span class="message-title">
                                        <el-tag 
                                            v-if="message.priority > 0" 
                                            :type="getPriorityType(message.priority)" 
                                            size="small"
                                            class="priority-tag"
                                        >
                                            {{ getPriorityLabel(message.priority) }}
                                        </el-tag>
                                        {{ message.title }}
                                    </span>
                                    <span class="message-time">{{ formatTime(message.createTime) }}</span>
                                </div>
                                <div class="message-body">{{ message.content }}</div>
                                <div class="message-footer">
                                    <el-tag size="small" type="info">{{ getTypeLabel(message.type) }}</el-tag>
                                    <span class="message-sender">{{ message.senderName }}</span>
                                </div>
                            </div>
                            <div class="message-status">
                                <el-icon v-if="message.status === 0" class="unread-dot"><ele-MoreFilled /></el-icon>
                            </div>
                        </div>
                    </el-checkbox-group>
                </template>
                <el-empty v-else description="暂无消息" />
            </div>

            <!-- 分页 -->
            <div class="pagination-bar" v-if="pagination.total > pagination.pageSize">
                <el-pagination
                    v-model:current-page="pagination.pageNum"
                    v-model:page-size="pagination.pageSize"
                    :total="pagination.total"
                    :page-sizes="[10, 20, 50]"
                    layout="total, sizes, prev, pager, next"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"
                />
            </div>
        </el-drawer>

        <!-- 消息详情对话框 -->
        <el-dialog 
            v-model="state.detailVisible" 
            :title="state.currentMessage?.title || '消息详情'"
            width="500px"
        >
            <div class="message-detail" v-if="state.currentMessage">
                <div class="detail-header">
                    <el-tag :type="getTypeColor(state.currentMessage.type)">
                        {{ getTypeLabel(state.currentMessage.type) }}
                    </el-tag>
                    <el-tag 
                        v-if="state.currentMessage.priority > 0" 
                        :type="getPriorityType(state.currentMessage.priority)"
                    >
                        {{ getPriorityLabel(state.currentMessage.priority) }}
                    </el-tag>
                </div>
                <div class="detail-content">{{ state.currentMessage.content }}</div>
                <div class="detail-footer">
                    <span>发送者：{{ state.currentMessage.senderName }}</span>
                    <span>时间：{{ state.currentMessage.createTime }}</span>
                </div>
            </div>
            <template #footer>
                <el-button @click="state.detailVisible = false">关闭</el-button>
                <el-button 
                    type="danger" 
                    @click="deleteCurrentMessage"
                >删除</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="NotificationCenter">
import { reactive, computed, onMounted, onUnmounted } from 'vue';
import { storeToRefs } from 'pinia';
import { useMessageStore, getMessageTypeLabel, getPriorityLabel as getStorePriorityLabel, getPriorityColor as getStorePriorityColor, MessageItem } from '/@/stores/message';
import { ElMessage, ElMessageBox } from 'element-plus';
import u from '/@/utils/u';

const messageStore = useMessageStore();
const { unreadCount, unreadCountByType, messageList, pagination, loading } = storeToRefs(messageStore);

const state = reactive({
    drawerVisible: false,
    detailVisible: false,
    activeTab: 'all',
    selectedIds: [] as number[],
    currentMessage: null as MessageItem | null
});

// 计算属性
const hasUnread = computed(() => unreadCount.value > 0);
const hasCurrentUnread = computed(() => {
    if (state.activeTab === 'all') return hasUnread.value;
    const type = parseInt(state.activeTab);
    return (unreadCountByType.value[type] || 0) > 0;
});

// 打开抽屉
const openDrawer = async () => {
    await initIfNeeded();
    state.drawerVisible = true;
    state.selectedIds = [];
    loadMessages();
};

// 加载消息列表
const loadMessages = () => {
    const type = state.activeTab === 'all' ? undefined : parseInt(state.activeTab);
    messageStore.setCurrentType(type ?? null);
    messageStore.fetchMessageList({ type });
};

// 切换标签
const handleTabChange = () => {
    state.selectedIds = [];
    loadMessages();
};

// 分页变化
const handlePageChange = (page: number) => {
    pagination.value.pageNum = page;
    loadMessages();
};

const handleSizeChange = (size: number) => {
    pagination.value.pageSize = size;
    pagination.value.pageNum = 1;
    loadMessages();
};

// 点击消息
const handleMessageClick = (message: MessageItem) => {
    state.currentMessage = message;
    state.detailVisible = true;
    
    // 标记已读
    if (message.status === 0) {
        messageStore.markAsRead(message.id);
    }
};

// 全部标记已读
const markAllRead = async () => {
    try {
        const type = state.activeTab === 'all' ? undefined : parseInt(state.activeTab);
        await messageStore.markAllAsRead(type);
        ElMessage.success('已全部标记为已读');
    } catch (error) {
        ElMessage.error('操作失败');
    }
};

// 删除选中
const deleteSelected = async () => {
    if (state.selectedIds.length === 0) return;
    
    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${state.selectedIds.length} 条消息吗？`,
            '删除确认',
            { type: 'warning' }
        );
        
        await messageStore.batchDeleteMessage(state.selectedIds);
        state.selectedIds = [];
        ElMessage.success('删除成功');
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败');
        }
    }
};

// 删除当前消息
const deleteCurrentMessage = async () => {
    if (!state.currentMessage) return;
    
    try {
        await ElMessageBox.confirm('确定要删除这条消息吗？', '删除确认', { type: 'warning' });
        await messageStore.deleteMessage(state.currentMessage.id);
        state.detailVisible = false;
        state.currentMessage = null;
        ElMessage.success('删除成功');
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败');
        }
    }
};

// 格式化时间
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) + '小时前';
    if (diff < 604800000) return Math.floor(diff / 86400000) + '天前';
    
    return time.split(' ')[0];
};

// 获取类型标签
const getTypeLabel = (type: number) => getMessageTypeLabel(type) || '未知';
const getTypeColor = (type: number) => u.fmt.fmtDictColor(type, 'message_type');

// 获取优先级
const getPriorityLabel = (priority: number) => getStorePriorityLabel(priority) || '';
const getPriorityType = (priority: number) => getStorePriorityColor(priority) || '';

// 是否已初始化
let initialized = false;

// 延迟初始化（避免页面加载时立即请求）
const initIfNeeded = async () => {
    if (!initialized) {
        initialized = true;
        await messageStore.init();
    }
};

// 生命周期 - 不在 onMounted 时立即初始化，而是在用户点击时初始化
onMounted(() => {
    // 延迟 2 秒后初始化，避免页面加载时立即请求
    setTimeout(() => {
        initIfNeeded();
    }, 2000);
});

onUnmounted(() => {
    messageStore.cleanup();
});
</script>

<style scoped lang="scss">
.notification-center {
    .layout-navbars-breadcrumb-user-icon {
        padding: 0 10px;
        cursor: pointer;
        color: var(--next-bg-topBarColor);
        height: 50px;
        line-height: 50px;
        display: flex;
        align-items: center;

        &:hover {
            background: var(--next-color-user-hover);
        }
    }
}

.tab-badge {
    margin-left: 4px;
    
    :deep(.el-badge__content) {
        transform: scale(0.8);
    }
}

.action-bar {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
    margin-bottom: 10px;
}

.message-list {
    min-height: 300px;
    max-height: calc(100vh - 280px);
    overflow-y: auto;
}

.message-item {
    display: flex;
    align-items: flex-start;
    padding: 12px;
    border-radius: 8px;
    margin-bottom: 8px;
    cursor: pointer;
    transition: all 0.3s;
    border: 1px solid var(--el-border-color-lighter);

    &:hover {
        background: var(--el-fill-color-light);
    }

    &.is-unread {
        background: var(--el-color-primary-light-9);
        border-color: var(--el-color-primary-light-7);
        
        .message-title {
            font-weight: 600;
        }
    }

    .message-checkbox {
        margin-right: 8px;
        padding-top: 2px;
    }

    .message-content {
        flex: 1;
        min-width: 0;
    }

    .message-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 6px;
    }

    .message-title {
        font-size: 14px;
        color: var(--el-text-color-primary);
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        
        .priority-tag {
            margin-right: 4px;
        }
    }

    .message-time {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        flex-shrink: 0;
        margin-left: 8px;
    }

    .message-body {
        font-size: 13px;
        color: var(--el-text-color-regular);
        line-height: 1.5;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        margin-bottom: 6px;
    }

    .message-footer {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 12px;
        color: var(--el-text-color-secondary);
    }

    .message-status {
        width: 20px;
        display: flex;
        align-items: center;
        justify-content: center;

        .unread-dot {
            color: var(--el-color-primary);
            font-size: 8px;
        }
    }
}

.pagination-bar {
    margin-top: 16px;
    display: flex;
    justify-content: center;
}

.message-detail {
    .detail-header {
        display: flex;
        gap: 8px;
        margin-bottom: 16px;
    }

    .detail-content {
        line-height: 1.8;
        color: var(--el-text-color-primary);
        padding: 16px;
        background: var(--el-fill-color-lighter);
        border-radius: 8px;
        margin-bottom: 16px;
        min-height: 100px;
    }

    .detail-footer {
        display: flex;
        justify-content: space-between;
        font-size: 13px;
        color: var(--el-text-color-secondary);
    }
}
</style>
