<template>
  <div class="notification-center">
    <el-card>
      <!-- Tab分类 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="全部消息" name="all">
          <template #label>
            <span>全部消息</span>
            <el-badge
              v-if="unreadCount > 0"
              :value="unreadCount"
              class="tab-badge"
            />
          </template>
        </el-tab-pane>
        <el-tab-pane name="unread">
          <template #label>
            <span>未读消息</span>
            <el-badge
              v-if="unreadCount > 0"
              :value="unreadCount"
              class="tab-badge"
            />
          </template>
        </el-tab-pane>
        <el-tab-pane label="已读消息" name="read" />

        <!-- 批量操作 -->
        <template #extra>
          <div class="batch-actions">
            <el-checkbox
              v-model="selectAll"
              :indeterminate="isIndeterminate"
              @change="handleSelectAll"
            >
              全选
            </el-checkbox>
            <el-button
              :disabled="selectedIds.length === 0"
              @click="handleMarkAsRead"
            >
              标记已读
            </el-button>
            <el-button
              :disabled="selectedIds.length === 0"
              @click="handleMarkAsUnread"
            >
              标记未读
            </el-button>
            <el-button
              type="danger"
              :disabled="selectedIds.length === 0"
              @click="handleBatchDelete"
            >
              批量删除
            </el-button>
            <el-button @click="handleMarkAllAsRead">
              全部已读
            </el-button>
          </div>
        </template>
      </el-tabs>

      <!-- 消息列表 -->
      <div class="notification-list" v-loading="loading">
        <div
          v-for="item in notifications"
          :key="item.id"
          class="notification-item"
          :class="{ unread: !item.isRead }"
        >
          <el-checkbox
            v-model="item.selected"
            @change="handleSelectionChange"
          />

          <div class="notification-content" @click="handleViewDetail(item)">
            <div class="notification-header">
              <div class="notification-title">
                <el-tag
                  :type="getTypeColor(item.type)"
                  size="small"
                  class="type-tag"
                >
                  {{ getTypeName(item.type) }}
                </el-tag>
                <span class="title-text">{{ item.title }}</span>
                <el-badge
                  v-if="!item.isRead"
                  is-dot
                  class="unread-dot"
                />
              </div>
              <div class="notification-time">{{ item.createdAt }}</div>
            </div>

            <div class="notification-body">
              {{ item.content }}
            </div>

            <div class="notification-footer">
              <el-button
                v-if="item.link"
                link
                type="primary"
                @click.stop="handleGoTo(item)"
              >
                查看详情
              </el-button>
              <el-button
                link
                type="primary"
                @click.stop="handleMarkSingleRead(item)"
                v-if="!item.isRead"
              >
                标记已读
              </el-button>
              <el-popconfirm
                title="确定删除该消息吗？"
                @confirm.stop="handleDelete(item.id)"
              >
                <template #reference>
                  <el-button link type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty
          v-if="notifications.length === 0"
          description="暂无消息"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="selectedNotification?.title"
      width="600px"
    >
      <div v-if="selectedNotification" class="notification-detail">
        <div class="detail-meta">
          <el-tag :type="getTypeColor(selectedNotification.type)">
            {{ getTypeName(selectedNotification.type) }}
          </el-tag>
          <span class="detail-time">{{ selectedNotification.createdAt }}</span>
        </div>
        <div class="detail-content">
          {{ selectedNotification.content }}
        </div>
        <div class="detail-extra" v-if="selectedNotification.extra">
          <pre>{{ formatJson(selectedNotification.extra) }}</pre>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button
          v-if="selectedNotification?.link"
          type="primary"
          @click="handleGoTo(selectedNotification)"
        >
          查看详情
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getNotifications, markAsRead, markAsUnread, deleteNotification, markAllAsRead } from '@/api'
import { usePagination } from '@/composables/usePagination'
import { ElMessage } from 'element-plus'

const router = useRouter()

const { pagination, resetPage, setTotal } = usePagination()

// 消息类型
const notificationTypes = [
  { label: '系统通知', value: 'system', color: 'info' },
  { label: '审批通知', value: 'approval', color: 'warning' },
  { label: '资产预警', value: 'alert', color: 'danger' },
  { label: '任务提醒', value: 'task', color: 'primary' },
  { label: '调拨通知', value: 'transfer', color: 'success' },
  { label: '维修通知', value: 'maintenance', color: 'warning' }
]

const activeTab = ref('all')
const loading = ref(false)
const notifications = ref<any[]>([])
const unreadCount = ref(0)
const detailDialogVisible = ref(false)
const selectedNotification = ref<any>(null)
const selectAll = ref(false)
const isIndeterminate = ref(false)

const selectedIds = computed(() => {
  return notifications.value.filter(n => n.selected).map(n => n.id)
})

// 获取消息列表
const fetchNotifications = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      page_size: pagination.pageSize
    }
    if (activeTab.value === 'unread') {
      params.is_read = false
    } else if (activeTab.value === 'read') {
      params.is_read = true
    }

    const data = await getNotifications(params)
    notifications.value = data.items.map((item: any) => ({
      ...item,
      selected: false
    }))
    setTotal(data.total)
    unreadCount.value = data.unreadCount || 0
  } catch (error) {
    ElMessage.error('获取消息列表失败')
  } finally {
    loading.value = false
  }
}

// Tab切换
const handleTabChange = () => {
  resetPage()
  fetchNotifications()
}

// 分页变化
const handlePageChange = () => {
  fetchNotifications()
}

// 选择变化
const handleSelectionChange = () => {
  const selectedCount = notifications.value.filter(n => n.selected).length
  selectAll.value = selectedCount === notifications.value.length
  isIndeterminate.value = selectedCount > 0 && selectedCount < notifications.value.length
}

// 全选
const handleSelectAll = (checked: boolean) => {
  notifications.value.forEach(item => {
    item.selected = checked
  })
  isIndeterminate.value = false
}

// 标记已读
const handleMarkAsRead = async () => {
  try {
    await markAsRead(selectedIds.value)
    ElMessage.success('标记成功')
    fetchNotifications()
  } catch (error) {
    ElMessage.error('标记失败')
  }
}

// 标记未读
const handleMarkAsUnread = async () => {
  try {
    await markAsUnread(selectedIds.value)
    ElMessage.success('标记成功')
    fetchNotifications()
  } catch (error) {
    ElMessage.error('标记失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await deleteNotification(selectedIds.value)
    ElMessage.success('删除成功')
    fetchNotifications()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 全部已读
const handleMarkAllAsRead = async () => {
  try {
    await markAllAsRead()
    ElMessage.success('操作成功')
    fetchNotifications()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 单条标记已读
const handleMarkSingleRead = async (item: any) => {
  try {
    await markAsRead([item.id])
    item.isRead = true
    unreadCount.value = Math.max(0, unreadCount.value - 1)
  } catch (error) {
    ElMessage.error('标记失败')
  }
}

// 查看详情
const handleViewDetail = async (item: any) => {
  selectedNotification.value = item
  detailDialogVisible.value = true
  if (!item.isRead) {
    await handleMarkSingleRead(item)
  }
}

// 删除单条
const handleDelete = async (id: number) => {
  try {
    await deleteNotification([id])
    ElMessage.success('删除成功')
    fetchNotifications()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 跳转
const handleGoTo = (item: any) => {
  if (item.link) {
    router.push(item.link)
    detailDialogVisible.value = false
  }
}

// 获取类型颜色
const getTypeColor = (type: string) => {
  const item = notificationTypes.find(t => t.value === type)
  return item?.color || ''
}

// 获取类型名称
const getTypeName = (type: string) => {
  const item = notificationTypes.find(t => t.value === type)
  return item?.label || type
}

// 格式化JSON
const formatJson = (data: any) => {
  try {
    return JSON.stringify(data, null, 2)
  } catch {
    return data
  }
}

onMounted(() => {
  fetchNotifications()
})
</script>

<style scoped lang="scss">
.notification-center {
  .batch-actions {
    display: flex;
    gap: 10px;
    align-items: center;
  }

  .tab-badge {
    margin-left: 8px;
  }

  .notification-list {
    min-height: 400px;
    max-height: calc(100vh - 350px);
    overflow-y: auto;

    .notification-item {
      display: flex;
      gap: 12px;
      padding: 16px;
      border-bottom: 1px solid #ebeef5;
      transition: background-color 0.3s;

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

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

      .notification-content {
        flex: 1;
        cursor: pointer;

        .notification-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;

          .notification-title {
            display: flex;
            align-items: center;
            gap: 8px;

            .type-tag {
              flex-shrink: 0;
            }

            .title-text {
              font-weight: 500;
              color: #303133;
            }

            .unread-dot {
              margin-left: 4px;
            }
          }

          .notification-time {
            font-size: 12px;
            color: #909399;
          }
        }

        .notification-body {
          color: #606266;
          font-size: 14px;
          line-height: 1.6;
          margin-bottom: 12px;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .notification-footer {
          display: flex;
          gap: 8px;
        }
      }
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }

  .notification-detail {
    .detail-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .detail-time {
        font-size: 12px;
        color: #909399;
      }
    }

    .detail-content {
      color: #606266;
      line-height: 1.8;
      margin-bottom: 16px;
    }

    .detail-extra {
      background: #f5f7fa;
      padding: 12px;
      border-radius: 4px;
      font-size: 12px;

      pre {
        margin: 0;
        white-space: pre-wrap;
        word-wrap: break-word;
      }
    }
  }
}
</style>
