NotificationCenter.vue 14.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
<template>
  <div v-if="visible" class="notification-center-container" :style="containerStyle" @mousedown.stop>
    <!-- Header (Draggable part) -->
    <div class="notification-header" @mousedown="onHeaderMouseDown">
      <div class="header-left">
        <span class="header-title">消息中心</span>
      </div>
      <div class="header-right">
        <span 
          v-if="notifyStore.unreadCount > 0" 
          class="ack-all-btn" 
          @click.stop="handleMarkAllAsRead"
        >
          全部已读
        </span>
        <el-icon class="close-icon" @click="close"><Close /></el-icon>
      </div>
    </div>

    <!-- Custom Filter Area -->
    <div class="filter-area">
      <div class="custom-select-wrapper" ref="filterRef">
        <div class="custom-select-trigger" @click.stop="toggleFilterDropdown">
          <span class="current-label">{{ filterLabels[currentFilter] }}</span>
          <el-icon class="arrow-icon" :class="{ 'is-open': filterDropdownVisible }">
            <ArrowDown />
          </el-icon>
        </div>

        <div v-if="filterDropdownVisible" class="custom-dropdown-menu">
          <div 
            v-for="(label, key) in filterLabels" 
            :key="key"
            class="custom-dropdown-item"
            :class="{ 'is-active': currentFilter === key }"
            @click.stop="handleSelectFilter(key)"
          >
            {{ label }}
            <el-icon v-if="currentFilter === key" class="check-icon"><Check /></el-icon>
          </div>
        </div>
      </div>
    </div>

    <!-- Message List -->
    <div class="notification-list" v-loading="loading">
      <template v-if="notifications.length > 0">
        <div v-for="item in notifications" :key="item.id" class="notification-item" :class="{ 'is-unread': item.status === 0 }" @click="handleItemClick(item)">
          <div class="item-header">
            <span class="item-title">{{ item.title }}</span>
            <div class="item-actions">
              <el-tooltip 
                :content="item.status === 0 ? '标记已读' : '设为未读'" 
                placement="top" 
                :show-after="200"
                :teleported="false"
              >
                <div class="action-icon-wrapper" style="display: flex; align-items: center;">
                  <el-icon 
                    v-if="item.status === 0" 
                    class="action-icon mark-read" 
                    @click.stop="handleMarkRead(item.id)"
                  >
                    <Check />
                  </el-icon>
                  <el-icon 
                    v-else 
                    class="action-icon mark-unread" 
                    @click.stop="handleMarkUnread(item.id)"
                  >
                    <RefreshLeft />
                  </el-icon>
                </div>
              </el-tooltip>
              <span v-if="item.status === 0" class="unread-dot"></span>
            </div>
          </div>
          <div class="item-content">
            {{ item.content }}
          </div>
          <div class="item-footer">
            <el-tooltip :content="item.createdAt" placement="top" :show-after="500">
              <span class="item-time">{{ formatTime(item.createdAt) }}</span>
            </el-tooltip>
          </div>
        </div>
        <div v-if="hasMore" class="load-more" @click="loadMore">加载更多</div>
      </template>
      <el-empty v-else description="暂无消息" :image-size="60" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Close, Check, ArrowDown, RefreshLeft, Memo, Bell, User, Warning } from '@element-plus/icons-vue'
import { useNotifyStore } from '@/stores/notify'
import { getNotificationsPage, type NotificationDTO, acknowledgeNotification, markAsUnread, acknowledgeAllNotifications } from '@/api/notify'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'

dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const router = useRouter()
const notifyStore = useNotifyStore()
const visible = ref(false)
const loading = ref(false)
const notifications = ref<NotificationDTO[]>([])
const currentFilter = ref('all')
const page = ref(0)
const size = ref(10)
const total = ref(0)
const hasMore = computed(() => notifications.value.length < total.value)

const filterDropdownVisible = ref(false)
const filterRef = ref<HTMLElement | null>(null)

const filterLabels: Record<string, string> = {
  all: '全部消息',
  unread: '未读消息'
}

// 1. 位置记忆逻辑(与 NewbieTaskDialog 保持一致风格)
const STORAGE_KEY = 'notification_center_pos'
const position = reactive<{ x: number; y: number }>({ x: 0, y: 0 })
const isDragging = ref(false)
const dragOffset = reactive({ x: 0, y: 0 })

const containerStyle = computed(() => ({
  left: `${position.x}px`,
  top: `${position.y}px`
}))

const toggle = () => {
  visible.value = !visible.value
  if (visible.value) {
    const saved = localStorage.getItem(STORAGE_KEY)

    if (saved) {
      try {
        const parsed = JSON.parse(saved) as { x?: number; y?: number }
        if (typeof parsed.x === 'number' && typeof parsed.y === 'number') {
          position.x = parsed.x
          position.y = parsed.y
        }
      } catch (e) {
        console.warn('解析消息中心位置失败,使用默认位置', e)
      }
    }

    if (!saved) {
      const sidebar = document.querySelector('.nav-rail')
      const sidebarWidth = sidebar ? sidebar.clientWidth : 54
      // 第一次打开时:位置与 NewbieTaskDialog 高度大致对齐,但底部留白更大一些
      position.x = sidebarWidth
      position.y = Math.max(0, window.innerHeight - 520)
    }

    resetAndFetch()
  }
}

const close = () => { 
  visible.value = false 
  filterDropdownVisible.value = false
}

const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'Escape' && visible.value) close()
}

const toggleFilterDropdown = () => {
  filterDropdownVisible.value = !filterDropdownVisible.value
}

const handleSelectFilter = (key: string) => {
  currentFilter.value = key
  filterDropdownVisible.value = false
  resetAndFetch()
}

const handleOutsideClick = (e: MouseEvent) => {
  if (filterRef.value && !filterRef.value.contains(e.target as Node)) {
    filterDropdownVisible.value = false
  }
}

const resetAndFetch = () => {
  page.value = 0
  notifications.value = []
  fetchNotifications()
}

const fetchNotifications = async () => {
  if (loading.value) return
  loading.value = true
  try {
    const params: any = { 
      page: page.value, 
      size: size.value,
      type: undefined,
      read: undefined
    }
    
    // 逻辑修正:严格构造过滤参数
    if (currentFilter.value === 'unread') {
      params.read = false
    } else if (currentFilter.value !== 'all') {
      params.type = currentFilter.value
    }
    
    const { data } = await getNotificationsPage(params)
    if (page.value === 0) {
      notifications.value = data.items || []
    } else {
      notifications.value = [...notifications.value, ...(data.items || [])]
    }
    total.value = data.total || 0
  } catch (error) {
    console.error('Failed to fetch notifications:', error)
  } finally {
    loading.value = false
  }
}

const handleMarkRead = async (id: number) => {
  try {
    await acknowledgeNotification(id)
    const item = notifications.value.find(n => n.id === id)
    if (item) item.status = 1
    notifyStore.fetchUnread()
  } catch (error) { ElMessage.error('操作失败') }
}

const handleMarkUnread = async (id: number) => {
  try {
    await markAsUnread(id)
    const item = notifications.value.find(n => n.id === id)
    if (item) item.status = 0
    notifyStore.fetchUnread()
  } catch (error) { ElMessage.error('操作失败') }
}

const handleItemClick = async (item: NotificationDTO) => {
  if (item.status === 0) {
    await handleMarkRead(item.id)
  }
  // 若有 sourceId(深度检索任务ID),关闭弹窗并跳转到 Welcome 页面打开任务详情
  if (item.sourceId != null) {
    close()
    router.push({ name: 'Welcome', query: { sourceId: String(item.sourceId) } })
  }
}

const handleMarkAllAsRead = async () => {
  try {
    await acknowledgeAllNotifications()
    notifications.value.forEach(item => { item.status = 1 })
    notifyStore.fetchUnread()
    ElMessage.success('已全部标记为已读')
  } catch (error) { ElMessage.error('操作失败') }
}

const loadMore = () => {
  page.value++
  fetchNotifications()
}

const formatTime = (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss')

const onHeaderMouseDown = (e: MouseEvent) => {
  isDragging.value = true
  dragOffset.x = e.clientX - position.x
  dragOffset.y = e.clientY - position.y
  window.addEventListener('mousemove', onMouseMove)
  window.addEventListener('mouseup', onMouseUp)
}

const onMouseMove = (e: MouseEvent) => {
  if (!isDragging.value) return
  const maxX = window.innerWidth - 380
  const maxY = window.innerHeight - 550
  position.x = Math.max(0, Math.min(e.clientX - dragOffset.x, maxX))
  position.y = Math.max(0, Math.min(e.clientY - dragOffset.y, maxY))
}

const onMouseUp = () => {
  if (isDragging.value) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify({ x: position.x, y: position.y }))
  }
  isDragging.value = false
  window.removeEventListener('mousemove', onMouseMove)
  window.removeEventListener('mouseup', onMouseUp)
}

onMounted(() => {
  window.addEventListener('click', handleOutsideClick)
  window.addEventListener('keydown', handleKeyDown)
})

onUnmounted(() => {
  window.removeEventListener('click', handleOutsideClick)
  window.removeEventListener('keydown', handleKeyDown)
})

defineExpose({ toggle, open: () => { visible.value = true; resetAndFetch(); }, close })
</script>

<style scoped>
.notification-center-container {
  position: fixed;
  width: 380px;
  height: 550px;
  background: var(--color-bg, #fff);
  border-radius: 12px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.15);
  z-index: 9999;
  display: flex;
  flex-direction: column;
  overflow: visible;
}

.notification-header {
  padding: 14px 16px;
  background: #fcfcfc;
  border-bottom: 1px solid #f2f2f2;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: move;
  border-radius: 12px 12px 0 0;
  flex-shrink: 0;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
.header-right { display: flex; align-items: center; gap: 12px; }
.ack-all-btn { font-size: 13px; color: #409eff; cursor: pointer; font-weight: 500; }
.ack-all-btn:hover { color: #66b1ff; text-decoration: underline; }
.close-icon {
  cursor: pointer;
  color: #909399;
  font-size: 18px;
  transition: all 0.2s;
}
.close-icon:hover { color: #f56c6c; }

.filter-area {
  padding: 12px 16px;
  background: #fff;
  border-bottom: 1px solid #f2f2f2;
  flex-shrink: 0;
  position: relative;
  z-index: 10;
}

.custom-select-wrapper { position: relative; width: 100%; }
.custom-select-trigger {
  display: flex; align-items: center; justify-content: space-between;
  padding: 6px 12px; background: #f5f7fa; border-radius: 6px;
  cursor: pointer; transition: all 0.2s; border: 1px solid transparent;
}
.custom-select-trigger:hover { background: #edf1f7; border-color: #dcdfe6; }
.current-label { font-size: 14px; color: #606266; font-weight: 500; }
.arrow-icon { font-size: 12px; color: #909399; transition: transform 0.3s; }
.arrow-icon.is-open { transform: rotate(180deg); }

.custom-dropdown-menu {
  position: absolute; top: calc(100% + 4px); left: 0;
  width: 100%; background: #fff; border: 1px solid #e4e7ed;
  border-radius: 8px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 4px 0; z-index: 100;
}
.custom-dropdown-item {
  display: flex; align-items: center; justify-content: space-between;
  padding: 10px 16px; font-size: 14px; color: #606266;
  cursor: pointer; transition: all 0.2s;
}
.custom-dropdown-item:hover { background-color: #f5f7fa; color: #409eff; }
.custom-dropdown-item.is-active { color: #409eff; font-weight: 600; background-color: #f0f7ff;}

.notification-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px 16px 18px;
  background: #fff;
  border-radius: 0 0 12px 12px;
  /* 隐藏滚动条但保留滚动能力 */
  scrollbar-width: none;        /* Firefox */
  -ms-overflow-style: none;     /* IE/Edge 旧版 */
}
.notification-list::-webkit-scrollbar {
  width: 0;
  height: 0;
}
.notification-item {
  padding: 12px; border-radius: 8px; border: 1px solid #f5f7fa;
  background: #fff; margin-bottom: 6px; transition: all 0.3s ease; position: relative;
  cursor: pointer;
}
.notification-item:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); border-color: #e4e7ed; }
.notification-item.is-unread { background: #fffcfc; border-left: 3px solid #f56c6c; border-color: #ffeaea; }

.item-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px; }
.item-title { font-weight: 700; font-size: 15px; color: #1a1a1a; line-height: 1.4; flex: 1; }
.item-actions { display: flex; align-items: center; gap: 8px; }
.action-icon {
  font-size: 18px;
  cursor: pointer;
  transition: all 0.2s;
  opacity: 0.7;
}
.action-icon:hover {
  opacity: 1;
  transform: scale(1.15);
}
.mark-read { color: #67c23a; }
.mark-unread { color: #909399; }
.unread-dot { width: 8px; height: 8px; background: #f56c6c; border-radius: 50%; flex-shrink: 0; }

.item-content { font-size: 13px; color: #4a4a4a; line-height: 1.6; margin-bottom: 12px; }
.item-footer { display: flex; justify-content: flex-end; padding-top: 8px; border-top: 1px solid #f5f7fa; }
.item-time { font-size: 11px; color: #999; cursor: help; }

.load-more { text-align: center; padding: 12px; font-size: 13px; color: #909399; cursor: pointer; border-radius: 8px; }
.load-more:hover { background: #f5f7fa; color: #409eff; }

/* Dark theme support(与 NewbieTaskDialog 一致) */
:global(.theme-dark) .notification-center-container { background: #2d2d2d; border-color: #4c4d4f; }
:global(.theme-dark) .notification-header { background: #333333; border-bottom-color: #4c4d4f; }
:global(.theme-dark) .header-title { color: #e4e7ed; }
:global(.theme-dark) .filter-area { background: #2d2d2d; border-bottom-color: #4c4d4f; }
:global(.theme-dark) .custom-select-trigger { background: #37373d; color: #e4e7ed; }
:global(.theme-dark) .custom-dropdown-menu { background: #333333; border-color: #4c4d4f; }
:global(.theme-dark) .custom-dropdown-item { color: #e4e7ed; }
:global(.theme-dark) .notification-list { background: #2d2d2d; }
:global(.theme-dark) .notification-item { background: #37373d; border-color: #4c4d4f; }
:global(.theme-dark) .notification-item.is-unread { background: #37373d; border-color: #4c4d4f; }
:global(.theme-dark) .item-title { color: #e4e7ed; }
:global(.theme-dark) .item-content { color: #e4e7ed; }
:global(.theme-dark) .item-footer { border-top-color: #4c4d4f; }
</style>