<template>
  <div class="spfzgl-container">
    <!-- 左侧分组树 -->
    <div class="left-panel">
      <div class="panel-header">
        <span class="panel-title">视频分组</span>
        <el-button type="primary" link @click="handleAddGroup">
          <el-icon><Plus /></el-icon> 新增组
        </el-button>
      </div>
      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="treeProps"
        node-key="id"
        highlight-current
        default-expand-all
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <span class="tree-node">
            <span class="tree-node-label">{{ node.label }}</span>
            <span v-if="data.count !== undefined" class="tree-node-count">({{ data.count }})</span>
            <span v-if="data.custom" class="tree-node-actions">
              <el-icon class="action-icon" @click.stop="handleDeleteGroup(node, data)"><Delete /></el-icon>
            </span>
          </span>
        </template>
      </el-tree>
    </div>

    <!-- 右侧视频列表 -->
    <div class="right-panel">
      <!-- 搜索栏 -->
      <el-form :model="queryParams" :inline="true" class="search-form">
        <el-form-item label="视频名称">
          <el-input v-model="queryParams.name" placeholder="请输入视频名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 130px">
            <el-option label="在线" value="在线" />
            <el-option label="离线" 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" :disabled="selectedIds.length === 0" @click="handleCollectBatch">
          <el-icon><Star /></el-icon> 收藏到分组
        </el-button>
      </div>

      <!-- 视频卡片网格 -->
      <el-row :gutter="16">
        <el-col :span="8" v-for="item in pagedList" :key="item.id">
          <div class="video-card" :class="{ 'is-selected': selectedIds.includes(item.id) }" @click="toggleSelect(item.id)">
            <div class="video-thumb">
              <el-icon :size="48" color="#fff"><VideoPlay /></el-icon>
            </div>
            <div class="video-info">
              <div class="video-name">
                <el-checkbox :model-value="selectedIds.includes(item.id)" @click.stop @change="toggleSelect(item.id)" />
                <span class="name-text">{{ item.name }}</span>
              </div>
              <div class="video-meta">
                <span :class="['status-tag', item.status === '在线' ? 'online' : 'offline']">{{ item.status }}</span>
                <span class="meta-text">关联设备：{{ item.device }}</span>
              </div>
              <div class="video-meta">
                <span class="meta-text">安装位置：{{ item.location }}</span>
              </div>
              <div class="video-actions">
                <el-button link type="primary" @click.stop="handleViewVideo(item)">查看视频</el-button>
                <el-button link :type="item.collected ? 'warning' : 'default'" @click.stop="handleToggleCollect(item)">
                  <el-icon><Star /></el-icon>
                  {{ item.collected ? '已收藏' : '收藏' }}
                </el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

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

    <!-- 新增收藏组弹窗 -->
    <el-dialog v-model="addGroupVisible" title="新增收藏组" width="420px" :before-close="() => addGroupVisible = false">
      <el-form ref="addGroupFormRef" :model="addGroupForm" :rules="addGroupRules" label-width="90px">
        <el-form-item label="组名称" prop="name">
          <el-input v-model="addGroupForm.name" placeholder="请输入收藏组名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addGroupVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddGroupSubmit">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 收藏到分组弹窗 -->
    <el-dialog v-model="collectDialogVisible" title="收藏到分组" width="420px" :before-close="() => collectDialogVisible = false">
      <el-form label-width="90px">
        <el-form-item label="选择分组">
          <el-select v-model="collectTargetGroup" placeholder="请选择收藏组" style="width: 100%">
            <el-option v-for="g in customGroups" :key="g.id" :label="g.label" :value="g.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="collectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCollectSubmit">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 查看视频弹窗 -->
    <el-dialog v-model="videoDialogVisible" title="视频查看" width="680px" :before-close="() => videoDialogVisible = false">
      <div class="video-player">
        <div class="video-placeholder">
          <el-icon :size="56" color="#fff"><VideoPlay /></el-icon>
          <span class="video-placeholder-text">视频播放区域</span>
        </div>
      </div>
      <div class="video-detail-info">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">视频名称：</span>
              <span class="info-value">{{ currentVideo.name || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">视频状态：</span>
              <span :class="currentVideo.status === '在线' ? 'status-online' : 'status-offline'">{{ currentVideo.status || '-' }}</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.device || '-' }}</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="info-item">
              <span class="info-label">安装位置：</span>
              <span class="info-value">{{ currentVideo.location || '-' }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

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

// ==================== 视频模拟数据 ====================
const videoList = ref([
  { id: 1, name: '沅陵大道积水点摄像头', type: '积水点', status: '在线', device: '液位计 YW-001', location: '沅陵大道与人民路交叉口', collected: true, collectGroup: 'g1' },
  { id: 2, name: '城北路段积水监测视频', type: '积水点', status: '在线', device: '液位计 YW-002', location: '城北路段低洼处', collected: true, collectGroup: 'g1' },
  { id: 3, name: '河西片区积水点监控', type: '积水点', status: '离线', device: '液位计 YW-003', location: '河西片区涵洞入口', collected: false, collectGroup: '' },
  { id: 4, name: '南环路积水监测摄像头', type: '积水点', status: '在线', device: '液位计 YW-004', location: '南环路低洼路段', collected: false, collectGroup: '' },
  { id: 5, name: '人民路积水点视频', type: '积水点', status: '在线', device: '液位计 YW-005', location: '人民路地下通道入口', collected: false, collectGroup: '' },
  { id: 6, name: '开发区排水泵站视频', type: '泵站', status: '在线', device: '流量计 LL-001', location: '开发区排水泵站出口', collected: true, collectGroup: 'g2' },
  { id: 7, name: '城北泵站监控摄像头', type: '泵站', status: '在线', device: '流量计 LL-002', location: '城北泵站进水口', collected: false, collectGroup: '' },
  { id: 8, name: '河西泵站视频监控', type: '泵站', status: '离线', device: '流量计 LL-003', location: '河西泵站出水口', collected: false, collectGroup: '' },
  { id: 9, name: '南环泵站监测视频', type: '泵站', status: '在线', device: '流量计 LL-004', location: '南环泵站机房', collected: true, collectGroup: 'g2' },
  { id: 10, name: '沅陵大道下穿立交监控', type: '下穿立交', status: '在线', device: '液位计 YW-006', location: '沅陵大道下穿段', collected: false, collectGroup: '' },
  { id: 11, name: '城北下穿立交视频', type: '下穿立交', status: '在线', device: '液位计 YW-007', location: '城北路下穿段', collected: false, collectGroup: '' },
  { id: 12, name: '河西下穿涵洞监控', type: '下穿立交', status: '离线', device: '液位计 YW-008', location: '河西大道下穿涵洞', collected: false, collectGroup: '' },
  { id: 13, name: '人民路管网监测视频', type: '管网', status: '在线', device: '流量计 LL-005', location: '人民路主干排水管道', collected: false, collectGroup: '' },
  { id: 14, name: '城北路段管网监控', type: '管网', status: '在线', device: '流量计 LL-006', location: '城北路段排水管网', collected: false, collectGroup: '' },
  { id: 15, name: '开发区管网监测摄像头', type: '管网', status: '离线', device: '流量计 LL-007', location: '开发区排水管网出口', collected: false, collectGroup: '' }
])

// ==================== 分组树 ====================
const typeCountMap = computed(() => {
  const map = {}
  videoList.value.forEach(v => {
    map[v.type] = (map[v.type] || 0) + 1
  })
  return map
})

const customGroups = ref([
  { id: 'g1', label: '常用监测组', custom: true, count: 2 },
  { id: 'g2', label: '泵站重点组', custom: true, count: 2 }
])

let groupSeq = 3

const treeData = computed(() => {
  return [
    { id: 'all', label: '全部视频', count: videoList.value.length },
    {
      id: 'type',
      label: '按类型分组',
      children: [
        { id: 'type-积水点', label: '积水点视频', count: typeCountMap.value['积水点'] || 0 },
        { id: 'type-泵站', label: '泵站视频', count: typeCountMap.value['泵站'] || 0 },
        { id: 'type-下穿立交', label: '下穿立交视频', count: typeCountMap.value['下穿立交'] || 0 },
        { id: 'type-管网', label: '管网视频', count: typeCountMap.value['管网'] || 0 }
      ]
    },
    {
      id: 'fav',
      label: '我的收藏',
      children: customGroups.value
    }
  ]
})

const treeProps = { children: 'children', label: 'label' }
const treeRef = ref(null)
const currentNodeId = ref('all')

function handleNodeClick(data) {
  currentNodeId.value = data.id
  pagination.value.current = 1
}

// ==================== 搜索 ====================
const queryParams = ref({ name: '', status: '' })

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

function resetQuery() {
  queryParams.value = { name: '', status: '' }
  pagination.value.current = 1
}

// ==================== 过滤 + 分页 ====================
const filteredList = computed(() => {
  return videoList.value.filter(item => {
    const nameMatch = !queryParams.value.name || item.name.includes(queryParams.value.name)
    const statusMatch = !queryParams.value.status || item.status === queryParams.value.status
    let groupMatch = true
    if (currentNodeId.value === 'all') {
      groupMatch = true
    } else if (currentNodeId.value.startsWith('type-')) {
      const typeName = currentNodeId.value.replace('type-', '')
      groupMatch = item.type === typeName
    } else if (currentNodeId.value === 'fav' || currentNodeId.value === 'type') {
      groupMatch = true
    } else {
      // 自定义收藏组
      groupMatch = item.collected && item.collectGroup === currentNodeId.value
    }
    return nameMatch && statusMatch && groupMatch
  })
})

const pagination = ref({ current: 1, size: 9 })

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

// ==================== 多选 ====================
const selectedIds = ref([])

function toggleSelect(id) {
  const idx = selectedIds.value.indexOf(id)
  if (idx > -1) {
    selectedIds.value.splice(idx, 1)
  } else {
    selectedIds.value.push(id)
  }
}

// ==================== 新增收藏组 ====================
const addGroupVisible = ref(false)
const addGroupFormRef = ref(null)
const addGroupForm = ref({ name: '' })
const addGroupRules = { name: [{ required: true, message: '请输入组名称', trigger: 'blur' }] }

function handleAddGroup() {
  addGroupForm.value = { name: '' }
  addGroupVisible.value = true
}

function handleAddGroupSubmit() {
  addGroupFormRef.value.validate(valid => {
    if (!valid) return
    const newId = 'g' + groupSeq++
    customGroups.value.push({ id: newId, label: addGroupForm.value.name, custom: true, count: 0 })
    ElMessage.success('新增收藏组成功')
    addGroupVisible.value = false
  })
}

// ==================== 删除收藏组 ====================
function handleDeleteGroup(node, data) {
  ElMessageBox.confirm(`确认删除收藏组"${data.label}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const idx = customGroups.value.findIndex(g => g.id === data.id)
    if (idx > -1) {
      // 取消该组下视频的收藏
      videoList.value.forEach(v => {
        if (v.collectGroup === data.id) {
          v.collected = false
          v.collectGroup = ''
        }
      })
      customGroups.value.splice(idx, 1)
      if (currentNodeId.value === data.id) {
        currentNodeId.value = 'all'
      }
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

// ==================== 收藏 ====================
const collectDialogVisible = ref(false)
const collectTargetGroup = ref('')

function handleCollectBatch() {
  if (customGroups.value.length === 0) {
    ElMessage.warning('请先创建收藏组')
    return
  }
  collectTargetGroup.value = customGroups.value[0].id
  collectDialogVisible.value = true
}

function handleCollectSubmit() {
  if (!collectTargetGroup.value) {
    ElMessage.warning('请选择收藏组')
    return
  }
  selectedIds.value.forEach(id => {
    const v = videoList.value.find(item => item.id === id)
    if (v) {
      v.collected = true
      v.collectGroup = collectTargetGroup.value
    }
  })
  // 更新收藏组计数
  updateGroupCounts()
  ElMessage.success('收藏成功')
  selectedIds.value = []
  collectDialogVisible.value = false
}

function handleToggleCollect(item) {
  if (item.collected) {
    item.collected = false
    item.collectGroup = ''
    ElMessage.success('已取消收藏')
  } else {
    if (customGroups.value.length === 0) {
      ElMessage.warning('请先创建收藏组')
      return
    }
    // 默认收藏到第一个组
    item.collected = true
    item.collectGroup = customGroups.value[0].id
    ElMessage.success('已收藏到「' + customGroups.value[0].label + '」')
  }
  updateGroupCounts()
}

function updateGroupCounts() {
  customGroups.value.forEach(g => {
    g.count = videoList.value.filter(v => v.collected && v.collectGroup === g.id).length
  })
}

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

function handleViewVideo(item) {
  currentVideo.value = { ...item }
  videoDialogVisible.value = true
}
</script>

<style scoped>
.spfzgl-container {
  display: flex;
  height: calc(100vh - 84px);
  background: #f5f7fa;
}

.left-panel {
  width: 250px;
  min-width: 250px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 16px;
  border-bottom: 1px solid #e4e7ed;
}

.panel-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.left-panel :deep(.el-tree) {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.tree-node {
  display: flex;
  align-items: center;
  flex: 1;
  font-size: 14px;
}

.tree-node-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tree-node-count {
  color: #909399;
  font-size: 12px;
  margin-left: 4px;
}

.tree-node-actions {
  margin-left: 8px;
  display: none;
}

.tree-node:hover .tree-node-actions {
  display: inline-flex;
}

.action-icon {
  color: #f56c6c;
  cursor: pointer;
  font-size: 14px;
}

.action-icon:hover {
  color: #e04040;
}

.right-panel {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.search-form {
  margin-bottom: 12px;
  background: #fff;
  padding: 16px 16px 0;
  border-radius: 4px;
}

.toolbar {
  margin-bottom: 12px;
}

.video-card {
  background: #fff;
  border-radius: 6px;
  overflow: hidden;
  margin-bottom: 16px;
  border: 2px solid transparent;
  cursor: pointer;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.video-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.video-card.is-selected {
  border-color: #409eff;
}

.video-thumb {
  width: 100%;
  height: 200px;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-info {
  padding: 12px;
}

.video-name {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.name-text {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.video-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.status-tag {
  display: inline-block;
  padding: 1px 8px;
  border-radius: 3px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.online {
  background: #e1f3d8;
  color: #67c23a;
}

.status-tag.offline {
  background: #fde2e2;
  color: #f56c6c;
}

.meta-text {
  font-size: 13px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.video-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

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

/* 查看视频弹窗 */
.video-player {
  margin-bottom: 20px;
}

.video-placeholder {
  width: 100%;
  height: 320px;
  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-detail-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>
