<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.area" placeholder="请选择" clearable style="width: 180px">
          <el-option v-for="item in areaOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型">
        <el-select v-model="queryParams.deviceType" placeholder="请选择" clearable style="width: 180px">
          <el-option v-for="item in deviceTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="关联状态">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 180px">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </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>

    <!-- 操作按钮区域 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">新增关联</el-button>
      <el-button type="danger" plain :disabled="selectedRows.length === 0" @click="handleBatchUnbind">批量解除关联</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="pagedList" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="设备编号" prop="deviceNo" min-width="130" />
      <el-table-column label="设备名称" prop="deviceName" min-width="140" />
      <el-table-column label="设备类型" prop="deviceType" min-width="110">
        <template #default="{ row }">
          <span>{{ deviceTypeText(row.deviceType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="安装位置" prop="location" min-width="150" />
      <el-table-column label="所属区域" prop="area" min-width="100" />
      <el-table-column label="关联视频" prop="videoName" min-width="150">
        <template #default="{ row }">
          <span>{{ row.videoName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联状态" prop="status" min-width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === '1' ? 'success' : 'info'">{{ row.status === '1' ? '已关联' : '未关联' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" align="center" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleBind(row)" v-if="row.status !== '1'">关联视频</el-button>
          <el-button link type="danger" @click="handleUnbind(row)" v-if="row.status === '1'">解除关联</el-button>
          <el-button link type="primary" @click="handleViewVideo(row)" v-if="row.status === '1'">查看视频</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrap">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50]"
        :total="filteredList.length"
        layout="total, sizes, prev, pager, next, jumper"
        background
      />
    </div>

    <!-- 新增关联弹窗 -->
    <el-dialog v-model="bindDialogVisible" title="设备关联视频" width="560px" :before-close="handleBindClose">
      <el-form ref="bindFormRef" :model="bindForm" :rules="bindRules" label-width="100px">
        <el-form-item label="监测设备" prop="deviceId">
          <el-select v-model="bindForm.deviceId" placeholder="请选择监测设备" style="width: 100%" filterable>
            <el-option v-for="item in unboundDevices" :key="item.id" :label="item.deviceName + '（' + item.deviceNo + '）'" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联视频" prop="videoId">
          <el-select v-model="bindForm.videoId" placeholder="请选择关联视频" style="width: 100%" filterable>
            <el-option v-for="item in videoList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联说明" prop="remark">
          <el-input v-model="bindForm.remark" type="textarea" :rows="3" placeholder="请输入关联说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleBindClose">取 消</el-button>
        <el-button type="primary" @click="handleBindSubmit">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 查看视频弹窗 -->
    <el-dialog v-model="videoDialogVisible" title="关联视频查看" width="700px" :before-close="handleVideoClose">
      <div class="video-player">
        <div class="video-placeholder">
          <el-icon :size="48" color="#fff"><VideoPlay /></el-icon>
          <span class="video-placeholder-text">视频播放区域</span>
        </div>
      </div>
      <div class="video-info">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">视频名称：</span>
              <span class="info-value">{{ currentVideo.videoName || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">关联设备：</span>
              <span class="info-value">{{ currentVideo.deviceName || '-' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">安装位置：</span>
              <span class="info-value">{{ currentVideo.location || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">视频状态：</span>
              <span class="info-value">
                <span :class="currentVideo.videoStatus === '在线' ? 'status-online' : 'status-offline'">
                  {{ currentVideo.videoStatus || '-' }}
                </span>
              </span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">最近记录时间：</span>
              <span class="info-value">{{ currentVideo.lastRecordTime || '-' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Spgngl">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'

// ==================== 选项配置 ====================
const areaOptions = ['沅陵大道', '城北路段', '河西片区', '人民路', '南环路', '开发区']

const deviceTypeOptions = [
  { label: '液位计', value: '1' },
  { label: '流量计', value: '2' },
  { label: '雨量计', value: '3' },
  { label: '水质监测仪', value: '4' },
  { label: '视频监控', value: '5' }
]

const statusOptions = [
  { label: '已关联', value: '1' },
  { label: '未关联', value: '0' }
]

function deviceTypeText(val) {
  const map = { '1': '液位计', '2': '流量计', '3': '雨量计', '4': '水质监测仪', '5': '视频监控' }
  return map[val] || '-'
}

// ==================== 视频列表 ====================
const videoList = ref([
  { id: 1, name: '沅陵大道与人民路交叉口摄像头' },
  { id: 2, name: '城北路段管网监控摄像头' },
  { id: 3, name: '河西片区排水口监控' },
  { id: 4, name: '人民路地下管网监测视频' },
  { id: 5, name: '南环路污水处理厂入口监控' },
  { id: 6, name: '开发区排水泵站视频监控' },
  { id: 7, name: '北环路河道排放口监控' },
  { id: 8, name: '沅陵大道排水井监测视频' }
])

// ==================== 搜索参数 ====================
const queryParams = ref({
  deviceName: '',
  area: '',
  deviceType: '',
  status: ''
})

// ==================== 表格数据 ====================
const tableData = ref([
  { id: 1, deviceNo: 'DEV-2025-001', deviceName: '城北液位监测仪', deviceType: '1', location: '城北路段排水井A3号', area: '城北路段', videoId: 2, videoName: '城北路段管网监控摄像头', status: '1', remark: '' },
  { id: 2, deviceNo: 'DEV-2025-002', deviceName: '河西流量监测计', deviceType: '2', location: '河西大道排水管道B7号', area: '河西片区', videoId: 3, videoName: '河西片区排水口监控', status: '1', remark: '' },
  { id: 3, deviceNo: 'DEV-2025-003', deviceName: '南区水质监测仪', deviceType: '4', location: '南环路污水处理厂入口', area: '南环路', videoId: 5, videoName: '南环路污水处理厂入口监控', status: '1', remark: '' },
  { id: 4, deviceNo: 'DEV-2025-004', deviceName: '东区雨量计', deviceType: '3', location: '东环路市政大楼楼顶', area: '开发区', videoId: null, videoName: '', status: '0', remark: '' },
  { id: 5, deviceNo: 'DEV-2025-005', deviceName: '人民路液位计', deviceType: '1', location: '人民路地下管网C2号', area: '人民路', videoId: 4, videoName: '人民路地下管网监测视频', status: '1', remark: '' },
  { id: 6, deviceNo: 'DEV-2025-006', deviceName: '开发区流量计', deviceType: '2', location: '开发区排水泵站出口', area: '开发区', videoId: null, videoName: '', status: '0', remark: '' },
  { id: 7, deviceNo: 'DEV-2025-007', deviceName: '沅陵大道雨量计', deviceType: '3', location: '沅陵大道气象站', area: '沅陵大道', videoId: 1, videoName: '沅陵大道与人民路交叉口摄像头', status: '1', remark: '' },
  { id: 8, deviceNo: 'DEV-2025-008', deviceName: '河西水质监测仪', deviceType: '4', location: '河西片区河道排放口', area: '河西片区', videoId: null, videoName: '', status: '0', remark: '' },
  { id: 9, deviceNo: 'DEV-2025-009', deviceName: '城北视频监控', deviceType: '5', location: '城北路段排水泵站', area: '城北路段', videoId: null, videoName: '', status: '0', remark: '' },
  { id: 10, deviceNo: 'DEV-2025-010', deviceName: '南环路液位计', deviceType: '1', location: '南环路排水井D5号', area: '南环路', videoId: null, videoName: '', status: '0', remark: '' },
  { id: 11, deviceNo: 'DEV-2025-011', deviceName: '人民路流量计', deviceType: '2', location: '人民路主干排水管道', area: '人民路', videoId: 4, videoName: '人民路地下管网监测视频', status: '1', remark: '' },
  { id: 12, deviceNo: 'DEV-2025-012', deviceName: '沅陵大道液位计', deviceType: '1', location: '沅陵大道排水井E2号', area: '沅陵大道', videoId: 8, videoName: '沅陵大道排水井监测视频', status: '1', remark: '' }
])

// 多选
const selectedRows = ref([])
function handleSelectionChange(selection) {
  selectedRows.value = selection
}

// 过滤后的列表
const filteredList = computed(() => {
  return tableData.value.filter(item => {
    const nameMatch = !queryParams.value.deviceName || item.deviceName.includes(queryParams.value.deviceName)
    const areaMatch = !queryParams.value.area || item.area === queryParams.value.area
    const typeMatch = !queryParams.value.deviceType || item.deviceType === queryParams.value.deviceType
    const statusMatch = !queryParams.value.status || item.status === queryParams.value.status
    return nameMatch && areaMatch && typeMatch && statusMatch
  })
})

// 分页
const pagination = ref({
  current: 1,
  size: 10
})

const pagedList = computed(() => {
  const start = (pagination.value.current - 1) * pagination.value.size
  const end = start + pagination.value.size
  return filteredList.value.slice(start, end)
})

// 搜索
function handleQuery() {
  pagination.value.current = 1
}

// 重置
function resetQuery() {
  queryParams.value = {
    deviceName: '',
    area: '',
    deviceType: '',
    status: ''
  }
  pagination.value.current = 1
}

// ==================== 新增关联弹窗 ====================
const bindDialogVisible = ref(false)
const bindFormRef = ref(null)

const unboundDevices = computed(() => {
  return tableData.value.filter(item => item.status === '0')
})

const bindForm = ref({
  deviceId: null,
  videoId: null,
  remark: ''
})

const bindRules = {
  deviceId: [{ required: true, message: '请选择监测设备', trigger: 'change' }],
  videoId: [{ required: true, message: '请选择关联视频', trigger: 'change' }]
}

function handleAdd() {
  bindForm.value = { deviceId: null, videoId: null, remark: '' }
  bindDialogVisible.value = true
}

function handleBind(row) {
  bindForm.value = { deviceId: row.id, videoId: null, remark: '' }
  bindDialogVisible.value = true
}

function handleBindClose() {
  bindDialogVisible.value = false
}

function handleBindSubmit() {
  bindFormRef.value.validate(valid => {
    if (!valid) return
    const device = tableData.value.find(item => item.id === bindForm.value.deviceId)
    const video = videoList.value.find(item => item.id === bindForm.value.videoId)
    if (device && video) {
      device.videoId = video.id
      device.videoName = video.name
      device.status = '1'
      device.remark = bindForm.value.remark
      ElMessage.success('关联成功')
    }
    bindDialogVisible.value = false
  })
}

// ==================== 解除关联 ====================
function handleUnbind(row) {
  ElMessageBox.confirm(`确认解除设备"${row.deviceName}"与视频"${row.videoName}"的关联吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    row.videoId = null
    row.videoName = ''
    row.status = '0'
    row.remark = ''
    ElMessage.success('解除关联成功')
  }).catch(() => {})
}

function handleBatchUnbind() {
  const boundRows = selectedRows.value.filter(item => item.status === '1')
  if (boundRows.length === 0) {
    ElMessage.warning('选中的设备中没有已关联的记录')
    return
  }
  ElMessageBox.confirm(`确认解除选中的 ${boundRows.length} 条关联吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    boundRows.forEach(row => {
      row.videoId = null
      row.videoName = ''
      row.status = '0'
      row.remark = ''
    })
    ElMessage.success('批量解除关联成功')
  }).catch(() => {})
}

// ==================== 查看视频弹窗 ====================
const videoDialogVisible = ref(false)
const currentVideo = ref({})

function handleViewVideo(row) {
  currentVideo.value = {
    videoName: row.videoName,
    deviceName: row.deviceName,
    location: row.location,
    videoStatus: Math.random() > 0.3 ? '在线' : '离线',
    lastRecordTime: '2025-12-15 14:32:18'
  }
  videoDialogVisible.value = true
}

function handleVideoClose() {
  videoDialogVisible.value = false
}
</script>

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

.search-form {
  margin-bottom: 16px;
}

.toolbar {
  margin-bottom: 16px;
}

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

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

.video-placeholder {
  width: 100%;
  height: 300px;
  background: #000;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.video-placeholder-text {
  color: #999;
  margin-top: 10px;
  font-size: 14px;
}

.video-info {
  padding: 0 4px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  line-height: 32px;
}

.info-label {
  color: #909399;
  font-size: 14px;
  white-space: nowrap;
}

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

.status-online {
  color: #67c23a;
  font-weight: bold;
}

.status-offline {
  color: #f56c6c;
  font-weight: bold;
}
</style>
