<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <!-- 摄像机管理标签页 -->
      <el-tab-pane label="摄像机管理" name="cameras">
        <el-form :model="cameraQuery" ref="cameraQueryRef" :inline="true" label-width="98px">
          <el-form-item label="摄像机编号" prop="cameraCode">
            <el-input v-model="cameraQuery.cameraCode" placeholder="请输入摄像机编号" clearable />
          </el-form-item>
          <el-form-item label="摄像机名称" prop="cameraName">
            <el-input v-model="cameraQuery.cameraName" placeholder="请输入摄像机名称" clearable />
          </el-form-item>
          <el-form-item label="监控区域" prop="monitorArea">
            <el-input v-model="cameraQuery.monitorArea" placeholder="请输入监控区域" clearable />
          </el-form-item>
          <el-form-item label="楼栋" prop="building">
            <el-select v-model="cameraQuery.building" placeholder="请选择楼栋" clearable>
              <el-option label="A栋" value="A" />
              <el-option label="B栋" value="B" />
              <el-option label="C栋" value="C" />
              <el-option label="D栋" value="D" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备状态" prop="deviceStatus">
            <el-select v-model="cameraQuery.deviceStatus" placeholder="请选择状态" clearable>
              <el-option label="在线" :value="1" />
              <el-option label="离线" :value="0" />
              <el-option label="故障" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getCameraList">搜索</el-button>
            <el-button icon="Refresh" @click="resetCameraQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="cameraLoading" :data="cameraList" stripe border>
          <el-table-column label="摄像机编号" prop="cameraCode" width="150" />
          <el-table-column label="摄像机名称" prop="cameraName"  />
          <el-table-column label="监控区域" prop="monitorArea" width="120" />
          <el-table-column label="位置信息" width="150">
            <template #default="scope">
              <div>{{ scope.row.building }}栋-{{ scope.row.floor }}层</div>
              <div class="text-gray-500">{{ scope.row.location_detail }}</div>
            </template>
          </el-table-column>
          <el-table-column label="IP地址" prop="ipAddress" width="120" />
          <el-table-column label="端口" prop="port" width="80" />
          <el-table-column label="品牌型号" width="120">
            <template #default="scope">
              <div>{{ scope.row.brand }}</div>
              <div class="text-gray-500">{{ scope.row.model }}</div>
            </template>
          </el-table-column>
          <el-table-column label="分辨率" prop="resolution" width="100" />
          <el-table-column label="设备状态" prop="deviceStatus" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.deviceStatus === 1 ? 'success' : scope.row.deviceStatus === 2 ? 'warning' : 'danger'">
                {{ getStatusText(scope.row.deviceStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="云台控制" prop="ptzSupport" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.ptzSupport === 1 ? 'success' : 'info'">
                {{ scope.row.ptzSupport === 1 ? '支持' : '不支持' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="录像状态" prop="recordingStatus" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.recordingStatus === 1 ? 'success' : 'danger'">
                {{ scope.row.recordingStatus === 1 ? '录像中' : '未录像' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="400" fixed="right">
            <template #default="scope">
              <el-button link type="primary" icon="VideoCamera" @click="handleVideoPreview(scope.row)">实时预览</el-button>
              <el-button link type="success" icon="Setting" @click="handlePtzControl(scope.row)" v-if="scope.row.ptzSupport === 1">云台控制</el-button>
              <el-button link type="warning" icon="View" @click="handleCameraDetail(scope.row)">详情</el-button>
              <el-button link type="info" icon="VideoPlay" @click="handlePlayback(scope.row)">录像回放</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="cameraTotal > 0"
            :total="cameraTotal"
            v-model:page="cameraQuery.pageNum"
            v-model:limit="cameraQuery.pageSize"
            @pagination="getCameraList"
        />
      </el-tab-pane>

      <!-- 告警联动标签页 -->
      <el-tab-pane label="告警联动" name="linkage">
        <el-form :model="linkageQuery" ref="linkageQueryRef" :inline="true" label-width="98px">
          <el-form-item label="联动规则名称" prop="ruleName">
            <el-input v-model="linkageQuery.ruleName" placeholder="请输入联动规则名称" clearable />
          </el-form-item>
          <el-form-item label="触发设备" prop="triggerDevice">
            <el-input v-model="linkageQuery.triggerDevice" placeholder="请输入触发设备" clearable />
          </el-form-item>
          <el-form-item label="联动摄像机" prop="linkageCamera">
            <el-input v-model="linkageQuery.linkageCamera" placeholder="请输入联动摄像机" clearable />
          </el-form-item>
          <el-form-item label="规则状态" prop="ruleStatus">
            <el-select v-model="linkageQuery.ruleStatus" placeholder="请选择状态" clearable>
              <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="getLinkageList">搜索</el-button>
            <el-button icon="Refresh" @click="resetLinkageQuery">重置</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="handleAddLinkage"
            >新增联动规则</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="linkageLoading" :data="linkageList" stripe border>
          <el-table-column label="规则名称" prop="rule_name"  />
          <el-table-column label="触发设备" prop="trigger_device_name"  />
          <el-table-column label="触发条件" prop="trigger_condition"  />
          <el-table-column label="联动摄像机" prop="linkage_camera_name"  />
          <el-table-column label="联动动作" prop="linkage_action" >
            <template #default="scope">
              <el-tag>{{ getLinkageActionText(scope.row.linkage_action) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="延迟时间" prop="delayTime" width="100">
            <template #default="scope">
              <span>{{ scope.row.delay_time }}秒</span>
            </template>
          </el-table-column>
          <el-table-column label="规则状态" prop="ruleStatus" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.ruleStatus === 1 ? 'success' : 'danger'">
                {{ scope.row.ruleStatus === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="create_time" width="150">
            <template #default="scope">
              <span>{{ parseTime(scope.row.create_time) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleEditLinkage(scope.row)">修改</el-button>
              <el-button link type="danger" icon="Delete" @click="handleDeleteLinkage(scope.row)">删除</el-button>
              <el-button link type="warning" icon="Switch" @click="handleToggleLinkage(scope.row)">
                {{ scope.row.ruleStatus === 1 ? '禁用' : '启用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="linkageTotal > 0"
            :total="linkageTotal"
            v-model:page="linkageQuery.pageNum"
            v-model:limit="linkageQuery.pageSize"
            @pagination="getLinkageList"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 实时视频预览抽屉 -->
    <el-drawer
        v-model="videoVisible"
        title="实时视频预览"
        direction="rtl"
        size="60%"
    >
      <div class="video-container">
        <div class="video-player">
          <video ref="videoPlayer" controls autoplay muted style="width: 100%; height: 400px; background: #000;">
            <source :src="currentVideoUrl" type="application/x-mpegURL">
            您的浏览器不支持视频播放
          </video>
        </div>
        <div class="video-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="摄像机名称">{{ currentCamera.cameraName }}</el-descriptions-item>
            <el-descriptions-item label="监控区域">{{ currentCamera.monitorArea }}</el-descriptions-item>
            <el-descriptions-item label="位置">{{ currentCamera.building }}栋-{{ currentCamera.floor }}层</el-descriptions-item>
            <el-descriptions-item label="分辨率">{{ currentCamera.resolution }}</el-descriptions-item>
            <el-descriptions-item label="设备状态">
              <el-tag :type="currentCamera.deviceStatus === 1 ? 'success' : 'danger'">
                {{ getStatusText(currentCamera.deviceStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="录像状态">
              <el-tag :type="currentCamera.recordingStatus === 1 ? 'success' : 'danger'">
                {{ currentCamera.recordingStatus === 1 ? '录像中' : '未录像' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="video-controls">
          <el-button type="primary" @click="startRecording" v-if="currentCamera.recordingStatus === 0">开始录像</el-button>
          <el-button type="danger" @click="stopRecording" v-if="currentCamera.recordingStatus === 1">停止录像</el-button>
          <el-button type="success" @click="takeSnapshot">抓拍</el-button>
          <el-button type="warning" @click="handlePtzControl(currentCamera)" v-if="currentCamera.ptzSupport === 1">云台控制</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 云台控制抽屉 -->
    <el-drawer
        v-model="ptzVisible"
        title="云台控制"
        direction="rtl"
        size="40%"
    >
      <div class="ptz-container">
        <div class="ptz-direction">
          <h4>方向控制</h4>
          <div class="direction-grid">
            <div class="direction-row">
              <el-button @click="ptzControl('UP')" icon="ArrowUp" class="direction-btn">上</el-button>
            </div>
            <div class="direction-row">
              <el-button @click="ptzControl('LEFT')" icon="ArrowLeft" class="direction-btn">左</el-button>
              <el-button @click="ptzControl('STOP')" icon="Close" class="direction-btn stop-btn">停止</el-button>
              <el-button @click="ptzControl('RIGHT')" icon="ArrowRight" class="direction-btn">右</el-button>
            </div>
            <div class="direction-row">
              <el-button @click="ptzControl('DOWN')" icon="ArrowDown" class="direction-btn">下</el-button>
            </div>
          </div>
        </div>

        <div class="ptz-zoom">
          <h4>变焦控制</h4>
          <div class="zoom-controls">
            <el-button @click="ptzControl('ZOOM_IN')" icon="ZoomIn">放大</el-button>
            <el-button @click="ptzControl('ZOOM_OUT')" icon="ZoomOut">缩小</el-button>
          </div>
        </div>

        <div class="ptz-focus">
          <h4>聚焦控制</h4>
          <div class="focus-controls">
            <el-button @click="ptzControl('FOCUS_NEAR')" icon="Minus">近焦</el-button>
            <el-button @click="ptzControl('FOCUS_FAR')" icon="Plus">远焦</el-button>
            <el-button @click="ptzControl('AUTO_FOCUS')" icon="Aim">自动聚焦</el-button>
          </div>
        </div>

        <div class="ptz-preset">
          <h4>预置位控制</h4>
          <el-form :model="presetForm" :inline="true">
            <el-form-item label="预置位">
              <el-select v-model="presetForm.presetId" placeholder="选择预置位">
                <el-option
                    v-for="preset in presetList"
                    :key="preset.id"
                    :label="preset.name"
                    :value="preset.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="gotoPreset">转到</el-button>
              <el-button @click="setPreset">设置</el-button>
              <el-button @click="deletePreset">删除</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="ptz-speed">
          <h4>控制速度</h4>
          <el-slider v-model="ptzSpeed" :min="1" :max="10" show-input />
        </div>
      </div>
    </el-drawer>

    <!-- 摄像机详情抽屉 -->
    <el-drawer
        v-model="detailVisible"
        title="摄像机详情"
        direction="rtl"
        size="50%"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="摄像机编号">{{ currentCamera.cameraCode }}</el-descriptions-item>
        <el-descriptions-item label="摄像机名称">{{ currentCamera.cameraName }}</el-descriptions-item>
        <el-descriptions-item label="监控区域">{{ currentCamera.monitorArea }}</el-descriptions-item>
        <el-descriptions-item label="位置">{{ currentCamera.building }}栋-{{ currentCamera.floor }}层-{{ currentCamera.locationDetail }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentCamera.ipAddress }}</el-descriptions-item>
        <el-descriptions-item label="端口">{{ currentCamera.port }}</el-descriptions-item>
        <el-descriptions-item label="品牌">{{ currentCamera.brand }}</el-descriptions-item>
        <el-descriptions-item label="型号">{{ currentCamera.model }}</el-descriptions-item>
        <el-descriptions-item label="分辨率">{{ currentCamera.resolution }}</el-descriptions-item>
        <el-descriptions-item label="帧率">{{ currentCamera.frameRate }} fps</el-descriptions-item>
        <el-descriptions-item label="云台支持">
          <el-tag :type="currentCamera.ptzSupport === 1 ? 'success' : 'info'">
            {{ currentCamera.ptzSupport === 1 ? '支持' : '不支持' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="红外夜视">
          <el-tag :type="currentCamera.infraredSupport === 1 ? 'success' : 'info'">
            {{ currentCamera.infraredSupport === 1 ? '支持' : '不支持' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="设备状态">
          <el-tag :type="currentCamera.deviceStatus === 1 ? 'success' : currentCamera.deviceStatus === 2 ? 'warning' : 'danger'">
            {{ getStatusText(currentCamera.deviceStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="录像状态">
          <el-tag :type="currentCamera.recordingStatus === 1 ? 'success' : 'danger'">
            {{ currentCamera.recordingStatus === 1 ? '录像中' : '未录像' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="存储路径">{{ currentCamera.storagePath }}</el-descriptions-item>
        <el-descriptions-item label="最后在线时间">{{ parseTime(currentCamera.lastOnlineTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>

    <!-- 联动规则配置对话框 -->
    <el-dialog v-model="linkageDialogVisible" :title="linkageDialogTitle" width="600px">
      <el-form :model="linkageForm" :rules="linkageRules" ref="linkageFormRef" label-width="120px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="linkageForm.ruleName" placeholder="请输入联动规则名称" />
        </el-form-item>
        <el-form-item label="触发设备" prop="triggerDeviceCode">
          <el-select v-model="linkageForm.triggerDeviceCode" placeholder="请选择触发设备" filterable>
            <el-option
                v-for="device in triggerDeviceList"
                :key="device.code"
                :label="device.name"
                :value="device.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="触发条件" prop="triggerCondition">
          <el-select v-model="linkageForm.triggerCondition" placeholder="请选择触发条件">
            <el-option label="设备报警" value="deviceAlarm" />
            <el-option label="入侵检测" value="intrusionDetection" />
            <el-option label="门禁异常" value="accessAbnormal" />
            <el-option label="火灾报警" value="fireAlarm" />
          </el-select>
        </el-form-item>
        <el-form-item label="联动摄像机" prop="linkageCameraCode">
          <el-select v-model="linkageForm.linkageCameraCode" placeholder="请选择联动摄像机" filterable>
            <el-option
                v-for="camera in cameraList"
                :key="camera.cameraCode"
                :label="camera.cameraName"
                :value="camera.cameraCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联动动作" prop="linkageAction">
          <el-select v-model="linkageForm.linkageAction" placeholder="请选择联动动作">
            <el-option label="开始录像" value="start_recording" />
            <el-option label="转到预置位" value="goto_preset" />
            <el-option label="自动跟踪" value="auto_tracking" />
            <el-option label="抓拍图片" value="capture_image" />
          </el-select>
        </el-form-item>
        <el-form-item label="延迟时间" prop="delayTime">
          <el-input-number v-model="linkageForm.delayTime" :min="0" :max="300" controls-position="right" />
          <span style="margin-left: 8px;">秒</span>
        </el-form-item>
        <el-form-item label="规则状态" prop="ruleStatus">
          <el-radio-group v-model="linkageForm.ruleStatus">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="linkageDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitLinkageForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { listCameras, getCameraStream, ptzControl as ptzControlApi, recordingControl, takeCameraSnapshot } from '@/api/subsystem/video'
import { listLinkageRules, addLinkageRule, updateLinkageRule, deleteLinkageRule, toggleLinkageRule } from '@/api/subsystem/video'

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

// 监听activeTab的变化
watch(activeTab, (newVal) => {
  if (newVal === 'linkage') {
    getLinkageList()
  }
})

// 摄像机查询相关
const cameraQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  cameraCode: null,
  cameraName: null,
  monitorArea: null,
  building: null,
  deviceStatus: null
})
const cameraList = ref([])
const cameraTotal = ref(0)
const cameraLoading = ref(false)

// 联动规则查询相关
const linkageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  ruleName: null,
  triggerDevice: null,
  linkageCamera: null,
  ruleStatus: null
})
const linkageList = ref([])
const linkageTotal = ref(0)
const linkageLoading = ref(false)

// 视频预览相关
const videoVisible = ref(false)
const currentCamera = ref({})
const currentVideoUrl = ref('')

// 云台控制相关
const ptzVisible = ref(false)
const ptzSpeed = ref(5)
const presetForm = ref({
  presetId: null
})
const presetList = ref([
  { id: 1, name: '预置位1' },
  { id: 2, name: '预置位2' },
  { id: 3, name: '预置位3' }
])

// 详情相关
const detailVisible = ref(false)

// 联动规则配置相关
const linkageDialogVisible = ref(false)
const linkageDialogTitle = ref('')
const linkageForm = ref({
  id: null,
  ruleName: '',
  triggerDeviceCode: '',
  triggerCondition: '',
  linkageCameraCode: '',
  linkageAction: '',
  delayTime: 0,
  ruleStatus: 1
})
const linkageRules = {
  ruleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  triggerDeviceCode: [{ required: true, message: '请选择触发设备', trigger: 'change' }],
  triggerCondition: [{ required: true, message: '请选择触发条件', trigger: 'change' }],
  linkageCameraCode: [{ required: true, message: '请选择联动摄像机', trigger: 'change' }],
  linkageAction: [{ required: true, message: '请选择联动动作', trigger: 'change' }]
}

// 触发设备列表（模拟数据，实际应从其他子系统获取）
const triggerDeviceList = ref([
  { code: 'ALARM001', name: '火灾报警器001' },
  { code: 'DOOR001', name: '门禁001' },
  { code: 'MOTION001', name: '红外探测器001' }
])

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

// 联动动作文本
const getLinkageActionText = (action) => {
  const texts = {
    'start_recording': '开始录像',
    'goto_preset': '转到预置位',
    'auto_tracking': '自动跟踪',
    'capture_image': '抓拍图片'
  }
  return texts[action] || '未知'
}

// 查询摄像机列表
function getCameraList() {
  cameraLoading.value = true
  const params = {
    ...cameraQuery,
    pageNum: cameraQuery.pageNum,
    pageSize: cameraQuery.pageSize
  }
  listCameras(params).then(response => {
    cameraList.value = response.rows
    cameraTotal.value = response.total
    cameraLoading.value = false
  })
}

// 重置摄像机查询
function resetCameraQuery() {
  proxy.resetForm('cameraQueryRef')
  cameraQuery.pageNum = 1
  getCameraList()
}

// 查询联动规则列表
function getLinkageList() {
  linkageLoading.value = true
  const params = {
    ...linkageQuery,
    pageNum: linkageQuery.pageNum,
    pageSize: linkageQuery.pageSize
  }
  listLinkageRules(params).then(response => {
    linkageList.value = response.rows
    linkageTotal.value = response.total
    linkageLoading.value = false
  })
}

// 重置联动规则查询
function resetLinkageQuery() {
  proxy.resetForm('linkageQueryRef')
  linkageQuery.pageNum = 1
  getLinkageList()
}

// 实时视频预览
function handleVideoPreview(row) {
  currentCamera.value = row
  videoVisible.value = true

  // 获取视频流地址
  getCameraStream(row.camera_code).then(response => {
    currentVideoUrl.value = response.data.streamUrl
  })
}

// 云台控制
function handlePtzControl(row) {
  currentCamera.value = row
  ptzVisible.value = true
}

// 云台方向控制
function ptzControl(direction) {
  const params = {
    cameraCode: currentCamera.value.cameraCode,
    command: direction,
    speed: ptzSpeed.value
  }
  ptzControlApi(params).then(response => {
    proxy.$modal.msgSuccess('云台控制指令发送成功')
  })
}

// 转到预置位
function gotoPreset() {
  if (!presetForm.value.presetId) {
    proxy.$modal.msgWarning('请选择预置位')
    return
  }
  ptzControl(`PRESET_${presetForm.value.presetId}`)
}

// 设置预置位
function setPreset() {
  if (!presetForm.value.presetId) {
    proxy.$modal.msgWarning('请选择预置位')
    return
  }
  ptzControl(`SET_PRESET_${presetForm.value.presetId}`)
}

// 删除预置位
function deletePreset() {
  if (!presetForm.value.presetId) {
    proxy.$modal.msgWarning('请选择预置位')
    return
  }
  ptzControl(`DEL_PRESET_${presetForm.value.presetId}`)
}

// 开始录像
function startRecording() {
  recordingControl({
    cameraCode: currentCamera.value.cameraCode,
    action: 'start'
  }).then(response => {
    proxy.$modal.msgSuccess('开始录像成功')
    currentCamera.value.recordingStatus = 1
    getCameraList()
  })
}

// 停止录像
function stopRecording() {
  recordingControl({
    cameraCode: currentCamera.value.cameraCode,
    action: 'stop'
  }).then(response => {
    proxy.$modal.msgSuccess('停止录像成功')
    currentCamera.value.recordingStatus = 0
    getCameraList()
  })
}

// 抓拍
function takeSnapshot() {
  takeCameraSnapshot(currentCamera.value.cameraCode).then(response => {
    proxy.$modal.msgSuccess('抓拍成功，图片已保存')
  })
}

// 查看摄像机详情
function handleCameraDetail(row) {
  currentCamera.value = row
  detailVisible.value = true
}

// 录像回放
function handlePlayback(row) {
  proxy.$modal.msgWarning('录像回放功能开发中...')
}

// 新增联动规则
function handleAddLinkage() {
  linkageForm.value = {
    id: null,
    ruleName: '',
    triggerDeviceCode: '',
    triggerCondition: '',
    linkageCameraCode: '',
    linkageAction: '',
    delayTime: 0,
    ruleStatus: 1
  }
  linkageDialogTitle.value = '新增联动规则'
  linkageDialogVisible.value = true
}

// 修改联动规则
function handleEditLinkage(row) {
  linkageForm.value = { ...row }
  linkageDialogTitle.value = '修改联动规则'
  linkageDialogVisible.value = true
}

// 删除联动规则
function handleDeleteLinkage(row) {
  proxy.$modal.confirm('确认删除该联动规则吗？').then(() => {
    deleteLinkageRule(row.id).then(response => {
      proxy.$modal.msgSuccess('删除成功')
      getLinkageList()
    })
  })
}

// 启用/禁用联动规则
function handleToggleLinkage(row) {
  const action = row.rule_status === 1 ? '禁用' : '启用'
  proxy.$modal.confirm(`确认${action}该联动规则吗？`).then(() => {
    toggleLinkageRule(row.id, { ruleStatus: row.rule_status === 1 ? 0 : 1 }).then(response => {
      proxy.$modal.msgSuccess(`${action}成功`)
      getLinkageList()
    })
  })
}

// 提交联动规则表单
function submitLinkageForm() {
  proxy.$refs['linkageFormRef'].validate((valid) => {
    if (valid) {
      if (linkageForm.value.id) {
        updateLinkageRule(linkageForm.value).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          linkageDialogVisible.value = false
          getLinkageList()
        })
      } else {
        addLinkageRule(linkageForm.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          linkageDialogVisible.value = false
          getLinkageList()
        })
      }
    }
  })
}

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

<style scoped>
.video-container {
  padding: 20px;
}

.video-player {
  margin-bottom: 20px;
}

.video-info {
  margin-bottom: 20px;
}

.video-controls {
  text-align: center;
}

.ptz-container {
  padding: 20px;
}

.ptz-direction, .ptz-zoom, .ptz-focus, .ptz-preset, .ptz-speed {
  margin-bottom: 30px;
}

.direction-grid {
  text-align: center;
}

.direction-row {
  margin-bottom: 10px;
}

.direction-btn {
  width: 60px;
  height: 60px;
  margin: 5px;
}

.stop-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: white;
}

.zoom-controls, .focus-controls {
  text-align: center;
}

.zoom-controls .el-button, .focus-controls .el-button {
  margin: 0 10px;
}
</style>