<template>
  <div class="notification-bell">
    <el-dropdown
      trigger="click"
      @visible-change="handleDropdownVisible"
    >
      <span class="bell-icon">
        <el-badge :value="unreadCount" :hidden="unreadCount === 0" :max="99">
          <el-icon :size="20"><Bell /></el-icon>
        </el-badge>
      </span>

      <template #dropdown>
        <el-dropdown-menu class="notification-dropdown">
          <div class="dropdown-header">
            <span class="header-title">消息通知</span>
            <el-link
              type="primary"
              :underline="false"
              @click="handleMarkAllAsRead"
              v-if="unreadCount > 0"
            >
              全部已读
            </el-link>
          </div>

          <div class="dropdown-content" v-loading="loading">
            <div
              v-for="item in recentNotifications"
              :key="item.id"
              class="notification-item"
              :class="{ unread: !item.isRead }"
              @click="handleNotificationClick(item)"
            >
              <div class="item-icon">
                <el-icon :color="getTypeColor(item.type)">
                  <component :is="getTypeIcon(item.type)" />
                </el-icon>
              </div>
              <div class="item-content">
                <div class="item-title">
                  <span class="title-text">{{ item.title }}</span>
                  <el-badge
                    v-if="!item.isRead"
                    is-dot
                    class="unread-dot"
                  />
                </div>
                <div class="item-desc">{{ item.content }}</div>
                <div class="item-time">{{ formatTime(item.createdAt) }}</div>
              </div>
            </div>

            <el-empty
              v-if="recentNotifications.length === 0"
              description="暂无消息"
              :image-size="80"
            />
          </div>

          <div class="dropdown-footer">
            <el-link
              type="primary"
              :underline="false"
              @click="handleViewAll"
            >
              查看全部
            </el-link>
          </div>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Bell, Warning, InfoFilled, SuccessFilled, CircleClose } from '@element-plus/icons-vue'
import { getNotifications, markAsRead, markAllAsRead } from '@/api'
import { ElMessage } from 'element-plus'

const router = useRouter()

const loading = ref(false)
const unreadCount = ref(0)
const recentNotifications = ref<any[]>([])

// 消息类型图标
const typeIcons: Record<string, any> = {
  system: InfoFilled,
  approval: Warning,
  alert: CircleClose,
  task: SuccessFilled,
  transfer: Bell,
  maintenance: Warning
}

// 消息类型颜色
const typeColors: Record<string, string> = {
  system: '#909399',
  approval: '#e6a23c',
  alert: '#f56c6c',
  task: '#67c23a',
  transfer: '#409eff',
  maintenance: '#e6a23c'
}

// 获取未读数量
const fetchUnreadCount = async () => {
  try {
    const data = await getNotifications({ page: 1, page_size: 1, is_read: false })
    unreadCount.value = data.total || 0
  } catch (error) {
    console.error('获取未读数量失败', error)
  }
}

// 获取最近消息
const fetchRecentNotifications = async () => {
  loading.value = true
  try {
    const data = await getNotifications({ page: 1, page_size: 5 })
    recentNotifications.value = data.items || []
  } catch (error) {
    ElMessage.error('获取消息失败')
  } finally {
    loading.value = false
  }
}

// 下拉框显示/隐藏
const handleDropdownVisible = (visible: boolean) => {
  if (visible) {
    fetchRecentNotifications()
  }
}

// 消息点击
const handleNotificationClick = async (item: any) => {
  if (!item.isRead) {
    try {
      await markAsRead([item.id])
      item.isRead = true
      unreadCount.value = Math.max(0, unreadCount.value - 1)
    } catch (error) {
      console.error('标记已读失败', error)
    }
  }

  if (item.link) {
    router.push(item.link)
  }
}

// 全部已读
const handleMarkAllAsRead = async () => {
  try {
    await markAllAsRead()
    unreadCount.value = 0
    recentNotifications.value.forEach((item: any) => {
      item.isRead = true
    })
    ElMessage.success('已全部标记为已读')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 查看全部
const handleViewAll = () => {
  router.push('/system/notification')
}

// 获取类型图标
const getTypeIcon = (type: string) => {
  return typeIcons[type] || InfoFilled
}

// 获取类型颜色
const getTypeColor = (type: string) => {
  return typeColors[type] || '#909399'
}

// 格式化时间
const formatTime = (time: string) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour

  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < 7 * day) {
    return `${Math.floor(diff / day)}天前`
  } else {
    return date.toLocaleDateString()
  }
}

onMounted(() => {
  fetchUnreadCount()
  // 每30秒刷新一次未读数量
  setInterval(fetchUnreadCount, 30000)
})

// 暴露刷新方法供外部调用
defineExpose({
  refresh: fetchUnreadCount
})
</script>

<style scoped lang="scss">
.notification-bell {
  .bell-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    cursor: pointer;
    transition: background-color 0.3s;
    border-radius: 4px;

    &:hover {
      background-color: rgba(0, 0, 0, 0.04);
    }
  }
}

.notification-dropdown {
  width: 360px;
  max-height: 500px;
  padding: 0;

  .dropdown-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid #ebeef5;

    .header-title {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
    }
  }

  .dropdown-content {
    max-height: 400px;
    overflow-y: auto;

    .notification-item {
      display: flex;
      gap: 12px;
      padding: 12px 16px;
      cursor: pointer;
      transition: background-color 0.3s;

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

      &.unread {
        background-color: #ecf5ff;
      }

      .item-icon {
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background-color: #f0f2f5;
      }

      .item-content {
        flex: 1;
        min-width: 0;

        .item-title {
          display: flex;
          align-items: center;
          gap: 4px;
          margin-bottom: 4px;

          .title-text {
            font-size: 14px;
            font-weight: 500;
            color: #303133;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .unread-dot {
            flex-shrink: 0;
          }
        }

        .item-desc {
          font-size: 12px;
          color: #606266;
          line-height: 1.5;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          margin-bottom: 4px;
        }

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

  .dropdown-footer {
    padding: 12px 16px;
    border-top: 1px solid #ebeef5;
    text-align: center;
  }
}
</style>
