<template>
  <el-popover
    placement="bottom"
    :width="360"
    trigger="click"
    popper-class="notification-popover"
    @show="handlePopoverShow"
  >
    <template #reference>
      <el-button link class="notification-btn">
        <el-icon :size="20"><Bell /></el-icon>
        <el-badge 
          v-if="unreadCount > 0" 
          :value="unreadCount > 99 ? '99+' : unreadCount" 
          class="notification-badge" 
        />
      </el-button>
    </template>
    
    <div class="notification-panel">
      <!-- 面板头部 -->
      <div class="panel-header">
        <span class="title">消息通知</span>
        <el-button 
          v-if="unreadCount > 0"
          link 
          type="primary" 
          size="small"
          @click="handleMarkAllRead"
        >
          全部已读
        </el-button>
      </div>
      
      <!-- 通知列表 -->
      <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="{ unread: !item.is_read }"
            @click="handleNotificationClick(item)"
          >
            <div class="item-icon" :class="getTypeClass(item.type)">
              <el-icon>
                <component :is="getTypeIcon(item.type)" />
              </el-icon>
            </div>
            <div class="item-content">
              <div class="item-title">{{ item.title }}</div>
              <div class="item-desc">{{ item.content }}</div>
              <div class="item-time">{{ formatTime(item.created_at) }}</div>
            </div>
            <div v-if="!item.is_read" class="unread-dot"></div>
          </div>
        </template>
        
        <el-empty v-else description="暂无消息" :image-size="80" />
      </div>
      
      <!-- 面板底部 -->
      <div class="panel-footer">
        <el-button link type="primary" @click="goToNotificationCenter">
          查看全部消息
        </el-button>
      </div>
    </div>
  </el-popover>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Bell, OfficeBuilding, Notebook, Clock, Document, InfoFilled } from '@element-plus/icons-vue'
import { notificationApi, type Notification, type NotificationType } from '@/api/notification'

const router = useRouter()

// 状态
const loading = ref(false)
const unreadCount = ref(0)
const notifications = ref<Notification[]>([])

// 轮询定时器
let pollTimer: number | null = null

/**
 * 获取未读数量
 */
const fetchUnreadCount = async () => {
  try {
    const res = await notificationApi.getUnreadCount()
    if (res.code === 200 && res.data) {
      unreadCount.value = res.data.unread_count
    }
  } catch (error) {
    console.error('获取未读数量失败:', error)
  }
}

/**
 * 获取通知列表
 */
const fetchNotifications = async () => {
  loading.value = true
  try {
    const res = await notificationApi.getNotifications({ page: 1, page_size: 5 })
    if (res.code === 200 && res.data) {
      notifications.value = res.data.items
      unreadCount.value = res.data.unread_count
    }
  } catch (error) {
    console.error('获取通知列表失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 弹窗显示时加载数据
 */
const handlePopoverShow = () => {
  fetchNotifications()
}

/**
 * 标记全部已读
 */
const handleMarkAllRead = async () => {
  try {
    await notificationApi.markAsRead()
    unreadCount.value = 0
    notifications.value = notifications.value.map(n => ({ ...n, is_read: true }))
    ElMessage.success('已全部标记为已读')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

/**
 * 点击通知项
 */
const handleNotificationClick = async (item: Notification) => {
  // 标记已读
  if (!item.is_read) {
    try {
      await notificationApi.markAsRead([item.id])
      item.is_read = true
      unreadCount.value = Math.max(0, unreadCount.value - 1)
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }
  
  // 根据类型跳转
  if (item.related_type === 'course' && item.related_id) {
    router.push(`/trainee/course/${item.related_id}`)
  } else if (item.related_type === 'position') {
    router.push('/trainee/course-center')
  } else {
    router.push('/user/notifications')
  }
}

/**
 * 跳转到消息中心
 */
const goToNotificationCenter = () => {
  router.push('/user/notifications')
}

/**
 * 获取通知类型图标
 */
const getTypeIcon = (type: NotificationType) => {
  const iconMap: Record<NotificationType, any> = {
    position_assign: OfficeBuilding,
    course_assign: Notebook,
    exam_remind: Clock,
    task_assign: Document,
    system: InfoFilled
  }
  return iconMap[type] || InfoFilled
}

/**
 * 获取通知类型样式类
 */
const getTypeClass = (type: NotificationType) => {
  const classMap: Record<NotificationType, string> = {
    position_assign: 'type-position',
    course_assign: 'type-course',
    exam_remind: 'type-exam',
    task_assign: 'type-task',
    system: 'type-system'
  }
  return classMap[type] || 'type-system'
}

/**
 * 格式化时间
 */
const formatTime = (time: string) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString()
}

// 组件挂载
onMounted(() => {
  fetchUnreadCount()
  // 每30秒轮询一次未读数量
  pollTimer = window.setInterval(fetchUnreadCount, 30000)
})

// 组件卸载
onUnmounted(() => {
  if (pollTimer) {
    clearInterval(pollTimer)
  }
})
</script>

<style lang="scss" scoped>
.notification-btn {
  position: relative;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.3s;

  &:hover {
    background-color: #f5f7fa;
  }

  .notification-badge {
    position: absolute;
    top: 2px;
    right: 2px;
    
    :deep(.el-badge__content) {
      font-size: 10px;
      height: 16px;
      line-height: 16px;
      padding: 0 4px;
    }
  }
}

.notification-panel {
  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;
    
    .title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .notification-list {
    max-height: 400px;
    overflow-y: auto;
    margin: 8px 0;
    
    .notification-item {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      padding: 12px 8px;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s;
      position: relative;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      &.unread {
        background-color: rgba(102, 126, 234, 0.05);
      }
      
      .item-icon {
        width: 36px;
        height: 36px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        
        &.type-position {
          background: rgba(103, 194, 58, 0.1);
          color: #67c23a;
        }
        
        &.type-course {
          background: rgba(102, 126, 234, 0.1);
          color: #667eea;
        }
        
        &.type-exam {
          background: rgba(230, 162, 60, 0.1);
          color: #e6a23c;
        }
        
        &.type-task {
          background: rgba(144, 147, 153, 0.1);
          color: #909399;
        }
        
        &.type-system {
          background: rgba(64, 158, 255, 0.1);
          color: #409eff;
        }
      }
      
      .item-content {
        flex: 1;
        min-width: 0;
        
        .item-title {
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .item-desc {
          font-size: 12px;
          color: #909399;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .item-time {
          font-size: 11px;
          color: #c0c4cc;
        }
      }
      
      .unread-dot {
        position: absolute;
        top: 16px;
        right: 8px;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #f56c6c;
      }
    }
  }
  
  .panel-footer {
    text-align: center;
    padding-top: 12px;
    border-top: 1px solid #ebeef5;
  }
}
</style>

<style>
/* 全局样式覆盖 popover */
.notification-popover {
  padding: 16px !important;
}
</style>




