<template>
  <div class="message-notification">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>消息通知</h2>
      <p>设备预警和系统通知管理</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <bell-outlined />
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.total_alerts || 0 }}</div>
                <div class="stat-label">总预警数</div>
              </div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon unread">
                <exclamation-circle-outlined />
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.unread_alerts || 0 }}</div>
                <div class="stat-label">未读预警</div>
              </div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon critical">
                <warning-outlined />
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ getCriticalCount() }}</div>
                <div class="stat-label">严重预警</div>
              </div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon pending">
                <clock-circle-outlined />
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ getPendingCount() }}</div>
                <div class="stat-label">待处理</div>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 筛选和操作栏 -->
    <div class="filter-bar">
      <a-row :gutter="16" align="middle">
        <a-col :span="4">
          <a-select
            v-model:value="filters.alert_level"
            placeholder="预警级别"
            allowClear
            @change="handleFilterChange"
          >
            <a-select-option value="info">信息</a-select-option>
            <a-select-option value="warning">警告</a-select-option>
            <a-select-option value="critical">严重</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="filters.alert_type"
            placeholder="预警类型"
            allowClear
            @change="handleFilterChange"
          >
            <a-select-option value="temperature">温度异常</a-select-option>
            <a-select-option value="humidity">湿度异常</a-select-option>
            <a-select-option value="offline">设备离线</a-select-option>
            <a-select-option value="maintenance">设备维护</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="filters.status"
            placeholder="处理状态"
            allowClear
            @change="handleFilterChange"
          >
            <a-select-option value="pending">待处理</a-select-option>
            <a-select-option value="processing">处理中</a-select-option>
            <a-select-option value="resolved">已解决</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="filters.is_read"
            placeholder="阅读状态"
            allowClear
            @change="handleFilterChange"
          >
            <a-select-option :value="false">未读</a-select-option>
            <a-select-option :value="true">已读</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="8">
          <a-space>
            <a-button @click="handleExport">
              <download-outlined />
              导出Excel
            </a-button>
            <a-button type="primary" @click="markAllAsRead" :disabled="!hasUnreadAlerts">
              <check-outlined />
              全部标记已读
            </a-button>
            <a-button @click="refreshData">
              <reload-outlined />
              刷新
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 预警列表 -->
    <div class="alert-list">
      <a-list
        :data-source="alerts"
        :loading="loading"
        :pagination="pagination"
        @change="handlePageChange"
      >
        <template #renderItem="{ item }">
          <a-list-item
            :class="['alert-item', `alert-${item.alert_level}`, { 'unread': !item.is_read }]"
            @click="handleAlertClick(item)"
          >
            <a-list-item-meta>
              <template #avatar>
                <a-avatar :class="`avatar-${item.alert_level}`">
                  <template #icon>
                    <component :is="getAlertIcon(item.alert_type)" />
                  </template>
                </a-avatar>
              </template>
              <template #title>
                <div class="alert-title">
                  <span class="title-text">{{ item.alert_title }}</span>
                  <a-tag :color="getAlertLevelColor(item.alert_level)" class="level-tag">
                    {{ getAlertLevelText(item.alert_level) }}
                  </a-tag>
                  <a-tag :color="getStatusColor(item.status)" class="status-tag">
                    {{ getStatusText(item.status) }}
                  </a-tag>
                  <span v-if="!item.is_read" class="unread-dot"></span>
                </div>
              </template>
              <template #description>
                <div class="alert-description">
                  <p class="alert-content">{{ item.alert_content }}</p>
                  <div class="alert-meta">
                    <span class="device-info">
                      <desktop-outlined />
                      {{ item.Device?.device_name || '未知设备' }} ({{ item.Device?.device_number || 'N/A' }})
                    </span>
                    <span class="location-info">
                      <environment-outlined />
                      {{ item.Device?.installation_location || '未知位置' }}
                    </span>
                    <span class="time-info">
                      <clock-circle-outlined />
                      {{ formatTime(item.alert_time) }}
                    </span>
                  </div>
                </div>
              </template>
            </a-list-item-meta>
            <template #actions>
              <a-space>
                <a-button
                  v-if="!item.is_read"
                  type="link"
                  size="small"
                  @click.stop="markAsRead(item)"
                >
                  标记已读
                </a-button>
                <a-button
                  v-if="item.status === 'pending'"
                  type="link"
                  size="small"
                  @click.stop="handleAlert(item)"
                >
                  处理
                </a-button>
                <a-button
                  type="link"
                  size="small"
                  @click.stop="viewDetail(item)"
                >
                  详情
                </a-button>
              </a-space>
            </template>
          </a-list-item>
        </template>
      </a-list>
    </div>

    <!-- 预警详情模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="预警详情"
      width="800px"
      :footer="null"
    >
      <div v-if="selectedAlert" class="alert-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="预警标题" :span="2">
            {{ selectedAlert.alert_title }}
          </a-descriptions-item>
          <a-descriptions-item label="预警级别">
            <a-tag :color="getAlertLevelColor(selectedAlert.alert_level)">
              {{ getAlertLevelText(selectedAlert.alert_level) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="预警类型">
            {{ getAlertTypeText(selectedAlert.alert_type) }}
          </a-descriptions-item>
          <a-descriptions-item label="处理状态">
            <a-tag :color="getStatusColor(selectedAlert.status)">
              {{ getStatusText(selectedAlert.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="阅读状态">
            <a-tag :color="selectedAlert.is_read ? 'green' : 'red'">
              {{ selectedAlert.is_read ? '已读' : '未读' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="预警内容" :span="2">
            {{ selectedAlert.alert_content }}
          </a-descriptions-item>
          <a-descriptions-item label="设备名称">
            {{ selectedAlert.Device?.device_name || '未知设备' }}
          </a-descriptions-item>
          <a-descriptions-item label="设备编号">
            {{ selectedAlert.Device?.device_number || 'N/A' }}
          </a-descriptions-item>
          <a-descriptions-item label="安装位置">
            {{ selectedAlert.Device?.installation_location || '未知位置' }}
          </a-descriptions-item>
          <a-descriptions-item label="设备状态">
            <a-tag :color="getDeviceStatusColor(selectedAlert.Device?.status)">
              {{ getDeviceStatusText(selectedAlert.Device?.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="预警时间">
            {{ formatTime(selectedAlert.alert_time) }}
          </a-descriptions-item>
          <a-descriptions-item label="阅读时间">
            {{ selectedAlert.read_time ? formatTime(selectedAlert.read_time) : '未读' }}
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedAlert.handler_id" label="处理人员">
            {{ selectedAlert.handler_id }}
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedAlert.handle_time" label="处理时间">
            {{ formatTime(selectedAlert.handle_time) }}
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedAlert.handle_note" label="处理备注" :span="2">
            {{ selectedAlert.handle_note }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 处理预警模态框 -->
    <a-modal
      v-model:open="handleModalVisible"
      title="处理预警"
      @ok="submitHandle"
      @cancel="handleModalVisible = false"
    >
      <a-form :model="handleForm" layout="vertical">
        <a-form-item label="处理备注" required>
          <a-textarea
            v-model:value="handleForm.handle_note"
            placeholder="请输入处理备注"
            :rows="4"
          />
        </a-form-item>
        <a-form-item label="处理状态">
          <a-select v-model:value="handleForm.status">
            <a-select-option value="processing">处理中</a-select-option>
            <a-select-option value="resolved">已解决</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import {
  BellOutlined,
  ExclamationCircleOutlined,
  WarningOutlined,
  ClockCircleOutlined,
  CheckOutlined,
  ReloadOutlined,
  DesktopOutlined,
  EnvironmentOutlined,
  FireOutlined,
  CloudOutlined,
  WifiOutlined,
  ToolOutlined,
  DownloadOutlined
} from '@ant-design/icons-vue'
import { deviceAlertAPI } from '@/utils/api'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const alerts = ref([])
const stats = ref({})
const selectedAlert = ref(null)
const detailModalVisible = ref(false)
const handleModalVisible = ref(false)

// 筛选条件
const filters = reactive({
  alert_level: undefined,
  alert_type: undefined,
  status: undefined,
  is_read: undefined
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 处理表单
const handleForm = reactive({
  handle_note: '',
  status: 'processing'
})

// 计算属性
const hasUnreadAlerts = computed(() => {
  return alerts.value.some(alert => !alert.is_read)
})

// 获取严重预警数量
const getCriticalCount = () => {
  if (!stats.value.alerts_by_level) return 0
  const critical = stats.value.alerts_by_level.find(item => item.alert_level === 'critical')
  return critical ? critical.count : 0
}

// 获取待处理数量
const getPendingCount = () => {
  if (!stats.value.alerts_by_status) return 0
  const pending = stats.value.alerts_by_status.find(item => item.status === 'pending')
  return pending ? pending.count : 0
}

// 获取预警图标
const getAlertIcon = (type) => {
  const iconMap = {
    temperature: FireOutlined,
    humidity: CloudOutlined,
    offline: WifiOutlined,
    maintenance: ToolOutlined
  }
  return iconMap[type] || BellOutlined
}

// 获取预警级别颜色
const getAlertLevelColor = (level) => {
  const colorMap = {
    info: 'blue',
    warning: 'orange',
    critical: 'red'
  }
  return colorMap[level] || 'default'
}

// 获取预警级别文本
const getAlertLevelText = (level) => {
  const textMap = {
    info: '信息',
    warning: '警告',
    critical: '严重'
  }
  return textMap[level] || level
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    pending: 'red',
    processing: 'orange',
    resolved: 'green'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待处理',
    processing: '处理中',
    resolved: '已解决'
  }
  return textMap[status] || status
}

// 获取预警类型文本
const getAlertTypeText = (type) => {
  const textMap = {
    temperature: '温度异常',
    humidity: '湿度异常',
    offline: '设备离线',
    maintenance: '设备维护'
  }
  return textMap[type] || type
}

// 获取设备状态颜色
const getDeviceStatusColor = (status) => {
  const colorMap = {
    normal: 'green',
    warning: 'orange',
    error: 'red',
    offline: 'gray'
  }
  return colorMap[status] || 'default'
}

// 获取设备状态文本
const getDeviceStatusText = (status) => {
  const textMap = {
    normal: '正常',
    warning: '警告',
    error: '错误',
    offline: '离线'
  }
  return textMap[status] || status
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await deviceAlertAPI.getStats()
    if (response.success) {
      stats.value = response.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取预警列表
const fetchAlerts = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...filters
    }
    
    // 移除undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await deviceAlertAPI.getList(params)
    if (response.success) {
      alerts.value = response.data.alerts
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('获取预警列表失败:', error)
    message.error('获取预警列表失败')
  } finally {
    loading.value = false
  }
}

// 筛选变化处理
const handleFilterChange = () => {
  pagination.current = 1
  fetchAlerts()
}

// 分页变化处理
const handlePageChange = (page, pageSize) => {
  pagination.current = page
  pagination.pageSize = pageSize
  fetchAlerts()
}

// 预警点击处理
const handleAlertClick = async (alert) => {
  if (!alert.is_read) {
    await markAsRead(alert)
  }
}

// 标记为已读
const markAsRead = async (alert) => {
  try {
    const response = await deviceAlertAPI.markAsRead(alert.id)
    if (response.success) {
      alert.is_read = true
      alert.read_time = new Date().toISOString()
      message.success('已标记为已读')
      await fetchStats() // 刷新统计数据
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    message.error('标记已读失败')
  }
}

// 全部标记已读
const markAllAsRead = async () => {
  try {
    const response = await deviceAlertAPI.markAllAsRead()
    if (response.success) {
      alerts.value.forEach(alert => {
        alert.is_read = true
        alert.read_time = new Date().toISOString()
      })
      message.success('已全部标记为已读')
      await fetchStats() // 刷新统计数据
    }
  } catch (error) {
    console.error('全部标记已读失败:', error)
    message.error('全部标记已读失败')
  }
}

// 查看详情
const viewDetail = (alert) => {
  selectedAlert.value = alert
  detailModalVisible.value = true
}

// 处理预警
const handleAlert = (alert) => {
  selectedAlert.value = alert
  handleForm.handle_note = ''
  handleForm.status = 'processing'
  handleModalVisible.value = true
}

// 提交处理
const submitHandle = async () => {
  if (!handleForm.handle_note.trim()) {
    message.error('请输入处理备注')
    return
  }
  
  try {
    const response = await deviceAlertAPI.handle(selectedAlert.value.id, handleForm)
    if (response.success) {
      message.success('处理成功')
      handleModalVisible.value = false
      await fetchAlerts()
      await fetchStats()
    }
  } catch (error) {
    console.error('处理失败:', error)
    message.error('处理失败')
  }
}

// 刷新数据
const refreshData = async () => {
  await Promise.all([fetchStats(), fetchAlerts()])
  message.success('数据已刷新')
}

// 导出Excel
const handleExport = async () => {
  try {
    loading.value = true
    const params = {
      ...filters
    }
    
    // 移除undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await deviceAlertAPI.export(params)
    
    // 创建下载链接
    const url = window.URL.createObjectURL(response.data)
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `消息通知_${new Date().getTime()}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    message.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchStats()
  fetchAlerts()
})
</script>

<style scoped>
.message-notification {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.page-header p {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 16px;
}

.stat-icon.total {
  background: #e6f7ff;
  color: #1890ff;
}

.stat-icon.unread {
  background: #fff2e8;
  color: #fa8c16;
}

.stat-icon.critical {
  background: #fff1f0;
  color: #f5222d;
}

.stat-icon.pending {
  background: #f6ffed;
  color: #52c41a;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #262626;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #8c8c8c;
}

.filter-bar {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
}

.alert-list {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.alert-item {
  cursor: pointer;
  transition: all 0.3s;
  border-left: 4px solid transparent;
}

.alert-item:hover {
  background: #fafafa;
}

.alert-item.unread {
  background: #f6ffed;
  border-left-color: #52c41a;
}

.alert-item.alert-critical {
  border-left-color: #f5222d;
}

.alert-item.alert-warning {
  border-left-color: #fa8c16;
}

.alert-item.alert-info {
  border-left-color: #1890ff;
}

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

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

.level-tag,
.status-tag {
  font-size: 12px;
}

.unread-dot {
  width: 8px;
  height: 8px;
  background: #f5222d;
  border-radius: 50%;
  display: inline-block;
}

.alert-description {
  margin-top: 8px;
}

.alert-content {
  margin: 0 0 8px 0;
  color: #595959;
  line-height: 1.5;
}

.alert-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #8c8c8c;
}

.alert-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.avatar-critical {
  background: #f5222d;
}

.avatar-warning {
  background: #fa8c16;
}

.avatar-info {
  background: #1890ff;
}

.alert-detail {
  margin-top: 16px;
}
</style>