<!--报警审核-->
<template>
  <div class="alert-audit-system">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon><Warning /></el-icon>
        <span class="title">报警审核与处置中心</span>
        <div class="stats-badge">
          <span class="stat-item pending"><i class="dot"></i>待审核 {{ pendingCount }}</span>
          <span class="stat-item processing"><i class="dot"></i>处置中 {{ processingCount }}</span>
          <span class="stat-item resolved"><i class="dot"></i>已解除 {{ resolvedCount }}</span>
        </div>
      </div>
      <div class="header-right">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索报警内容/设备名称"
            clearable
            :prefix-icon="Search"
            style="width: 240px"
        />
        <el-select v-model="statusFilter" placeholder="状态筛选" clearable style="width: 120px">
          <el-option label="待审核" value="pending" />
          <el-option label="处置中" value="processing" />
          <el-option label="已解除" value="resolved" />
        </el-select>
        <el-button type="primary" :icon="Refresh" @click="refreshData">刷新</el-button>
      </div>
    </div>

    <!-- 主内容区：左侧报警列表 + 右侧审核面板 -->
    <div class="main-layout">
      <!-- 左侧报警列表 -->
      <div class="alert-list-panel">
        <div class="panel-header">
          <span><el-icon><List /></el-icon> 报警事件列表</span>
          <span class="total-count">共 {{ filteredAlerts.length }} 条</span>
        </div>
        <div class="alert-list">
          <div
              v-for="alert in paginatedAlerts"
              :key="alert.id"
              class="alert-item"
              :class="{
              selected: selectedAlert?.id === alert.id,
              pending: alert.status === 'pending',
              processing: alert.status === 'processing',
              resolved: alert.status === 'resolved'
            }"
              @click="selectAlert(alert)"
          >
            <div class="alert-level">
              <el-tag :type="alert.level === 'critical' ? 'danger' : 'warning'" size="small">
                {{ alert.level === 'critical' ? '严重' : '预警' }}
              </el-tag>
            </div>
            <div class="alert-info">
              <div class="alert-title">{{ alert.deviceName }}</div>
              <div class="alert-desc">{{ alert.ruleName }}: {{ alert.currentValue }}{{ alert.unit }}</div>
              <div class="alert-time">{{ alert.triggerTime }}</div>
            </div>
            <div class="alert-status">
              <el-tag :type="getStatusType(alert.status)" size="small">
                {{ getStatusText(alert.status) }}
              </el-tag>
            </div>
          </div>
        </div>
        <div class="pagination-area">
          <el-pagination
              small
              layout="prev, pager, next"
              :total="filteredAlerts.length"
              :page-size="pageSize"
              v-model:current-page="currentPage"
          />
        </div>
      </div>

      <!-- 右侧审核处置面板 -->
      <div class="audit-panel" v-if="selectedAlert">
        <div class="panel-header">
          <span><el-icon><Checked /></el-icon> 报警审核与处置</span>
          <el-tag :type="getStatusType(selectedAlert.status)" size="large">
            {{ getStatusText(selectedAlert.status) }}
          </el-tag>
        </div>

        <!-- 报警基本信息 -->
        <div class="alert-basic">
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="设备名称">{{ selectedAlert.deviceName }}</el-descriptions-item>
            <el-descriptions-item label="设备编号">{{ selectedAlert.deviceCode }}</el-descriptions-item>
            <el-descriptions-item label="报警规则">{{ selectedAlert.ruleName }}</el-descriptions-item>
            <el-descriptions-item label="报警级别">
              <el-tag :type="selectedAlert.level === 'critical' ? 'danger' : 'warning'" size="small">
                {{ selectedAlert.level === 'critical' ? '严重报警' : '预警' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="当前值">{{ selectedAlert.currentValue }} {{ selectedAlert.unit }}</el-descriptions-item>
            <el-descriptions-item label="报警阈值">{{ selectedAlert.threshold }} {{ selectedAlert.unit }}</el-descriptions-item>
            <el-descriptions-item label="触发时间">{{ selectedAlert.triggerTime }}</el-descriptions-item>
            <el-descriptions-item label="报警位置">{{ selectedAlert.location }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 审核/处置操作区（根据状态显示不同内容） -->
        <div class="action-section" v-if="selectedAlert.status === 'pending'">
          <div class="section-title">审核结果</div>
          <el-radio-group v-model="auditResult" class="audit-options">
            <el-radio value="confirm">确认为真报警</el-radio>
            <el-radio value="false_alarm">误报警</el-radio>
            <el-radio value="uncertain">需现场核实</el-radio>
          </el-radio-group>

          <div class="section-title">审核意见</div>
          <el-input
              type="textarea"
              v-model="auditOpinion"
              placeholder="请输入审核意见..."
              rows="3"
              maxlength="500"
              show-word-limit
          />

          <div class="section-title">附件上传</div>
          <el-upload
              class="upload-area"
              drag
              action="#"
              :auto-upload="false"
              :file-list="uploadFiles"
              :on-change="handleFileChange"
              multiple
          >
            <el-icon class="upload-icon"><Upload /></el-icon>
            <div class="upload-text">点击或拖拽上传相关附件（现场照片、检测报告等）</div>
          </el-upload>

          <div class="action-buttons">
            <el-button type="primary" @click="submitAudit">提交审核</el-button>
            <el-button @click="resetAuditForm">重置</el-button>
          </div>
        </div>

        <!-- 处置操作区（待现场核实状态） -->
        <div class="action-section" v-if="selectedAlert.status === 'processing'">
          <div class="section-title">处置操作</div>
          <el-radio-group v-model="disposeResult" class="dispose-options">
            <el-radio value="resolved">处置完成，解除报警</el-radio>
            <el-radio value="pending_repair">已派修，待修复</el-radio>
            <el-radio value="monitoring">持续监测中</el-radio>
          </el-radio-group>

          <div class="section-title">处置说明</div>
          <el-input
              type="textarea"
              v-model="disposeRemark"
              placeholder="请输入现场处置情况说明..."
              rows="3"
          />

          <div class="section-title">现场照片/证据</div>
          <el-upload
              class="upload-area"
              drag
              action="#"
              :auto-upload="false"
              :file-list="disposeFiles"
              :on-change="handleDisposeFileChange"
              multiple
          >
            <el-icon class="upload-icon"><Camera /></el-icon>
            <div class="upload-text">点击或拖拽上传现场处置照片</div>
          </el-upload>

          <div class="action-buttons">
            <el-button type="primary" @click="submitDispose">提交处置结果</el-button>
            <el-button @click="resetDisposeForm">重置</el-button>
          </div>
        </div>

        <!-- 已解除/已完成状态 -->
        <div class="completed-section" v-if="selectedAlert.status === 'resolved'">
          <el-alert
              :title="`报警已${selectedAlert.resolvedType === 'false_alarm' ? '排除（误报警）' : '处置解除'}`"
              type="success"
              show-icon
              :closable="false"
          />
          <div class="resolve-info">
            <div><strong>审核/处置结果：</strong>{{ selectedAlert.resolvedTypeName }}</div>
            <div><strong>意见说明：</strong>{{ selectedAlert.resolvedOpinion }}</div>
            <div v-if="selectedAlert.attachments?.length" class="attachments">
              <strong>附件：</strong>
              <div v-for="file in selectedAlert.attachments" :key="file.name" class="attachment-item">
                <el-icon><Document /></el-icon>
                <span>{{ file.name }}</span>
                <el-button link type="primary" size="small">下载</el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 处置跟踪时间轴 -->
        <div class="timeline-section">
          <div class="section-title">处置跟踪记录</div>
          <el-timeline>
            <el-timeline-item
                v-for="record in selectedAlert.processRecords"
                :key="record.id"
                :timestamp="record.time"
                :type="record.type"
                :hollow="true"
            >
              <div class="timeline-content">
                <strong>{{ record.operator }}</strong> - {{ record.action }}
                <div class="timeline-desc">{{ record.remark }}</div>
                <div v-if="record.attachments?.length" class="timeline-attachments">
                  附件: {{ record.attachments.map(f => f.name).join(', ') }}
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>

      <!-- 未选中状态 -->
      <div v-else class="empty-panel">
        <el-empty description="请从左侧选择报警事件进行审核处置" :image-size="140" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Warning, Search, Refresh, List, Checked, Upload, Camera, Document } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 模拟报警数据
const alerts = ref([
  {
    id: 1, deviceName: '世纪大道流量计', deviceCode: 'FM-001', ruleName: '流量异常',
    currentValue: 1350, threshold: 1200, unit: 'm³/h', level: 'warning',
    triggerTime: '2025-04-02 15:23:45', location: '世纪大道福山路口',
    status: 'pending', // pending, processing, resolved
    processRecords: [
      { id: 1, time: '2025-04-02 15:23:45', operator: '系统', action: '报警触发', type: 'danger', remark: '流量1350m³/h超过阈值1200m³/h' }
    ],
    attachments: [], resolvedType: null, resolvedTypeName: null, resolvedOpinion: null
  },
  {
    id: 2, deviceName: '人民广场气体监测仪', deviceCode: 'CH4-001', ruleName: '甲烷浓度超标',
    currentValue: 28, threshold: 20, unit: 'ppm', level: 'critical',
    triggerTime: '2025-04-02 15:18:22', location: '人民大道200号',
    status: 'processing',
    processRecords: [
      { id: 1, time: '2025-04-02 15:18:22', operator: '系统', action: '报警触发', type: 'danger', remark: '甲烷浓度28ppm超过阈值20ppm' },
      { id: 2, time: '2025-04-02 15:35:00', operator: '张建国', action: '审核确认为真报警，已派发现场核实', type: 'warning', remark: '已通知抢修队前往现场' }
    ],
    attachments: [], resolvedType: null, resolvedTypeName: null, resolvedOpinion: null
  },
  {
    id: 3, deviceName: '张杨路水位计', deviceCode: 'WL-003', ruleName: '水位超限',
    currentValue: 45, threshold: 40, unit: 'cm', level: 'critical',
    triggerTime: '2025-04-02 14:55:10', location: '张杨路松林路口',
    status: 'resolved',
    processRecords: [
      { id: 1, time: '2025-04-02 14:55:10', operator: '系统', action: '报警触发', type: 'danger', remark: '水位45cm超过阈值40cm' },
      { id: 2, time: '2025-04-02 15:10:00', operator: '李志强', action: '审核确认为真报警', type: 'warning', remark: '已通知排水部门' },
      { id: 3, time: '2025-04-02 15:45:00', operator: '李志强', action: '处置完成，报警解除', type: 'success', remark: '现场排水完成，水位恢复正常' }
    ],
    attachments: [{ name: '现场照片_001.jpg', url: '' }],
    resolvedType: 'resolved', resolvedTypeName: '处置完成', resolvedOpinion: '现场排水作业完成，设备运行正常'
  },
  {
    id: 4, deviceName: '东方路压力监测仪', deviceCode: 'PR-003', ruleName: '管道压力异常',
    currentValue: 285, threshold: 300, unit: 'kPa', level: 'warning',
    triggerTime: '2025-04-02 14:30:05', location: '东方路蓝村路口',
    status: 'pending',
    processRecords: [
      { id: 1, time: '2025-04-02 14:30:05', operator: '系统', action: '报警触发', type: 'danger', remark: '压力285kPa低于阈值300kPa' }
    ],
    attachments: [], resolvedType: null, resolvedTypeName: null, resolvedOpinion: null
  }
])

// 统计数据
const pendingCount = computed(() => alerts.value.filter(a => a.status === 'pending').length)
const processingCount = computed(() => alerts.value.filter(a => a.status === 'processing').length)
const resolvedCount = computed(() => alerts.value.filter(a => a.status === 'resolved').length)

// 筛选
const searchKeyword = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = 5
const selectedAlert = ref(alerts.value[0])

// 审核表单
const auditResult = ref('confirm')
const auditOpinion = ref('')
const uploadFiles = ref([])

// 处置表单
const disposeResult = ref('resolved')
const disposeRemark = ref('')
const disposeFiles = ref([])

const filteredAlerts = computed(() => {
  let list = alerts.value
  if (statusFilter.value) {
    list = list.filter(a => a.status === statusFilter.value)
  }
  if (searchKeyword.value) {
    const kw = searchKeyword.value.toLowerCase()
    list = list.filter(a => a.deviceName.toLowerCase().includes(kw) || a.ruleName.toLowerCase().includes(kw))
  }
  return list
})

const paginatedAlerts = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  return filteredAlerts.value.slice(start, start + pageSize)
})

const getStatusType = (status) => {
  const map = { pending: 'danger', processing: 'warning', resolved: 'success' }
  return map[status]
}
const getStatusText = (status) => {
  const map = { pending: '待审核', processing: '处置中', resolved: '已解除' }
  return map[status]
}

const selectAlert = (alert) => {
  selectedAlert.value = alert
  resetAuditForm()
  resetDisposeForm()
}

const resetAuditForm = () => {
  auditResult.value = 'confirm'
  auditOpinion.value = ''
  uploadFiles.value = []
}

const resetDisposeForm = () => {
  disposeResult.value = 'resolved'
  disposeRemark.value = ''
  disposeFiles.value = []
}

const handleFileChange = (file, fileList) => {
  uploadFiles.value = fileList
}
const handleDisposeFileChange = (file, fileList) => {
  disposeFiles.value = fileList
}

// 提交审核
const submitAudit = () => {
  if (!auditOpinion.value) {
    ElMessage.warning('请填写审核意见')
    return
  }
  const alert = selectedAlert.value
  const resultMap = {
    confirm: { nextStatus: 'processing', typeName: '确认为真报警', action: '审核确认为真报警' },
    false_alarm: { nextStatus: 'resolved', typeName: '误报警', action: '审核为误报警，报警解除' },
    uncertain: { nextStatus: 'processing', typeName: '需现场核实', action: '审核为需现场核实，已派单' }
  }
  const result = resultMap[auditResult.value]

  // 添加处置记录
  alert.processRecords.push({
    id: Date.now(),
    time: new Date().toLocaleString(),
    operator: '审核员',
    action: result.action,
    type: auditResult.value === 'false_alarm' ? 'success' : 'warning',
    remark: auditOpinion.value,
    attachments: uploadFiles.value
  })

  alert.status = result.nextStatus
  if (auditResult.value === 'false_alarm') {
    alert.resolvedType = 'false_alarm'
    alert.resolvedTypeName = '误报警'
    alert.resolvedOpinion = auditOpinion.value
    alert.attachments = uploadFiles.value
  }

  ElMessage.success(`审核完成：${result.typeName}`)
  resetAuditForm()
}

// 提交处置结果
const submitDispose = () => {
  if (!disposeRemark.value) {
    ElMessage.warning('请填写处置说明')
    return
  }
  const alert = selectedAlert.value
  const resultMap = {
    resolved: { nextStatus: 'resolved', typeName: '处置完成，解除报警', action: '现场处置完成，报警解除' },
    pending_repair: { nextStatus: 'processing', typeName: '已派修，待修复', action: '已派维修人员，待修复' },
    monitoring: { nextStatus: 'processing', typeName: '持续监测中', action: '现场情况稳定，持续监测' }
  }
  const result = resultMap[disposeResult.value]

  alert.processRecords.push({
    id: Date.now(),
    time: new Date().toLocaleString(),
    operator: '处置人员',
    action: result.action,
    type: disposeResult.value === 'resolved' ? 'success' : 'warning',
    remark: disposeRemark.value,
    attachments: disposeFiles.value
  })

  if (disposeResult.value === 'resolved') {
    alert.status = 'resolved'
    alert.resolvedType = 'resolved'
    alert.resolvedTypeName = '处置完成'
    alert.resolvedOpinion = disposeRemark.value
    alert.attachments = disposeFiles.value
  }

  ElMessage.success(`处置提交：${result.typeName}`)
  resetDisposeForm()
}

const refreshData = () => { ElMessage.success('数据已刷新') }
</script>

<style scoped>
.alert-audit-system {
  background: #f0f2f6;
  min-height: 100vh;
  padding: 20px;
}
.page-header {
  background: white;
  border-radius: 16px;
  padding: 16px 24px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-left { display: flex; align-items: center; gap: 20px; }
.header-left .title { font-size: 1.3rem; font-weight: 600; }
.stats-badge { display: flex; gap: 20px; }
.stat-item { font-size: 13px; display: flex; align-items: center; gap: 6px; }
.stat-item.pending { color: #f56c6c; }
.stat-item.processing { color: #e6a23c; }
.stat-item.resolved { color: #67c23a; }
.stat-item .dot { width: 8px; height: 8px; border-radius: 50%; }
.stat-item.pending .dot { background: #f56c6c; }
.stat-item.processing .dot { background: #e6a23c; }
.stat-item.resolved .dot { background: #67c23a; }
.header-right { display: flex; gap: 12px; }

.main-layout {
  display: flex;
  gap: 20px;
}
.alert-list-panel {
  width: 380px;
  background: white;
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.panel-header {
  padding: 16px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}
.alert-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  max-height: calc(100vh - 280px);
}
.alert-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 12px;
  background: #fafbfc;
  border: 1px solid #e9ecef;
  cursor: pointer;
  transition: all 0.2s;
}
.alert-item.selected { background: #ecf5ff; border-color: #409eff; }
.alert-item.pending { border-left: 3px solid #f56c6c; }
.alert-item.processing { border-left: 3px solid #e6a23c; }
.alert-item.resolved { border-left: 3px solid #67c23a; }
.alert-info { flex: 1; }
.alert-title { font-weight: 600; margin-bottom: 4px; }
.alert-desc { font-size: 12px; color: #606266; }
.alert-time { font-size: 11px; color: #aaa; margin-top: 4px; }

.audit-panel {
  flex: 1;
  background: white;
  border-radius: 16px;
  padding: 20px;
  overflow-y: auto;
  max-height: calc(100vh - 180px);
}
.empty-panel {
  flex: 1;
  background: white;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.section-title { font-weight: 600; margin: 20px 0 12px 0; font-size: 14px; }
.audit-options, .dispose-options { display: flex; gap: 20px; margin-bottom: 8px; }
.upload-area { margin: 8px 0; }
.upload-icon { font-size: 32px; color: #c0c4cc; margin-bottom: 8px; }
.upload-text { font-size: 12px; color: #909399; }
.action-buttons { display: flex; gap: 12px; margin-top: 20px; justify-content: flex-end; }
.completed-section { margin: 20px 0; }
.resolve-info { margin-top: 16px; padding: 12px; background: #f5f7fa; border-radius: 8px; }
.attachments { margin-top: 8px; }
.attachment-item { display: flex; align-items: center; gap: 8px; margin-top: 6px; }

.timeline-section { margin-top: 24px; border-top: 1px solid #e9ecef; padding-top: 16px; }
.timeline-content { font-size: 13px; }
.timeline-desc { font-size: 12px; color: #909399; margin-top: 4px; }
.timeline-attachments { font-size: 11px; color: #409eff; margin-top: 4px; }

.pagination-area { padding: 12px; text-align: center; border-top: 1px solid #eee; }
</style>