<template>
  <div class="notifications-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">消息中心</h1>
      <div class="header-actions">
        <el-button 
          v-if="unreadCount > 0"
          type="primary" 
          plain
          @click="handleMarkAllRead"
        >
          <el-icon><Check /></el-icon>
          全部标记已读
        </el-button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section card">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="全部" name="all">
          <template #label>
            <span>全部</span>
            <el-badge v-if="total > 0" :value="total" :max="99" class="tab-badge" />
          </template>
        </el-tab-pane>
        <el-tab-pane label="未读" name="unread">
          <template #label>
            <span>未读</span>
            <el-badge v-if="unreadCount > 0" :value="unreadCount" :max="99" class="tab-badge" type="danger" />
          </template>
        </el-tab-pane>
        <el-tab-pane label="岗位通知" name="position_assign" />
        <el-tab-pane label="课程通知" name="course_assign" />
        <el-tab-pane label="系统通知" name="system" />
      </el-tabs>
    </div>

    <!-- 通知列表 -->
    <div class="notification-list card" 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 }"
        >
          <div class="item-left">
            <div class="item-icon" :class="getTypeClass(item.type)">
              <el-icon :size="20">
                <component :is="getTypeIcon(item.type)" />
              </el-icon>
            </div>
          </div>
          
          <div class="item-main">
            <div class="item-header">
              <span class="item-title">{{ item.title }}</span>
              <el-tag size="small" :type="getTypeTagType(item.type)">
                {{ getTypeName(item.type) }}
              </el-tag>
            </div>
            <div class="item-content">{{ item.content }}</div>
            <div class="item-footer">
              <span class="item-time">
                <el-icon><Clock /></el-icon>
                {{ formatTime(item.created_at) }}
              </span>
              <span v-if="item.sender_name" class="item-sender">
                来自：{{ item.sender_name }}
              </span>
            </div>
          </div>
          
          <div class="item-actions">
            <el-button 
              v-if="!item.is_read"
              link 
              type="primary"
              size="small"
              @click="handleMarkRead(item)"
            >
              标记已读
            </el-button>
            <el-button 
              v-if="item.related_id"
              link 
              type="primary"
              size="small"
              @click="handleViewDetail(item)"
            >
              查看详情
            </el-button>
            <el-button 
              link 
              type="danger"
              size="small"
              @click="handleDelete(item)"
            >
              删除
            </el-button>
          </div>
        </div>
      </template>
      
      <el-empty v-else description="暂无消息" :image-size="120" />
    </div>

    <!-- 分页 -->
    <div v-if="total > pageSize" class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

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

const router = useRouter()

// 状态
const loading = ref(false)
const activeTab = ref('all')
const notifications = ref<Notification[]>([])
const total = ref(0)
const unreadCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

/**
 * 加载通知列表
 */
const loadNotifications = async () => {
  loading.value = true
  try {
    const params: any = {
      page: currentPage.value,
      page_size: pageSize.value
    }
    
    // 根据tab筛选
    if (activeTab.value === 'unread') {
      params.is_read = false
    } else if (activeTab.value !== 'all') {
      params.type = activeTab.value
    }
    
    const res = await notificationApi.getNotifications(params)
    if (res.code === 200 && res.data) {
      notifications.value = res.data.items
      total.value = res.data.total
      unreadCount.value = res.data.unread_count
    }
  } catch (error) {
    ElMessage.error('加载消息失败')
  } finally {
    loading.value = false
  }
}

/**
 * Tab切换
 */
const handleTabChange = () => {
  currentPage.value = 1
  loadNotifications()
}

/**
 * 分页切换
 */
const handlePageChange = () => {
  loadNotifications()
}

/**
 * 标记单条已读
 */
const handleMarkRead = async (item: Notification) => {
  try {
    await notificationApi.markAsRead([item.id])
    item.is_read = true
    unreadCount.value = Math.max(0, unreadCount.value - 1)
    ElMessage.success('已标记为已读')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

/**
 * 标记全部已读
 */
const handleMarkAllRead = async () => {
  try {
    await ElMessageBox.confirm('确定将所有消息标记为已读？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await notificationApi.markAsRead()
    unreadCount.value = 0
    notifications.value = notifications.value.map(n => ({ ...n, is_read: true }))
    ElMessage.success('已全部标记为已读')
  } catch (error) {
    // 取消操作不处理
  }
}

/**
 * 查看详情
 */
const handleViewDetail = (item: Notification) => {
  // 先标记已读
  if (!item.is_read) {
    handleMarkRead(item)
  }
  
  // 根据类型跳转
  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')
  }
}

/**
 * 删除通知
 */
const handleDelete = async (item: Notification) => {
  try {
    await ElMessageBox.confirm('确定删除这条消息？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await notificationApi.deleteNotification(item.id)
    
    // 从列表中移除
    const index = notifications.value.findIndex(n => n.id === item.id)
    if (index > -1) {
      notifications.value.splice(index, 1)
      total.value--
      if (!item.is_read) {
        unreadCount.value = Math.max(0, unreadCount.value - 1)
      }
    }
    
    ElMessage.success('删除成功')
  } catch (error) {
    // 取消操作不处理
  }
}

/**
 * 获取通知类型图标
 */
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 getTypeName = (type: NotificationType) => {
  const nameMap: Record<NotificationType, string> = {
    position_assign: '岗位通知',
    course_assign: '课程通知',
    exam_remind: '考试提醒',
    task_assign: '任务通知',
    system: '系统通知'
  }
  return nameMap[type] || '系统通知'
}

/**
 * 获取通知类型标签样式
 */
const getTypeTagType = (type: NotificationType) => {
  const tagMap: Record<NotificationType, string> = {
    position_assign: 'success',
    course_assign: 'primary',
    exam_remind: 'warning',
    task_assign: 'info',
    system: ''
  }
  return tagMap[type] || ''
}

/**
 * 格式化时间
 */
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.toLocaleString()
}

// 组件挂载
onMounted(() => {
  loadNotifications()
})
</script>

<style lang="scss" scoped>
.notifications-container {
  max-width: 900px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
}

.filter-section {
  padding: 16px 24px 0;
  margin-bottom: 16px;
  
  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }
  
  .tab-badge {
    margin-left: 6px;
    
    :deep(.el-badge__content) {
      font-size: 10px;
      height: 16px;
      line-height: 16px;
      padding: 0 4px;
    }
  }
}

.notification-list {
  padding: 16px;
  
  .notification-item {
    display: flex;
    gap: 16px;
    padding: 20px;
    border-radius: 12px;
    transition: all 0.3s;
    border: 1px solid transparent;
    
    &:not(:last-child) {
      margin-bottom: 12px;
    }
    
    &:hover {
      background-color: #f5f7fa;
    }
    
    &.unread {
      background-color: rgba(102, 126, 234, 0.04);
      border-color: rgba(102, 126, 234, 0.1);
    }
    
    .item-left {
      flex-shrink: 0;
      
      .item-icon {
        width: 44px;
        height: 44px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        
        &.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-main {
      flex: 1;
      min-width: 0;
      
      .item-header {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 8px;
        
        .item-title {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }
      
      .item-content {
        font-size: 14px;
        color: #606266;
        line-height: 1.6;
        margin-bottom: 12px;
      }
      
      .item-footer {
        display: flex;
        align-items: center;
        gap: 16px;
        font-size: 12px;
        color: #909399;
        
        .item-time {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
    
    .item-actions {
      flex-shrink: 0;
      display: flex;
      flex-direction: column;
      gap: 8px;
      align-items: flex-end;
    }
  }
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

// 响应式
@media (max-width: 768px) {
  .notifications-container {
    padding: 0 12px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    
    .page-title {
      font-size: 20px;
    }
  }
  
  .notification-list {
    .notification-item {
      flex-direction: column;
      gap: 12px;
      
      .item-left {
        .item-icon {
          width: 36px;
          height: 36px;
        }
      }
      
      .item-actions {
        flex-direction: row;
        justify-content: flex-start;
      }
    }
  }
}
</style>




