<!-- 通知中心页面 -->

<template>
    <div class="notification-container">
        <div class="notification-header">
            <h2>通知中心</h2>
            <div class="header-actions">
                <!-- <el-button type="primary" size="small" @click="act_markAllRead">
                    全部已读
                </el-button>
                <el-button type="danger" size="small" @click="act_clearAll">
                    清空通知
                </el-button> -->
            </div>
        </div>

        <div class="notification-content">
            <el-empty v-if="!g_dataList.length" description="暂无通知" />
            <template v-else>
                <div v-for="item in g_dataList" :key="item.id" class="notification-item"
                    :class="{ 'is-read': item.isRead }">
                    <div class="notification-item-header">
                        <div class="left">
                            <el-tag :type="item.typeClass" size="small">{{ item.typeText }}</el-tag>
                            <span class="title">{{ item.title }}</span>
                        </div>
                        <div class="right">
                            <span class="time">{{ item.time }}</span>

                            <el-button type="text" @click="act_deleteNotification(item.id)">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </el-button>
                        </div>
                    </div>
                    <div class="notification-item-content">
                        {{ item.content }}
                    </div>
                    <div class="notification-item-footer" v-if="!item.isRead">
                        <!-- <el-button type="primary" link @click="act_markRead(item.id)">标记已读</el-button> -->
                    </div>
                </div>
            </template>
        </div>

        <div class="notification-footer">
            <el-pagination v-model:current-page="g_currentPage" v-model:page-size="g_pageSize" :total="g_total"
                :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next"
                @size-change="act_handleSizeChange" @current-change="act_handleCurrentChange" />
        </div>
    </div>
</template>

<script setup>
/************************************************
 *                   引入文件                   *
 ************************************************/
import { ref, onMounted } from 'vue'
import { Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from "@/store/index";
import { getNoticeByUserId, getNotice } from '@/http/api/pages/Notice/index'

/************************************************
 * 全局变量
 *
 * 格式: g_ + 事件名     例如: getAppDataList
 ************************************************/
const g_userStore = useUserStore();

// 分页相关
const g_currentPage = ref(1)
const g_pageSize = ref(10)
const g_total = ref(0)

// 模拟数据
const g_dataList = ref([])

// 通知类型映射
const g_noticeTypeMap = {
    1: { text: '系统通知', type: '' },
    2: { text: '活动通知', type: 'success' },
    3: { text: '安全提醒', type: 'danger' }
}

// 通知状态映射
const g_noticeStateMap = {
    1: { text: '未读', isRead: false },
    2: { text: '已读', isRead: true }
}

/************************************************
 * 生命周期函数
 ************************************************/
// 挂载完成
onMounted(async () => {
    await get_notificationList()
})

/************************************************
* 事件处理
*
* 格式: act_ + 事件名     例如: getAppDataList
************************************************/

// 获取通知列表
const get_notificationList = async () => {
    try {
        const res = await getNoticeByUserId(g_userStore.userInfo.user.id)
        if (res.code === 200) {
            // 处理数据，添加类型和状态的映射
            g_dataList.value = res.data.map(item => ({
                ...item,
                typeText: g_noticeTypeMap[item.type]?.text || '未知类型',
                typeClass: g_noticeTypeMap[item.type]?.type || 'info',
                isRead: g_noticeStateMap[item.state]?.isRead || false,
                time: formatTime(item.createTime) // 假设后端返回createTime字段
            }))
            g_total.value = res.data.length
        } else {
            ElMessage.error(res.msg || '获取通知列表失败')
        }
    } catch (error) {
        console.error('获取通知列表失败:', error)
        ElMessage.error('获取通知列表失败')
    }
}

// 格式化时间
const formatTime = (time) => {
    if (!time) return ''
    const date = new Date(time)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取通知类型对应的样式
const getNotificationType = (type) => {
    return g_noticeTypeMap[type]?.type || 'info'
}

// 标记单条通知为已读
const act_markRead = async (id) => {
    try {
        // TODO: 调用API标记已读
        const notification = g_dataList.value.find(item => item.id === id)
        if (notification) {
            notification.state = 2
            notification.isRead = true
        }
        ElMessage.success('已标记为已读')
    } catch (error) {
        console.error('标记已读失败:', error)
        ElMessage.error('标记已读失败')
    }
}

// 标记所有通知为已读
const act_markAllRead = async () => {
    try {
        // TODO: 调用API标记所有已读
        // await api.markAllNotificationsRead()

        // 模拟API调用成功
        g_dataList.value.forEach(item => {
            item.isRead = true
        })
        ElMessage.success('已全部标记为已读')
    } catch (error) {
        console.error('标记全部已读失败:', error)
        ElMessage.error('标记全部已读失败')
    }
}

// 删除单条通知
const act_deleteNotification = async (id) => {
    try {
        await ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // TODO: 调用API删除通知
        // await api.deleteNotification(id)

        // 模拟API调用成功
        g_dataList.value = g_dataList.value.filter(item => item.id !== id)
        g_total.value--
        ElMessage.success('删除成功')
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除通知失败:', error)
            ElMessage.error('删除通知失败')
        }
    }
}

// 清空所有通知
const act_clearAll = async () => {
    try {
        await ElMessageBox.confirm('确定要清空所有通知吗？此操作不可恢复！', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // TODO: 调用API清空通知
        // await api.clearAllNotifications()

        // 模拟API调用成功
        g_dataList.value = []
        g_total.value = 0
        ElMessage.success('已清空所有通知')
    } catch (error) {
        if (error !== 'cancel') {
            console.error('清空通知失败:', error)
            ElMessage.error('清空通知失败')
        }
    }
}

// 分页大小改变
const act_handleSizeChange = async (size) => {
    g_pageSize.value = size
    g_currentPage.value = 1
    await get_notificationList()
}

// 页码改变
const act_handleCurrentChange = async (page) => {
    g_currentPage.value = page
    await get_notificationList()
}
</script>

<style scoped>
.notification-container {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 24px;
    min-height: calc(100vh - 48px);
    display: flex;
    flex-direction: column;
    width: 100%;
    margin: 0;
}

.notification-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #eee;
}

.notification-header h2 {
    margin: 0;
    font-size: 20px;
    color: #2c3e50;
}

.header-actions {
    display: flex;
    gap: 12px;
}

.notification-content {
    flex: 1;
    overflow-y: auto;
    width: 100%;
}

.notification-item {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;
    transition: all 0.3s ease;
    width: 100%;
    position: relative;
}

.notification-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.notification-item.is-read {
    background-color: #fff;
    border: 1px solid #eee;
}

.notification-item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.notification-item-header .left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.notification-item-header .right {
    display: flex;
    align-items: center;
    gap: 16px;
}

.title {
    font-size: 16px;
    font-weight: 500;
    color: #2c3e50;
}

.time {
    color: #909399;
    font-size: 14px;
}

.notification-item-content {
    color: #606266;
    line-height: 1.6;
    margin: 12px 0;
    padding-bottom: 32px;
}

.notification-item-footer {
    display: flex;
    justify-content: flex-end;
    position: absolute;
    bottom: 16px;
    right: 56px;
}

.notification-footer {
    margin-top: 24px;
    display: flex;
    justify-content: center;
}

:deep(.el-pagination) {
    justify-content: center;
}

:deep(.el-tag) {
    text-transform: none;
}
</style>