<template>
  <div class="jcsp-gis-page">
    <!-- 左侧浮动面板 -->
    <div class="side-panel">
      <div class="panel-header">
        <span class="panel-title">视频资源分布</span>
      </div>

      <!-- 图层筛选 -->
      <div class="panel-section">
        <div class="section-label">图层筛选</div>
        <div class="layer-list">
          <div class="layer-item" v-for="item in layerOptions" :key="item.value">
            <el-checkbox
              v-model="layerChecked[item.value]"
              @change="onLayerChange"
            >
              <span class="layer-dot" :style="{ background: item.color }"></span>
              {{ item.label }}
            </el-checkbox>
          </div>
        </div>
      </div>

      <!-- 视频统计 -->
      <div class="panel-section">
        <div class="section-label">视频统计</div>
        <div class="stats-row">
          <div class="stat-card">
            <div class="stat-value">{{ videoList.length }}</div>
            <div class="stat-text">总数</div>
          </div>
          <div class="stat-card stat-online">
            <div class="stat-value">{{ onlineCount }}</div>
            <div class="stat-text">在线</div>
          </div>
          <div class="stat-card stat-offline">
            <div class="stat-value">{{ offlineCount }}</div>
            <div class="stat-text">离线</div>
          </div>
        </div>
      </div>

      <!-- 搜索框 -->
      <div class="panel-section">
        <div class="section-label">快速定位</div>
        <el-input
          v-model="searchKey"
          placeholder="输入视频名称搜索"
          clearable
          prefix-icon="Search"
          @input="onSearch"
        />
        <div class="search-results" v-if="searchResults.length > 0">
          <div
            class="search-item"
            v-for="item in searchResults"
            :key="item.id"
            @click="locateVideo(item)"
          >
            <span class="layer-dot" :style="{ background: getTypeColor(item.type) }"></span>
            <span class="search-name">{{ item.name }}</span>
            <span class="search-status" :class="item.status === '在线' ? 'online' : 'offline'">
              {{ item.status }}
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 地图容器 -->
    <div id="jcspGISMap" class="map-container"></div>

    <!-- 视频弹窗 -->
    <el-dialog
      v-model="videoDialogVisible"
      :title="currentVideo.name"
      width="480px"
      :close-on-click-modal="false"
      class="video-dialog"
      @closed="onDialogClosed"
    >
      <div class="video-player" :class="{ offline: currentVideo.status === '离线' }">
        <div class="player-placeholder" v-if="currentVideo.status === '离线'">
          <el-icon :size="48"><VideoCamera /></el-icon>
          <span>设备离线，无法播放</span>
        </div>
        <div class="player-placeholder playing" v-else>
          <el-icon :size="48" class="play-icon"><VideoCamera /></el-icon>
          <span>实时监控画面</span>
          <div class="live-badge">LIVE</div>
        </div>
      </div>
      <div class="video-info">
        <div class="info-row">
          <span class="info-label">视频名称</span>
          <span class="info-value">{{ currentVideo.name }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">设备类型</span>
          <span class="info-value">
            <span class="type-tag" :style="{ background: getTypeColor(currentVideo.type), color: '#fff' }">
              {{ getTypeLabel(currentVideo.type) }}
            </span>
          </span>
        </div>
        <div class="info-row">
          <span class="info-label">安装位置</span>
          <span class="info-value">{{ currentVideo.location }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">在线状态</span>
          <span class="info-value" :class="currentVideo.status === '在线' ? 'status-online' : 'status-offline'">
            {{ currentVideo.status }}
          </span>
        </div>
        <div class="info-row">
          <span class="info-label">关联设备</span>
          <span class="info-value">{{ currentVideo.device }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="JcspGIS">
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
import { VideoCamera, Search } from '@element-plus/icons-vue'
import locationIcon from '@/assets/images/location.png'

// ==================== 图层配置 ====================
const layerOptions = [
  { label: '积水点视频', value: 'jsd', color: '#409eff' },
  { label: '泵站视频', value: 'bz', color: '#67c23a' },
  { label: '下穿立交视频', value: 'xclj', color: '#e6a23c' },
  { label: '管网视频', value: 'gw', color: '#9b59b6' }
]

const layerChecked = reactive({
  jsd: true,
  bz: true,
  xclj: true,
  gw: true
})

// ==================== 模拟视频数据（18个点位）====================
const videoList = ref([
  { id: 1, name: '沅陵大桥积水点', type: 'jsd', lng: 110.396, lat: 28.468, status: '在线', location: '沅陵大桥南侧', device: 'WL-JSD-001' },
  { id: 2, name: '太常路积水点', type: 'jsd', lng: 110.382, lat: 28.459, status: '在线', location: '太常路与沅江路交汇', device: 'WL-JSD-002' },
  { id: 3, name: '沅江路积水点', type: 'jsd', lng: 110.403, lat: 28.447, status: '离线', location: '沅江路中段', device: 'WL-JSD-003' },
  { id: 4, name: '龙舟路积水点', type: 'jsd', lng: 110.388, lat: 28.436, status: '在线', location: '龙舟路与建设路交汇', device: 'WL-JSD-004' },
  { id: 5, name: '城东积水点', type: 'jsd', lng: 110.412, lat: 28.461, status: '在线', location: '城东开发区入口', device: 'WL-JSD-005' },
  { id: 6, name: '一号泵站', type: 'bz', lng: 110.391, lat: 28.465, status: '在线', location: '沅陵大桥西侧', device: 'WL-BZ-001' },
  { id: 7, name: '二号泵站', type: 'bz', lng: 110.378, lat: 28.451, status: '在线', location: '太常片区排水口', device: 'WL-BZ-002' },
  { id: 8, name: '三号泵站', type: 'bz', lng: 110.407, lat: 28.455, status: '离线', location: '沅江路东段', device: 'WL-BZ-003' },
  { id: 9, name: '四号泵站', type: 'bz', lng: 110.395, lat: 28.439, status: '在线', location: '城区排水枢纽', device: 'WL-BZ-004' },
  { id: 10, name: '五号泵站', type: 'bz', lng: 110.368, lat: 28.448, status: '在线', location: '沅水南岸排水站', device: 'WL-BZ-005' },
  { id: 11, name: '沅陵大桥下穿', type: 'xclj', lng: 110.398, lat: 28.463, status: '在线', location: '沅陵大桥下穿通道', device: 'WL-XC-001' },
  { id: 12, name: '太常路下穿', type: 'xclj', lng: 110.384, lat: 28.453, status: '在线', location: '太常路下穿隧道', device: 'WL-XC-002' },
  { id: 13, name: '建设路下穿', type: 'xclj', lng: 110.393, lat: 28.441, status: '离线', location: '建设路下穿通道', device: 'WL-XC-003' },
  { id: 14, name: '城东下穿立交', type: 'xclj', lng: 110.415, lat: 28.457, status: '在线', location: '城东立交桥下', device: 'WL-XC-004' },
  { id: 15, name: '主城区管网A段', type: 'gw', lng: 110.390, lat: 28.460, status: '在线', location: '主城区排水干管', device: 'WL-GW-001' },
  { id: 16, name: '太常片区管网', type: 'gw', lng: 110.376, lat: 28.446, status: '在线', location: '太常片区管网节点', device: 'WL-GW-002' },
  { id: 17, name: '沅江路管网', type: 'gw', lng: 110.405, lat: 28.449, status: '离线', location: '沅江路管网检测点', device: 'WL-GW-003' },
  { id: 18, name: '城东管网B段', type: 'gw', lng: 110.418, lat: 28.465, status: '在线', location: '城东管网检测井', device: 'WL-GW-004' }
])

// ==================== 统计计算 ====================
const onlineCount = computed(() => videoList.value.filter(v => v.status === '在线').length)
const offlineCount = computed(() => videoList.value.filter(v => v.status === '离线').length)

// ==================== 搜索功能 ====================
const searchKey = ref('')
const searchResults = ref([])

function onSearch() {
  if (!searchKey.value.trim()) {
    searchResults.value = []
    return
  }
  const key = searchKey.value.trim().toLowerCase()
  searchResults.value = videoList.value.filter(v =>
    v.name.toLowerCase().includes(key) || v.location.toLowerCase().includes(key)
  )
}

function locateVideo(item) {
  if (mapInstance) {
    mapInstance.centerAndZoom(new BMapGL.Point(item.lng, item.lat), 17)
    // 触发对应标记的点击
    const label = markerMap.get(item.id)
    if (label) {
      // 打开视频弹窗
      openVideoDialog(item)
    }
  }
  searchResults.value = []
  searchKey.value = ''
}

// ==================== 工具方法 ====================
function getTypeColor(type) {
  const map = { jsd: '#409eff', bz: '#67c23a', xclj: '#e6a23c', gw: '#9b59b6' }
  return map[type] || '#409eff'
}

function getTypeLabel(type) {
  const map = { jsd: '积水点视频', bz: '泵站视频', xclj: '下穿立交视频', gw: '管网视频' }
  return map[type] || '未知类型'
}

// ==================== 地图相关 ====================
let mapInstance = null
const markerMap = new Map() // id -> label

function initMap() {
  const container = document.getElementById('jcspGISMap')
  if (!container || typeof BMapGL === 'undefined') {
    console.warn('BMapGL 未加载或容器不存在')
    return
  }

  try {
    mapInstance = new BMapGL.Map('jcspGISMap')
    const centerPoint = new BMapGL.Point(110.393, 28.452)
    mapInstance.centerAndZoom(centerPoint, 15)
    mapInstance.enableScrollWheelZoom(true)

    // 添加所有标记
    videoList.value.forEach(point => {
      addMapMarker(point)
    })
  } catch (e) {
    console.error('百度地图初始化失败：', e)
  }
}

function addMapMarker(point) {
  const color = getTypeColor(point.type)
  const typeLabel = getTypeLabel(point.type)
  const bPoint = new BMapGL.Point(point.lng, point.lat)
  const statusDot = point.status === '在线'
    ? '<span style="display:inline-block;width:6px;height:6px;border-radius:50%;background:#67c23a;margin-right:3px;vertical-align:middle;"></span>'
    : '<span style="display:inline-block;width:6px;height:6px;border-radius:50%;background:#f56c6c;margin-right:3px;vertical-align:middle;"></span>'

  const html = `<div style="text-align:center;cursor:pointer;">
    <div style="color:#fff;background:${color};border-radius:4px;padding:2px 8px;font-size:11px;white-space:nowrap;display:inline-block;margin-bottom:2px;box-shadow:0 1px 4px rgba(0,0,0,0.3);">
      ${statusDot}${point.name}
    </div>
    <div><img src="${locationIcon}" style="width:28px;height:28px;display:block;margin:0 auto;"/></div>
  </div>`

  const label = new BMapGL.Label(html, {
    position: bPoint,
    offset: new BMapGL.Size(-30, -50)
  })
  label.setStyle({
    border: 'none',
    background: 'transparent',
    padding: '0',
    zIndex: '10'
  })
  mapInstance.addOverlay(label)

  // 存储标记引用
  markerMap.set(point.id, label)

  // 点击标记打开视频弹窗
  label.addEventListener('click', function () {
    openVideoDialog(point)
  })
}

// ==================== 图层筛选 ====================
function onLayerChange() {
  videoList.value.forEach(point => {
    const label = markerMap.get(point.id)
    if (!label) return
    const visible = layerChecked[point.type]
    label.show()
    if (!visible) {
      label.hide()
    }
  })
}

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

function openVideoDialog(point) {
  currentVideo.value = { ...point }
  videoDialogVisible.value = true
}

function onDialogClosed() {
  currentVideo.value = {}
}

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

<style scoped>
.jcsp-gis-page {
  position: relative;
  width: 100%;
  height: calc(100vh - 84px);
  overflow: hidden;
}

.map-container {
  width: 100%;
  height: 100%;
}

/* ==================== 左侧浮动面板 ==================== */
.side-panel {
  position: absolute;
  top: 16px;
  left: 16px;
  width: 280px;
  background: rgba(20, 30, 48, 0.92);
  border-radius: 8px;
  z-index: 100;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4);
  padding: 0;
  max-height: calc(100% - 32px);
  overflow-y: auto;
}

.side-panel::-webkit-scrollbar {
  width: 4px;
}
.side-panel::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 2px;
}

.panel-header {
  padding: 16px 18px 12px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.panel-title {
  font-size: 16px;
  font-weight: 600;
  color: #fff;
  letter-spacing: 1px;
}

.panel-section {
  padding: 14px 18px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}

.panel-section:last-child {
  border-bottom: none;
}

.section-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.5);
  margin-bottom: 10px;
  text-transform: uppercase;
  letter-spacing: 1px;
}

/* 图层列表 */
.layer-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.layer-item :deep(.el-checkbox) {
  color: rgba(255, 255, 255, 0.85);
  height: auto;
}

.layer-item :deep(.el-checkbox__label) {
  color: rgba(255, 255, 255, 0.85);
  font-size: 13px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.layer-item :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background: #409eff;
  border-color: #409eff;
}

.layer-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 2px;
  vertical-align: middle;
}

/* 统计卡片 */
.stats-row {
  display: flex;
  gap: 10px;
}

.stat-card {
  flex: 1;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 6px;
  padding: 10px 8px;
  text-align: center;
}

.stat-card.stat-online {
  background: rgba(103, 194, 58, 0.15);
}

.stat-card.stat-offline {
  background: rgba(245, 108, 108, 0.15);
}

.stat-value {
  font-size: 22px;
  font-weight: 700;
  color: #fff;
  line-height: 1.2;
}

.stat-online .stat-value {
  color: #67c23a;
}

.stat-offline .stat-value {
  color: #f56c6c;
}

.stat-text {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.5);
  margin-top: 4px;
}

/* 搜索 */
.side-panel :deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.08);
  box-shadow: none;
  border: 1px solid rgba(255, 255, 255, 0.12);
}

.side-panel :deep(.el-input__inner) {
  color: #fff;
  font-size: 13px;
}

.side-panel :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.35);
}

.side-panel :deep(.el-input__prefix .el-icon) {
  color: rgba(255, 255, 255, 0.4);
}

.search-results {
  margin-top: 8px;
  max-height: 200px;
  overflow-y: auto;
  border-radius: 4px;
}

.search-results::-webkit-scrollbar {
  width: 3px;
}
.search-results::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 2px;
}

.search-item {
  display: flex;
  align-items: center;
  padding: 7px 10px;
  cursor: pointer;
  border-radius: 4px;
  transition: background 0.15s;
}

.search-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.search-name {
  flex: 1;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.85);
  margin-left: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.search-status {
  font-size: 11px;
  padding: 1px 6px;
  border-radius: 3px;
}

.search-status.online {
  color: #67c23a;
  background: rgba(103, 194, 58, 0.15);
}

.search-status.offline {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.15);
}

/* ==================== 视频弹窗样式 ==================== */
.video-dialog :deep(.el-dialog) {
  border-radius: 10px;
  overflow: hidden;
}

.video-dialog :deep(.el-dialog__header) {
  background: #1a1a2e;
  padding: 14px 20px;
  margin: 0;
}

.video-dialog :deep(.el-dialog__title) {
  color: #fff;
  font-size: 15px;
}

.video-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: rgba(255, 255, 255, 0.6);
}

.video-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.video-player {
  width: 100%;
  height: 300px;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.player-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: rgba(255, 255, 255, 0.3);
  font-size: 14px;
}

.player-placeholder.playing {
  color: rgba(255, 255, 255, 0.6);
}

.play-icon {
  color: #409eff;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.live-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: #f56c6c;
  color: #fff;
  font-size: 11px;
  font-weight: 700;
  padding: 2px 8px;
  border-radius: 3px;
  letter-spacing: 1px;
  animation: blink 1.5s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.4; }
}

.video-info {
  padding: 16px 20px;
}

.info-row {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  width: 80px;
  flex-shrink: 0;
  font-size: 13px;
  color: #909399;
}

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

.type-tag {
  font-size: 11px;
  padding: 2px 8px;
  border-radius: 3px;
}

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

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