<template>
    <div class="notification-center-wrapper">
        <div class="layout-padding notification-center-page">
            <div class="layout-padding-auto layout-padding-view">
                <div class="page-title">{{ t('notificationCenter.title') }}</div>

                <div class="notification-header">
                    <div class="header-left">
                        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
                            <el-tab-pane :label="t('notificationCenter.tabs.all')" name="all" />
                            <el-tab-pane :label="t('notificationCenter.tabs.unread')" name="unread" />
                            <el-tab-pane :label="t('notificationCenter.tabs.read')" name="read" />
                        </el-tabs>
                        <el-button type="primary" plain @click="handleMarkAllAsRead" class="mark-all-btn">
                            {{ t('notificationCenter.actions.markAllAsRead') }}
                        </el-button>
                    </div>
                    <div class="header-right">
                        <el-input v-model="searchKeyword" :placeholder="t('notificationCenter.searchPlaceholder')"
                            clearable @keyup.enter="handleSearch" class="search-input">
                            <template #append>
                                <el-button type="primary" @click="handleSearch">
                                    {{ t('notificationCenter.actions.query') }}
                                </el-button>
                            </template>
                        </el-input>
                    </div>
                </div>

                <div class="notification-list" v-loading="tableLoading">
                    <div v-for="notification in pagedNotifications" :key="notification.id" class="notification-card"
                        :class="{ 'is-read': notification.isRead }" @click="handleNotificationClick(notification)">
                        <div class="notification-dot" v-if="!notification.isRead"></div>
                        <div class="notification-content">
                            <div class="notification-message">
                                <span class="notification-type">{{ notification.type }}</span>
                                <span class="notification-text">{{ notification.message }}</span>
                            </div>
                            <div class="notification-time">{{ notification.createTime }}</div>
                        </div>
                    </div>
                    <el-empty v-if="!tableLoading && pagedNotifications.length === 0"
                        :description="t('notificationCenter.noDataText') || '暂无数据'" />
                </div>

                <div class="notification-footer" v-if="totalCount > 0">
                    <div class="total-text">
                        {{ t('notificationCenter.pagination.total', { total: totalCount }) }}
                    </div>
                    <el-pagination background :current-page="pagination.page" :page-size="pagination.pageSize"
                        :total="totalCount" layout="prev, pager, next, jumper, ->, sizes"
                        :page-sizes="[10, 20, 50, 100]" @current-change="handlePageChange"
                        @size-change="handleSizeChange" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '/@/hooks/message';
import { fetchUserMessageList, readUserMessage } from '/@/api/admin/message';

const { t } = useI18n();
const message = useMessage();

const activeTab = ref<'all' | 'unread' | 'read'>('all');
const searchKeyword = ref('');
const tableLoading = ref(false);
const totalCount = ref(0);

interface NotificationItem {
    id: number | string;
    type: string;
    message: string;
    createTime: string;
    isRead: boolean;
    category?: string;
}

const notifications = ref<NotificationItem[]>([]);

const pagination = reactive({
    page: 1,
    pageSize: 20,
});

const filteredNotifications = computed(() => {
    let result = notifications.value;

    // 根据标签页过滤
    if (activeTab.value === 'unread') {
        result = result.filter((item) => !item.isRead);
    } else if (activeTab.value === 'read') {
        result = result.filter((item) => item.isRead);
    }

    // 根据搜索关键词过滤
    const keyword = searchKeyword.value.trim();
    if (keyword) {
        result = result.filter((item) => item.message.includes(keyword));
    }

    return result;
});

const pagedNotifications = computed(() => {
    const start = (pagination.page - 1) * pagination.pageSize;
    return filteredNotifications.value.slice(start, start + pagination.pageSize);
});

// 监听过滤后的通知列表，更新总数
watch(
    filteredNotifications,
    (val) => {
        totalCount.value = val.length;
        // 如果当前页超出范围，重置到第一页
        const maxPage = Math.max(1, Math.ceil((val.length || 1) / pagination.pageSize));
        if (pagination.page > maxPage) {
            pagination.page = maxPage;
        }
    },
    { immediate: true }
);

const getNotificationType = (category?: string): string => {
    if (!category) return '【提醒】';
    if (category.includes('审批') || category.includes('approval')) return '【审批】';
    if (category.includes('提醒') || category.includes('reminder')) return '【提醒】';
    return '【提醒】';
};

const normalizeNotification = (item: any): NotificationItem => {
    return {
        id: item.id || item.messageId,
        type: getNotificationType(item.category || item.type),
        message: item.message || item.content || item.title || '--',
        createTime: item.createTime || item.sendTime || '--',
        isRead: item.isRead === true || item.readFlag === '1' || item.readFlag === 1,
        category: item.category || item.type,
    };
};

const fetchNotificationList = async () => {
    tableLoading.value = true;
    try {
        const params: any = {
            page: pagination.page,
            size: pagination.pageSize,
        };

        if (activeTab.value === 'unread') {
            params.isRead = false;
        } else if (activeTab.value === 'read') {
            params.isRead = true;
        }

        if (searchKeyword.value.trim()) {
            params.keyword = searchKeyword.value.trim();
        }

        const res = await fetchUserMessageList(params);
        const records = (res as any)?.records ?? (res as any)?.data?.records ?? (res as any)?.data ?? [];

        notifications.value = Array.isArray(records) ? records.map(normalizeNotification) : [];
        // totalCount 会在 filteredNotifications 计算属性中更新
    } catch (error: any) {
        message.error(error?.msg || error?.message || t('common.operateFail') || '获取通知列表失败');
    } finally {
        tableLoading.value = false;
    }
};

const handleTabChange = () => {
    pagination.page = 1;
    fetchNotificationList();
};

const handleSearch = () => {
    pagination.page = 1;
    fetchNotificationList();
};

const handlePageChange = (page: number) => {
    pagination.page = page;
    fetchNotificationList();
};

const handleSizeChange = (size: number) => {
    pagination.pageSize = size;
    pagination.page = 1;
    fetchNotificationList();
};

const handleNotificationClick = async (notification: NotificationItem) => {
    if (!notification.isRead) {
        try {
            await readUserMessage({ id: notification.id });
            notification.isRead = true;
            message.success(t('notificationCenter.messages.markedAsRead') || '已标记为已读');
        } catch (error: any) {
            message.error(error?.msg || error?.message || '标记失败');
        }
    }
    // TODO: 跳转到详情页面或执行相应操作
    message.info(t('notificationCenter.messages.viewDetail') || '查看详情功能待接入');
};

const handleMarkAllAsRead = async () => {
    try {
        const unreadIds = notifications.value.filter((item) => !item.isRead).map((item) => item.id);
        if (unreadIds.length === 0) {
            message.info(t('notificationCenter.messages.noUnread') || '没有未读通知');
            return;
        }

        // 批量标记为已读
        for (const id of unreadIds) {
            try {
                await readUserMessage({ id });
            } catch (error) {
                // 忽略单个失败
            }
        }

        // 更新本地状态
        notifications.value.forEach((item) => {
            if (!item.isRead) {
                item.isRead = true;
            }
        });

        message.success(t('notificationCenter.messages.allMarkedAsRead') || '全部标记为已读成功');
    } catch (error: any) {
        message.error(error?.msg || error?.message || '标记失败');
    }
};

onMounted(() => {
    fetchNotificationList();
});
</script>

<style scoped>
.notification-center-wrapper {
    width: 100%;
    height: 100%;
}

.notification-center-page {
    position: relative;
    width: 1000px;
    margin: 0 auto;
}

.page-title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 16px;
}

.notification-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16px;
    gap: 16px;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    flex: 1;
}

.header-right {
    display: flex;
    align-items: center;
}

.search-input {
    width: 320px;
    min-width: 240px;
}

.mark-all-btn {
    margin-left: 8px;
}

.notification-list {
    min-height: 400px;
}

.notification-card {
    background: #fff;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 12px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: flex-start;
    position: relative;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.notification-card:hover {
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-color: var(--el-color-primary);
}

.notification-card.is-read {
    opacity: 0.8;
}

.notification-dot {
    width: 8px;
    height: 8px;
    background-color: #f56c6c;
    border-radius: 50%;
    margin-right: 12px;
    margin-top: 6px;
    flex-shrink: 0;
}

.notification-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.notification-message {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    line-height: 1.6;
}

.notification-type {
    color: var(--el-color-primary);
    font-weight: 500;
    flex-shrink: 0;
}

.notification-text {
    color: var(--el-text-color-primary);
    flex: 1;
}

.notification-time {
    color: var(--el-text-color-secondary);
    font-size: 12px;
}

.notification-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16px;
    margin-top: 16px;
}

.total-text {
    color: var(--el-text-color-secondary);
}

:deep(.el-tabs__header) {
    margin: 0;
}

:deep(.el-tabs__item) {
    padding: 0 16px;
}
</style>
