<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <!-- 报警点管理标签页 -->
      <el-tab-pane label="报警点管理" name="alarmPoints">
        <el-form :model="alarmPointQuery" ref="alarmPointQueryRef" :inline="true" label-width="80px">
          <el-form-item label="设备编号" prop="deviceCode">
            <el-input v-model="alarmPointQuery.deviceCode" placeholder="请输入设备编号" clearable />
          </el-form-item>
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="alarmPointQuery.deviceName" placeholder="请输入设备名称" clearable />
          </el-form-item>
          <el-form-item label="报警类型" prop="alarmType">
            <el-select v-model="alarmPointQuery.alarmType" placeholder="请选择报警类型" clearable style="width: 180px;">
              <el-option label="入侵检测" value="intrusion" />
              <el-option label="门磁报警" value="door_magnetic" />
              <el-option label="红外探测" value="infrared" />
              <el-option label="玻璃破碎" value="glass_break" />
              <el-option label="震动检测" value="vibration" />
            </el-select>
          </el-form-item>
          <el-form-item label="防区" prop="zone">
            <el-select v-model="alarmPointQuery.zone" placeholder="请选择防区" clearable style="width: 180px;">
              <el-option label="防区1" value="zone1" />
              <el-option label="防区2" value="zone2" />
              <el-option label="防区3" value="zone3" />
              <el-option label="防区4" value="zone4" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备状态" prop="deviceStatus">
            <el-select v-model="alarmPointQuery.deviceStatus" placeholder="请选择状态" clearable style="width: 180px;">
              <el-option label="正常" :value="1" />
              <el-option label="报警" :value="2" />
              <el-option label="故障" :value="3" />
              <el-option label="离线" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getAlarmPointList">搜索</el-button>
            <el-button icon="Refresh" @click="resetAlarmPointQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="alarmPointLoading" :data="alarmPointList" stripe border>
          <el-table-column label="设备编号" prop="deviceCode"  />
          <el-table-column label="设备名称" prop="deviceName"  />
          <el-table-column label="报警类型" prop="alarmType">
            <template #default="scope">
              <el-tag :type="getAlarmTypeTag(scope.row.alarmType)">
                {{ getAlarmTypeText(scope.row.alarmType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="防区信息" >
            <template #default="scope">
              <div>{{ scope.row.zoneName }}</div>
              <div class="text-gray-500">{{ scope.row.zoneCode }}</div>
            </template>
          </el-table-column>
          <el-table-column label="位置信息" >
            <template #default="scope">
              <div>{{ scope.row.building }}栋-{{ scope.row.floor }}层</div>
              <div class="text-gray-500">{{ scope.row.locationDetail }}</div>
            </template>
          </el-table-column>
          <el-table-column label="设备状态" prop="device_status" >
            <template #default="scope">
              <el-tag :type="getDeviceStatusTag(scope.row.deviceStatus)">
                {{ getDeviceStatusText(scope.row.deviceStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="布防状态" prop="armStatus" >
            <template #default="scope">
              <el-tag :type="scope.row.armStatus === 1 ? 'success' : 'info'">
                {{ scope.row.armStatus === 1 ? '布防' : '撤防' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="敏感度" prop="sensitivity" width="80">
            <template #default="scope">
              <span>{{ scope.row.sensitivity }}%</span>
            </template>
          </el-table-column>
          <el-table-column label="最后报警时间" prop="lastAlarmTime">
            <template #default="scope">
              <span>{{ parseTime(scope.row.lastAlarmTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="340" fixed="right">
            <template #default="scope">
              <el-button link type="primary" icon="View" @click="handleAlarmPointDetail(scope.row)">详情</el-button>
              <el-button
                  link
                  :type="scope.row.armStatus === 1 ? 'warning' : 'success'"
                  icon="Switch"
                  @click="handleToggleArm(scope.row)"
              >
                {{ scope.row.armStatus === 1 ? '撤防' : '布防' }}
              </el-button>
              <el-button link type="info" icon="Setting" @click="handleDeviceConfig(scope.row)">配置</el-button>
              <el-button link type="danger" icon="Bell" @click="handleTestAlarm(scope.row)">测试</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="alarmPointTotal > 0"
            :total="alarmPointTotal"
            v-model:page="alarmPointQuery.pageNum"
            v-model:limit="alarmPointQuery.pageSize"
            @pagination="getAlarmPointList"
        />
      </el-tab-pane>

      <!-- 实时报警标签页 -->
      <el-tab-pane label="实时报警" name="realTimeAlarms">
        <el-form :model="alarmQuery" ref="alarmQueryRef" :inline="true" label-width="80px">
          <el-form-item label="报警级别" prop="alarmLevel">
            <el-select v-model="alarmQuery.alarmLevel" placeholder="请选择报警级别" clearable style="width: 180px;">
              <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="处理状态" prop="handleStatus">
            <el-select v-model="alarmQuery.handleStatus" placeholder="请选择处理状态" clearable style="width: 180px;">
              <el-option label="未处理" :value="0" />
              <el-option label="处理中" :value="1" />
              <el-option label="已处理" :value="2" />
              <el-option label="已忽略" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="防区" prop="zone">
            <el-select v-model="alarmQuery.zone" placeholder="请选择防区" clearable style="width: 180px;">
              <el-option label="防区1" value="zone1" />
              <el-option label="防区2" value="zone2" />
              <el-option label="防区3" value="zone3" />
              <el-option label="防区4" value="zone4" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围" prop="timeRange">
            <el-date-picker
                v-model="alarmQuery.timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getAlarmList">搜索</el-button>
            <el-button icon="Refresh" @click="resetAlarmQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="20" class="mb8">
          <el-col :span="6">
            <el-statistic title="今日报警数" :value="statisticsData.todayAlarms" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="未处理报警" :value="statisticsData.unhandledAlarms" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="在线设备" :value="statisticsData.onlineDevices" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="布防防区" :value="statisticsData.armedZones" />
          </el-col>
        </el-row>

        <el-table v-loading="alarmLoading" :data="alarmList" stripe border>
          <el-table-column label="报警时间" prop="alarm_time" >
            <template #default="scope">
              <span>{{ parseTime(scope.row.alarm_time) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设备信息" >
            <template #default="scope">
              <div>{{ scope.row.device_name }}</div>
              <div class="text-gray-500">{{ scope.row.device_code }}</div>
            </template>
          </el-table-column>
          <el-table-column label="报警类型" prop="alarm_type" >
            <template #default="scope">
              <el-tag :type="getAlarmTypeTag(scope.row.alarm_type)">
                {{ getAlarmTypeText(scope.row.alarm_type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="报警级别" prop="alarm_level">
            <template #default="scope">
              <el-tag :type="getAlarmLevelTag(scope.row.alarm_level)">
                {{ getAlarmLevelText(scope.row.alarm_level) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="位置信息">
            <template #default="scope">
              <div>{{ scope.row.building }}栋-{{ scope.row.floor }}层</div>
              <div class="text-gray-500">{{ scope.row.zone_name }}</div>
            </template>
          </el-table-column>
          <el-table-column label="报警内容" prop="alarm_message" width="200" show-overflow-tooltip />
          <el-table-column label="处理状态" prop="handle_status" width="100">
            <template #default="scope">
              <el-tag :type="getHandleStatusTag(scope.row.handle_status)">
                {{ getHandleStatusText(scope.row.handle_status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="处理人" prop="handle_user"  />
          <el-table-column label="联动状态" prop="linkage_status">
            <template #default="scope">
              <el-tag :type="scope.row.linkage_status === 1 ? 'success' : 'info'">
                {{ scope.row.linkage_status === 1 ? '已联动' : '未联动' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button link type="primary" icon="View" @click="handleAlarmDetail(scope.row)">详情</el-button>
              <el-button
                  link
                  type="warning"
                  icon="Edit"
                  @click="handleAlarmProcess(scope.row)"
                  v-if="scope.row.handle_status === 0 || scope.row.handle_status === 1"
              >处理</el-button>
              <el-button link type="success" icon="VideoCamera" @click="handleViewVideo(scope.row)">查看视频</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="alarmTotal > 0"
            :total="alarmTotal"
            v-model:page="alarmQuery.pageNum"
            v-model:limit="alarmQuery.pageSize"
            @pagination="getAlarmList"
        />
      </el-tab-pane>

      <!-- 防区管理标签页 -->
      <el-tab-pane label="防区管理" name="zones">
        <el-form :model="zoneQuery" ref="zoneQueryRef" :inline="true" label-width="80px">
          <el-form-item label="防区名称" prop="zoneName">
            <el-input v-model="zoneQuery.zoneName" placeholder="请输入防区名称" clearable />
          </el-form-item>
          <el-form-item label="防区状态" prop="zoneStatus">
            <el-select v-model="zoneQuery.zoneStatus" placeholder="请选择状态" clearable style="width: 180px;">
              <el-option label="布防" :value="1" />
              <el-option label="撤防" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getZoneList">搜索</el-button>
            <el-button icon="Refresh" @click="resetZoneQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAddZone">新增防区</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Upload" @click="handleBatchArm">批量布防</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleBatchDisarm">批量撤防</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="zoneLoading" :data="zoneList" stripe border @selection-change="handleZoneSelectionChange">
          <el-table-column type="selection" width="65" />
          <el-table-column label="防区编号" prop="zone_code"  />
          <el-table-column label="防区名称" prop="zone_name"  />
          <el-table-column label="防区描述" prop="zone_description"  show-overflow-tooltip />
          <el-table-column label="防区状态" prop="zone_status">
            <template #default="scope">
              <el-tag :type="scope.row.zone_status === 1 ? 'success' : 'info'">
                {{ scope.row.zone_status === 1 ? '布防' : '撤防' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="设备数量" prop="deviceCount" >
            <template #default="scope">
              <span>{{ scope.row.device_count }}台</span>
            </template>
          </el-table-column>
          <el-table-column label="在线设备" prop="online_count">
            <template #default="scope">
              <span>{{ scope.row.online_count }}/{{ scope.row.device_count }}</span>
            </template>
          </el-table-column>
          <el-table-column label="联动摄像机" prop="linkage_cameras"  show-overflow-tooltip />
          <el-table-column label="创建时间" prop="create_time">
            <template #default="scope">
              <span>{{ parseTime(scope.row.create_time) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="340" fixed="right">
            <template #default="scope">
              <el-button link type="primary" icon="View" @click="handleZoneDetail(scope.row)">详情</el-button>
              <el-button link type="success" icon="Edit" @click="handleEditZone(scope.row)">修改</el-button>
              <el-button
                  link
                  :type="scope.row.zone_status === 1 ? 'warning' : 'success'"
                  icon="Switch"
                  @click="handleToggleZone(scope.row)"
              >
                {{ scope.row.zone_status === 1 ? '撤防' : '布防' }}
              </el-button>
              <el-button link type="danger" icon="Delete" @click="handleDeleteZone(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="zoneTotal > 0"
            :total="zoneTotal"
            v-model:page="zoneQuery.pageNum"
            v-model:limit="zoneQuery.pageSize"
            @pagination="getZoneList"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 报警点详情抽屉 -->
    <el-drawer v-model="alarmPointDetailVisible" title="报警点详情" direction="rtl" size="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备编号">{{ currentAlarmPoint.deviceCode }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ currentAlarmPoint.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="报警类型">{{ getAlarmTypeText(currentAlarmPoint.alarmType) }}</el-descriptions-item>
        <el-descriptions-item label="防区">{{ currentAlarmPoint.zoneName }}</el-descriptions-item>
        <el-descriptions-item label="位置">{{ currentAlarmPoint.building }}栋-{{ currentAlarmPoint.floor }}层-{{ currentAlarmPoint.locationDetail }}</el-descriptions-item>
        <el-descriptions-item label="品牌型号">{{ currentAlarmPoint.brand }} {{ currentAlarmPoint.model }}</el-descriptions-item>
        <el-descriptions-item label="设备状态">
          <el-tag :type="getDeviceStatusTag(currentAlarmPoint.deviceStatus)">
            {{ getDeviceStatusText(currentAlarmPoint.deviceStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="布防状态">
          <el-tag :type="currentAlarmPoint.armStatus === 1 ? 'success' : 'info'">
            {{ currentAlarmPoint.armStatus === 1 ? '布防' : '撤防' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="敏感度">{{ currentAlarmPoint.sensitivity }}%</el-descriptions-item>
        <el-descriptions-item label="延时时间">{{ currentAlarmPoint.delayTime }}秒</el-descriptions-item>
        <el-descriptions-item label="联动摄像机">{{ currentAlarmPoint.linkageCameras }}</el-descriptions-item>
        <el-descriptions-item label="最后报警时间">{{ parseTime(currentAlarmPoint.lastAlarmTime) }}</el-descriptions-item>
        <el-descriptions-item label="安装时间">{{ parseTime(currentAlarmPoint.installTime) }}</el-descriptions-item>
        <el-descriptions-item label="最后维护时间">{{ parseTime(currentAlarmPoint.lastMaintainTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>

    <!-- 报警详情抽屉 -->
    <el-drawer v-model="alarmDetailVisible" title="报警详情" direction="rtl" size="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="报警时间">{{ parseTime(currentAlarm.last_alarm_time) }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ currentAlarm.device_name }}</el-descriptions-item>
        <el-descriptions-item label="设备编号">{{ currentAlarm.device_code }}</el-descriptions-item>
        <el-descriptions-item label="报警类型">{{ getAlarmTypeText(currentAlarm.alarm_type) }}</el-descriptions-item>
        <el-descriptions-item label="报警级别">
          <el-tag :type="getAlarmLevelTag(currentAlarm.alarm_level)">
            {{ getAlarmLevelText(currentAlarm.alarm_level) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="位置">{{ currentAlarm.building }}栋-{{ currentAlarm.floor }}层</el-descriptions-item>
        <el-descriptions-item label="防区">{{ currentAlarm.zone_name }}</el-descriptions-item>
        <el-descriptions-item label="报警内容">{{ currentAlarm.alarm_message }}</el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="getHandleStatusTag(currentAlarm.handles_satus)">
            {{ getHandleStatusText(currentAlarm.handles_satus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理人">{{ currentAlarm.handle_user }}</el-descriptions-item>
        <el-descriptions-item label="处理时间">{{ parseTime(currentAlarm.handle_time) }}</el-descriptions-item>
        <el-descriptions-item label="处理备注">{{ currentAlarm.handle_remark }}</el-descriptions-item>
        <el-descriptions-item label="联动状态">
          <el-tag :type="currentAlarm.linkages_status === 1 ? 'success' : 'info'">
            {{ currentAlarm.linkages_status === 1 ? '已联动' : '未联动' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="联动结果">{{ currentAlarm.linkage_result }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>

    <!-- 报警处理对话框 -->
    <el-dialog v-model="processDialogVisible" title="报警处理" width="600px">
      <el-form :model="processForm" :rules="processRules" ref="processFormRef" label-width="100px">
        <el-form-item label="处理状态" prop="handleStatus">
          <el-radio-group v-model="processForm.handleStatus">
            <el-radio :label="1">处理中</el-radio>
            <el-radio :label="2">已处理</el-radio>
            <el-radio :label="3">已忽略</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理备注" prop="handleRemark">
          <el-input
              v-model="processForm.handleRemark"
              type="textarea"
              :rows="4"
              placeholder="请输入处理备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProcessForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设备配置对话框 -->
    <el-dialog v-model="configDialogVisible" title="设备配置" width="600px">
      <el-form :model="configForm" :rules="configRules" ref="configFormRef" label-width="100px">
        <el-form-item label="敏感度" prop="sensitivity">
          <el-slider v-model="configForm.sensitivity" :min="1" :max="100" show-input />
        </el-form-item>
        <el-form-item label="延时时间" prop="delayTime">
          <el-input-number v-model="configForm.delayTime" :min="0" :max="300" controls-position="right" />
          <span style="margin-left: 8px;">秒</span>
        </el-form-item>
        <el-form-item label="联动摄像机" prop="linkageCameras">
          <el-select v-model="configForm.linkageCameras" multiple placeholder="选择联动摄像机">
            <el-option
                v-for="camera in cameraOptions"
                :key="camera.code"
                :label="camera.name"
                :value="camera.code"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="configDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitConfigForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import {
  listAlarmPoints,
  listAlarms,
  listZones,
  getAlarmStatistics,
  toggleArmStatus,
  testAlarmDevice,
  processAlarm,
  updateDeviceConfig
} from '@/api/subsystem/intrusion'

const { proxy } = getCurrentInstance()
const activeTab = ref('alarmPoints')

// 监听activeTab的变化
watch(activeTab, (newVal) => {
  if (newVal === 'realTimeAlarms') {
    getAlarmList()
    getStatisticsData()
  } else if (newVal === 'zones') {
    getZoneList()
  }
})

// 报警点查询相关
const alarmPointQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  deviceCode: null,
  deviceName: null,
  alarmType: null,
  zone: null,
  deviceStatus: null
})
const alarmPointList = ref([])
const alarmPointTotal = ref(0)
const alarmPointLoading = ref(false)

// 报警查询相关
const alarmQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  alarmLevel: null,
  handleStatus: null,
  zone: null,
  timeRange: []
})
const alarmList = ref([])
const alarmTotal = ref(0)
const alarmLoading = ref(false)

// 防区查询相关
const zoneQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  zoneName: null,
  zoneStatus: null
})
const zoneList = ref([])
const zoneTotal = ref(0)
const zoneLoading = ref(false)
const selectedZones = ref([])

// 统计数据
const statisticsData = ref({
  todayAlarms: 0,
  unhandledAlarms: 0,
  onlineDevices: 0,
  armedZones: 0
})

// 详情相关
const alarmPointDetailVisible = ref(false)
const currentAlarmPoint = ref({})

const alarmDetailVisible = ref(false)
const currentAlarm = ref({})

// 报警处理相关
const processDialogVisible = ref(false)
const processForm = ref({
  id: null,
  handleStatus: 2,
  handleRemark: ''
})
const processRules = {
  handleStatus: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
  handleRemark: [{ required: true, message: '请输入处理备注', trigger: 'blur' }]
}

// 设备配置相关
const configDialogVisible = ref(false)
const configForm = ref({
  deviceCode: '',
  sensitivity: 50,
  delayTime: 10,
  linkageCameras: []
})
const configRules = {
  sensitivity: [{ required: true, message: '请设置敏感度', trigger: 'change' }],
  delayTime: [{ required: true, message: '请设置延时时间', trigger: 'change' }]
}

// 摄像机选项（模拟数据）
const cameraOptions = ref([
  { code: 'CAM001', name: '一层大厅摄像机' },
  { code: 'CAM002', name: '二层走廊摄像机' },
  { code: 'CAM003', name: '三层办公区摄像机' }
])

// 报警类型标签
const getAlarmTypeTag = (type) => {
  const tags = {
    'intrusion': 'danger',
    'door_magnetic': 'warning',
    'infrared': 'primary',
    'glass_break': 'danger',
    'vibration': 'warning'
  }
  return tags[type] || 'info'
}

// 报警类型文本
const getAlarmTypeText = (type) => {
  const texts = {
    'intrusion': '入侵检测',
    'door_magnetic': '门磁报警',
    'infrared': '红外探测',
    'glass_break': '玻璃破碎',
    'vibration': '震动检测'
  }
  return texts[type] || '未知'
}

// 设备状态标签
const getDeviceStatusTag = (status) => {
  const tags = ['danger', 'success', 'danger', 'warning']
  return tags[status] || 'info'
}

// 设备状态文本
const getDeviceStatusText = (status) => {
  const texts = ['离线', '正常', '报警', '故障']
  return texts[status] || '未知'
}

// 报警级别标签
const getAlarmLevelTag = (level) => {
  const tags = ['info', 'success', 'warning', 'danger']
  return tags[level - 1] || 'info'
}

// 报警级别文本
const getAlarmLevelText = (level) => {
  const texts = ['', '低级', '中级', '高级', '紧急']
  return texts[level] || '未知'
}

// 处理状态标签
const getHandleStatusTag = (status) => {
  const tags = ['danger', 'warning', 'success', 'info']
  return tags[status] || 'info'
}

// 处理状态文本
const getHandleStatusText = (status) => {
  const texts = ['未处理', '处理中', '已处理', '已忽略']
  return texts[status] || '未知'
}

// 查询报警点列表
function getAlarmPointList() {
  alarmPointLoading.value = true
  const params = { ...alarmPointQuery }
  listAlarmPoints(params).then(response => {
    alarmPointList.value = response.rows
    alarmPointTotal.value = response.total
    alarmPointLoading.value = false
  })
}

// 重置报警点查询
function resetAlarmPointQuery() {
  proxy.resetForm('alarmPointQueryRef')
  alarmPointQuery.pageNum = 1
  getAlarmPointList()
}

// 查询报警列表
function getAlarmList() {
  alarmLoading.value = true
  const params = {
    ...alarmQuery,
    pageNum: alarmQuery.pageNum,
    pageSize: alarmQuery.pageSize
  }
  if (alarmQuery.timeRange && alarmQuery.timeRange.length === 2) {
    params.beginTime = alarmQuery.timeRange[0]
    params.endTime = alarmQuery.timeRange[1]
  }
  listAlarms(params).then(response => {
    alarmList.value = response.rows
    alarmTotal.value = response.total
    alarmLoading.value = false
  })
}

// 重置报警查询
function resetAlarmQuery() {
  proxy.resetForm('alarmQueryRef')
  alarmQuery.pageNum = 1
  getAlarmList()
}

// 查询防区列表
function getZoneList() {
  zoneLoading.value = true
  const params = { ...zoneQuery }
  listZones(params).then(response => {
    zoneList.value = response.rows
    zoneTotal.value = response.total
    zoneLoading.value = false
  })
}

// 重置防区查询
function resetZoneQuery() {
  proxy.resetForm('zoneQueryRef')
  zoneQuery.pageNum = 1
  getZoneList()
}

// 获取统计数据
function getStatisticsData() {
  getAlarmStatistics().then(response => {
    statisticsData.value = response.data
  })
}

// 查看报警点详情
function handleAlarmPointDetail(row) {
  currentAlarmPoint.value = row
  alarmPointDetailVisible.value = true
}

// 切换布防状态
function handleToggleArm(row) {
  const action = row.armStatus === 1 ? '撤防' : '布防'
  proxy.$modal.confirm(`确认${action}该设备吗？`).then(() => {
    toggleArmStatus({
      deviceCode: row.deviceCode,
      armStatus: row.armStatus === 1 ? 0 : 1
    }).then(response => {
      proxy.$modal.msgSuccess(`${action}成功`)
      getAlarmPointList()
    })
  })
}

// 设备配置
function handleDeviceConfig(row) {
  configForm.value = {
    deviceCode: row.deviceCode,
    sensitivity: row.sensitivity || 50,
    delayTime: row.delayTime || 10,
    linkageCameras: row.linkageCameras ? row.linkageCameras.split(',') : []
  }
  configDialogVisible.value = true
}

// 提交设备配置
function submitConfigForm() {
  proxy.$refs['configFormRef'].validate((valid) => {
    if (valid) {
      updateDeviceConfig(configForm.value).then(response => {
        proxy.$modal.msgSuccess('配置更新成功')
        configDialogVisible.value = false
        getAlarmPointList()
      })
    }
  })
}

// 测试报警
function handleTestAlarm(row) {
  proxy.$modal.confirm('确认测试该报警设备吗？').then(() => {
    testAlarmDevice(row.deviceCode).then(response => {
      proxy.$modal.msgSuccess('测试指令发送成功')
    })
  })
}

// 查看报警详情
function handleAlarmDetail(row) {
  currentAlarm.value = row
  alarmDetailVisible.value = true
}

// 处理报警
function handleAlarmProcess(row) {
  processForm.value = {
    id: row.id,
    handleStatus: 2,
    handleRemark: ''
  }
  processDialogVisible.value = true
}

// 提交报警处理
function submitProcessForm() {
  proxy.$refs['processFormRef'].validate((valid) => {
    if (valid) {
      processAlarm(processForm.value).then(response => {
        proxy.$modal.msgSuccess('报警处理成功')
        processDialogVisible.value = false
        getAlarmList()
      })
    }
  })
}

// 查看联动视频
function handleViewVideo(row) {
  proxy.$modal.msgWarning('联动视频查看功能开发中...')
}

// 防区选择变化
function handleZoneSelectionChange(selection) {
  selectedZones.value = selection
}

// 新增防区
function handleAddZone() {
  proxy.$modal.msgWarning('新增防区功能开发中...')
}

// 批量布防
function handleBatchArm() {
  if (selectedZones.value.length === 0) {
    proxy.$modal.msgWarning('请选择要布防的防区')
    return
  }
  proxy.$modal.msgWarning('批量布防功能开发中...')
}

// 批量撤防
function handleBatchDisarm() {
  if (selectedZones.value.length === 0) {
    proxy.$modal.msgWarning('请选择要撤防的防区')
    return
  }
  proxy.$modal.msgWarning('批量撤防功能开发中...')
}

// 查看防区详情
function handleZoneDetail(row) {
  proxy.$modal.msgWarning('防区详情功能开发中...')
}

// 修改防区
function handleEditZone(row) {
  proxy.$modal.msgWarning('修改防区功能开发中...')
}

// 切换防区状态
function handleToggleZone(row) {
  const action = row.zoneStatus === 1 ? '撤防' : '布防'
  proxy.$modal.confirm(`确认${action}该防区吗？`).then(() => {
    proxy.$modal.msgSuccess(`${action}成功`)
    getZoneList()
  })
}

// 删除防区
function handleDeleteZone(row) {
  proxy.$modal.confirm('确认删除该防区吗？').then(() => {
    proxy.$modal.msgSuccess('删除成功')
    getZoneList()
  })
}

// 初始化
onMounted(() => {
  getAlarmPointList()
  getStatisticsData()
})
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}

.text-gray-500 {
  color: #6b7280;
  font-size: 12px;
}
</style>
