<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" class="search-form">
      <el-form-item label="设备名称">
        <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable style="width: 180px" />
      </el-form-item>
      <el-form-item label="告警等级">
        <el-select v-model="queryParams.alarmLevel" placeholder="请选择" clearable style="width: 160px">
          <el-option label="最高" :value="1" />
          <el-option label="高" :value="2" />
          <el-option label="中" :value="3" />
          <el-option label="低" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="处理状态">
        <el-select v-model="queryParams.alarmStatus" placeholder="请选择" clearable style="width: 140px">
          <el-option label="未处理" :value="0" />
          <el-option label="已处理" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" v-loading="loading" border style="width: 100%" size="default">
      <el-table-column label="设备名称" prop="deviceName" min-width="130" show-overflow-tooltip />
      <el-table-column label="设备编码" prop="deviceCode" min-width="120" show-overflow-tooltip />
      <el-table-column label="设备类型" prop="deviceType" min-width="100" show-overflow-tooltip />
      <el-table-column label="预警类型" prop="warningType" min-width="100" show-overflow-tooltip />
      <el-table-column label="实际值" prop="actualValue" min-width="80" align="center" />
      <el-table-column label="阈值范围" min-width="130" align="center">
        <template #default="{ row }">
          {{ row.minValue ?? '-' }} ~ {{ row.maxValue ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column label="告警等级" min-width="90" align="center">
        <template #default="{ row }">
          <span :class="levelClass(row.alarmLevel)">{{ levelText(row.alarmLevel) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="处理状态" min-width="90" align="center">
        <template #default="{ row }">
          <el-tag :type="statusTagType(row.alarmStatus)" size="small" effect="plain">{{ statusText(row.alarmStatus) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="报警时间" prop="alarmTime" min-width="160" />
      <el-table-column label="处理人" prop="handleUser" min-width="90" show-overflow-tooltip />
      <el-table-column label="处理时间" prop="handleTime" min-width="160" />
      <el-table-column label="操作" width="80" align="center" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleView(row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 查看详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="报警详情" width="680px" :before-close="handleClose">
      <div class="detail-panel">
        <div class="detail-top">
          <div class="detail-image">
            <el-icon :size="48" color="#b0c4de"><Monitor /></el-icon>
          </div>
          <div class="detail-info">
            <div class="detail-number">编号: {{ currentRow.id }}</div>
            <el-row :gutter="16">
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">设备名称</span>
                  <span class="info-value">{{ currentRow.deviceName || '-' }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">设备编码</span>
                  <span class="info-value">{{ currentRow.deviceCode || '-' }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">设备类型</span>
                  <span class="info-value">{{ currentRow.deviceType || '-' }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">预警类型</span>
                  <span class="info-value">{{ currentRow.warningType || '-' }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">实际值</span>
                  <span class="info-value">{{ currentRow.actualValue ?? '-' }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">阈值范围</span>
                  <span class="info-value">{{ currentRow.minValue ?? '-' }} ~ {{ currentRow.maxValue ?? '-' }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">告警等级</span>
                  <span class="info-value">
                    <span :class="levelClass(currentRow.alarmLevel)">{{ levelText(currentRow.alarmLevel) }}</span>
                  </span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">处理状态</span>
                  <span class="info-value">
                    <el-tag :type="statusTagType(currentRow.alarmStatus)" size="small" effect="plain">{{ statusText(currentRow.alarmStatus) }}</el-tag>
                  </span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">报警时间</span>
                  <span class="info-value">{{ currentRow.alarmTime || '-' }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">偏离比率</span>
                  <span class="info-value">{{ currentRow.deviationRatio ?? '-' }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">处理人</span>
                  <span class="info-value">{{ currentRow.handleUser || '-' }}</span>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <span class="info-label">处理时间</span>
                  <span class="info-value">{{ currentRow.handleTime || '-' }}</span>
                </div>
              </el-col>
            </el-row>
            <div class="info-item desc-item" v-if="currentRow.handleRemark">
              <span class="info-label">处理备注</span>
              <span class="info-value desc-text">{{ currentRow.handleRemark }}</span>
            </div>
            <div class="info-item desc-item" v-if="currentRow.remark">
              <span class="info-label">备注</span>
              <span class="info-value desc-text">{{ currentRow.remark }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Bjqd">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Monitor } from '@element-plus/icons-vue'
import { getAlarmDataPage } from '@/api/drainage'

// ==================== 搜索参数 ====================
const queryParams = ref({
  deviceName: '',
  alarmLevel: '',
  alarmStatus: '',
  dateRange: []
})
const queryRef = ref(null)

function handleQuery() {
  pageNum.value = 1
  loadData()
}

function resetQuery() {
  queryParams.value = { deviceName: '', alarmLevel: '', alarmStatus: '', dateRange: [] }
  pageNum.value = 1
  loadData()
}

// ==================== 等级/状态映射（alarm_data表） ====================
const levelMap = { 1: '最高', 2: '高', 3: '中', 4: '低' }
const statusMap = { 0: '未处理', 1: '已处理' }

function levelText(level) {
  return levelMap[level] || '-'
}
function levelClass(level) {
  const map = { 1: 'level-critical', 2: 'level-major', 3: 'level-minor', 4: 'level-low' }
  return map[level] || ''
}
function statusText(status) {
  return statusMap[status] ?? '-'
}
function statusTagType(status) {
  const map = { 0: 'warning', 1: 'success' }
  return map[status] || 'info'
}

// ==================== 表格数据（服务端分页） ====================
const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)

async function loadData() {
  loading.value = true
  try {
    const params = { equipmentType: 'drainage' }
    if (queryParams.value.deviceName) params.deviceName = queryParams.value.deviceName
    if (queryParams.value.alarmLevel !== '' && queryParams.value.alarmLevel !== null) params.alarmLevel = queryParams.value.alarmLevel
    if (queryParams.value.alarmStatus !== '' && queryParams.value.alarmStatus !== null) params.alarmStatus = queryParams.value.alarmStatus
    if (queryParams.value.dateRange && queryParams.value.dateRange.length === 2) {
      params.startTime = queryParams.value.dateRange[0]
      params.endTime = queryParams.value.dateRange[1]
    }

    const res = await getAlarmDataPage(pageNum.value, pageSize.value, params)
    const pageData = res.code !== undefined ? res.data : res
    tableData.value = pageData.records || pageData.rows || []
    total.value = pageData.total || 0
  } catch (error) {
    console.error('加载报警清单失败', error)
    ElMessage.error('加载报警清单失败')
  } finally {
    loading.value = false
  }
}

function handlePageChange() {
  loadData()
}

function handleSizeChange() {
  pageNum.value = 1
  loadData()
}

// ==================== 查看详情 ====================
const dialogVisible = ref(false)
const currentRow = ref({})

function handleView(row) {
  currentRow.value = { ...row }
  dialogVisible.value = true
}

function handleClose() {
  dialogVisible.value = false
}

// ==================== 生命周期 ====================
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background: #fff;
  min-height: calc(100vh - 84px);
}

.search-form {
  margin-bottom: 16px;
  padding: 16px 16px 0;
  background: #f5f7fa;
  border-radius: 6px;
}

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

/* 等级彩色文字 */
.level-critical {
  color: #f56c6c;
  font-weight: 700;
}

.level-major {
  color: #e6a23c;
  font-weight: 700;
}

.level-minor {
  color: #409eff;
  font-weight: 600;
}

.level-low {
  color: #67c238;
  font-weight: 600;
}

/* 详情弹窗 */
.detail-panel {
  padding: 0 4px;
}

.detail-top {
  display: flex;
  gap: 24px;
}

.detail-image {
  width: 150px;
  height: 150px;
  flex-shrink: 0;
  background: #dce6f0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #c0cfe0;
}

.detail-info {
  flex: 1;
}

.detail-number {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 14px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  line-height: 22px;
}

.info-label {
  color: #909399;
  font-size: 14px;
  white-space: nowrap;
  min-width: 65px;
  flex-shrink: 0;
}

.info-value {
  color: #303133;
  font-size: 14px;
  flex: 1;
}

.desc-item {
  align-items: flex-start;
}

.desc-text {
  line-height: 22px;
  color: #606266;
}

/* 底部操作区 */
.detail-footer {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.dispatch-row {
  display: flex;
  align-items: center;
}

.dispatch-label {
  font-size: 14px;
  color: #303133;
  font-weight: 600;
  white-space: nowrap;
}
</style>
