<template>
  <div class="platform-overview platform-no-padding">
    <OpenLayersMap 
      ref="mapRef" 
      :vehicleMovementControl="vehicleMovementRef"
      :vehicleCategories="vehicleCategories" 
      @setCategoryVisibility="handleSetCategoryVisibility"
      @drawTestRoute="handleDrawTestRoute"
    />
    <CarAlarm />
    
    <!-- 告警统计卡片 -->
    <div class="alarm-stats-card">
      <div class="stats-header">
        <span class="stats-title">告警统计</span>
        <span class="stats-time">{{ currentTime }}</span>
      </div>
      <div class="stats-content">
        <div class="stats-item" :class="{ 'has-new': hasNewWarning }">
          <img src="../../assets/images/count1.png" class="stats-icon">
          <div class="stats-text">
            <span class="stats-count">{{ warningCount }}</span>
            <span class="stats-label">冲突预警</span>
          </div>
          <span v-if="hasNewWarning" class="new-badge"></span>
        </div>
        <div class="stats-item" :class="{ 'has-new': hasNewAlert }">
          <img src="../../assets/images/count2.png" class="stats-icon">
          <div class="stats-text">
            <span class="stats-count">{{ alertCount }}</span>
            <span class="stats-label">冲突告警</span>
          </div>
          <span v-if="hasNewAlert" class="new-badge"></span>
        </div>
        <div class="stats-item" :class="{ 'has-new': hasNewBoundary }">
          <img src="../../assets/images/count3.png" class="stats-icon">
          <div class="stats-text">
            <span class="stats-count">{{ boundaryCount }}</span>
            <span class="stats-label">越界告警</span>
          </div>
          <span v-if="hasNewBoundary" class="new-badge"></span>
        </div>
        <div class="stats-item" :class="{ 'has-new': hasNewSpeed }">
          <img src="../../assets/images/count4.png" class="stats-icon">
          <div class="stats-text">
            <span class="stats-count">{{ speedCount }}</span>
            <span class="stats-label">超速告警</span>
          </div>
          <span v-if="hasNewSpeed" class="new-badge"></span>
        </div>
      </div>
    </div>
    
    <!-- 报警通知面板 -->
    <AlarmNotification 
      ref="alarmNotificationRef"
      v-if="showAlarmPanel" 
      @close="handleAlarmClose" 
    />
    <!-- 报警通知按钮 -->
    <div class="alarm-btn" @click="toggleAlarmPanel">
      <i class="alarm-icon"></i>
      <span class="alarm-badge" v-if="totalAlarmCount > 0">{{ totalAlarmCount }}</span>
    </div>
    <!-- 右侧展开/收起按钮 -->
    <img
      class="eventlist-toggle-btn"
      :class="{ 'btn-opened': showEventList }"
      :src="showEventList ? btn_left : btn_right"
      :alt="showEventList ? '收起车辆列表' : '展开车辆列表'"
      @click="toggleEventList"
    />
    <!-- 车辆列表 -->
    <Eventlist v-if="showEventList" />
 
    <!-- 车辆移动控制组件 -->
    <VehicleMovementControlRefactored :map="map" ref="vehicleMovementRef" v-if="map" />
    <!-- <VehicleDisplayControl :map="map" ref="vehicleMovementRef" v-if="map" /> -->

    <!-- 气象监测站弹窗 -->
    <WeatherStationPopup 
      v-if="showWeatherPopup" 
      :visible="showWeatherPopup"
      :station-data="selectedTrafficLight"
      :position="popupPosition"
      @close="handleWeatherPopupClose" 
    />


    <!-- 绘制工具栏 -->
    <!-- <div class="draw-toolbar">
      <div class="toolbar-title">绘制工具</div>
      <div class="toolbar-buttons">
        <button @click="startDrawLine" class="toolbar-button">绘制路线</button>
        <button @click="startDrawPolygon" class="toolbar-button">绘制区域</button>
        <button @click="clearDraw" class="toolbar-button clear">清除</button>
        <button @click="exportRouteData" class="toolbar-button export">导出数据</button>
        <button @click="importRouteData" class="toolbar-button import">导入数据</button>
      </div>
    </div>   -->

  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed, onActivated } from 'vue';
import OpenLayersMap from '../../components/map/OpenLayersMap.vue';
import CarAlarm from '../../components/map/info/carClarm.vue';
import Eventlist from '../../components/map/info/eventlist.vue';
import AlarmNotification from '../../components/map/info/AlarmNotification.vue';
import WeatherStationPopup from '../../components/map/controls/WeatherStationPopup.vue';
import VehicleMovementControlRefactored from '../../components/map/controls/VehicleMovementControlRefactored.vue';
import btn_left from '../../assets/images/btn_left.png';
import btn_right from '../../assets/images/btn_right.png';
// 导入路口API
import { listIntersection } from '@/api/road/intersection';
// 导入红绿灯API
import { listTrafficLight } from '@/api/road/trafficLight';

// 导入OpenLayers相关模块
import { Vector as VectorSource } from 'ol/source';
import { Vector as VectorLayer } from 'ol/layer';
import { Style, Fill, Stroke, RegularShape, Icon } from 'ol/style';
import { Point } from 'ol/geom';
import { Feature } from 'ol';
import { fromLonLat, transform } from 'ol/proj';
import { unByKey } from 'ol/Observable';
// 导入路口图标
import roadIcon from '../../assets/images/road.png';
// 导入红绿灯图标
import trafficLightIcon from '../../assets/images/light.svg';
// 导入红绿灯不同状态的图标
import redTrafficLightIcon from '../../assets/images/red.svg';
import yellowTrafficLightIcon from '../../assets/images/yellow.svg';
import greenTrafficLightIcon from '../../assets/images/green.svg';

const showEventList = ref(false); // 默认不显示列表
const showAlarmPanel = ref(false); // 默认不显示报警面板
// const alarmCount = ref(4); // 报警数量 - 已替换为计算属性totalAlarmCount
const mapRef = ref(null);
const vehicleMovementRef = ref(null);
const map = ref(null); // 存储地图实例

// 路口相关数据
const intersections = ref([]); // 存储路口数据
const intersectionLayer = ref(null); // 路口图层
const mapMoveListener = ref(null); // 地图移动监听器

// 红绿灯相关数据
const trafficLights = ref([]); // 存储红绿灯数据
const trafficLightLayer = ref(null); // 红绿灯图层

// 气象监测站弹窗相关
const showWeatherPopup = ref(false); // 控制气象监测站弹窗显示
const selectedTrafficLight = ref(null); // 选中的红绿灯信息
const popupPosition = ref({ x: 0, y: 0 }); // 弹窗位置

// 告警统计数据 - 基于真实alarmList计算
const warningCount = computed(() => {
  const alarmList = vehicleMovementRef.value?.alarmList || [];
  return alarmList.filter(alarm => alarm.type === 'car' && alarm.level === 'medium').length;
});

const alertCount = computed(() => {
  const alarmList = vehicleMovementRef.value?.alarmList || [];
  return alarmList.filter(alarm => alarm.type === 'car' && alarm.level === 'high').length;
});

const boundaryCount = computed(() => {
  const alarmList = vehicleMovementRef.value?.alarmList || [];
  return alarmList.filter(alarm => alarm.type === 'report').length;
});

const speedCount = computed(() => {
  const alarmList = vehicleMovementRef.value?.alarmList || [];
  return alarmList.filter(alarm => alarm.type === 'speed').length;
});

// 新告警标记 - 基于最近的告警时间判断
const hasNewWarning = computed(() => {
  const alarmList = vehicleMovementRef.value?.alarmList || [];
  const recentAlarms = alarmList.filter(alarm => 
    alarm.type === 'car' && alarm.level === 'medium' && 
    Date.now() - new Date(alarm.date).getTime() < 10000 // 10秒内的告警视为新告警
  );
  return recentAlarms.length > 0;
});

const hasNewAlert = computed(() => {
  const alarmList = vehicleMovementRef.value?.alarmList || [];
  const recentAlarms = alarmList.filter(alarm => 
    alarm.type === 'car' && alarm.level === 'high' && 
    Date.now() - new Date(alarm.date).getTime() < 10000
  );
  return recentAlarms.length > 0;
});

const hasNewBoundary = computed(() => {
  const alarmList = vehicleMovementRef.value?.alarmList || [];
  const recentAlarms = alarmList.filter(alarm => 
    alarm.type === 'report' && 
    Date.now() - new Date(alarm.date).getTime() < 10000
  );
  return recentAlarms.length > 0;
});

const hasNewSpeed = computed(() => {
  const alarmList = vehicleMovementRef.value?.alarmList || [];
  const recentAlarms = alarmList.filter(alarm => 
    alarm.type === 'speed' && 
    Date.now() - new Date(alarm.date).getTime() < 10000
  );
  return recentAlarms.length > 0;
});

// 当前时间
const currentTime = ref('');

// 告警通知相关
const alarmNotificationRef = ref(null);

// 监听vehicleMovementRef中的告警列表变化
watch(() => vehicleMovementRef.value?.alarmList, (newAlarmList) => {
  if (newAlarmList && alarmNotificationRef.value) {
    // 更新告警通知面板中的数据
    alarmNotificationRef.value.updateAlarmList(newAlarmList);
    
    // 告警数量现在通过计算属性自动更新
     // alarmCount.value = newAlarmList.length; // 不再需要手动更新
  }
}, { deep: true });

// 更新时间
function updateCurrentTime() {
  const now = new Date();
  currentTime.value = now.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
}

// 总告警数量计算
const totalAlarmCount = computed(() => {
  return warningCount.value + alertCount.value + boundaryCount.value + speedCount.value;
});

// 获取车辆分类数据，从VehicleMovementControl组件中获取
const vehicleCategories = computed(() => {
  return vehicleMovementRef.value?.vehicleCategories || {};
});

// 处理设置分类可见性
function handleSetCategoryVisibility(type, settings) {
  if (vehicleMovementRef.value && vehicleMovementRef.value.setCategoryVisibility) {
    vehicleMovementRef.value.setCategoryVisibility(type, settings);
  }
}

function handleDrawTestRoute() {
  if (vehicleMovementRef.value && vehicleMovementRef.value.drawTestRoute) {
    vehicleMovementRef.value.drawTestRoute();
  }
}

// 处理告警面板关闭事件
function handleAlarmClose() {
  showAlarmPanel.value = false;
  console.log('告警面板已关闭');
}

// 处理气象监测站弹窗关闭事件
function handleWeatherPopupClose() {
  showWeatherPopup.value = false;
  selectedTrafficLight.value = null;
  console.log('气象监测站弹窗已关闭');
}

// 处理地图点击事件（红绿灯点击）
function handleTrafficLightClick(event) {
  const feature = map.value.forEachFeatureAtPixel(event.pixel, function(feature) {
    return feature;
  });
  
  if (feature) {
    const featureProperties = feature.getProperties();
    // 检查是否点击的是红绿灯
    if (featureProperties.type === 'trafficLight') {
      selectedTrafficLight.value = featureProperties;
      
      // 计算弹窗位置（红绿灯右侧）
      const clickX = event.pixel[0];
      const clickY = event.pixel[1];
      
      // 获取地图容器的位置偏移
      const mapElement = map.value.getTargetElement();
      const mapRect = mapElement.getBoundingClientRect();
      
      // 计算屏幕坐标（红绿灯右侧20px处）
      popupPosition.value = {
        x: mapRect.left + clickX + 20,
        y: mapRect.top + clickY - 50 // 向上偏移50px，避免遮挡红绿灯
      };
      
      showWeatherPopup.value = true;
      console.log('点击了红绿灯:', featureProperties, '弹窗位置:', popupPosition.value);
    }
  }
}

// 判断是否为开发环境
const isDevelopment = process.env.NODE_ENV === 'development';

function toggleEventList() {
  showEventList.value = !showEventList.value;
}

function toggleAlarmPanel() {
  showAlarmPanel.value = !showAlarmPanel.value;
  
  // 如果面板显示，确保告警数据是最新的
  if (showAlarmPanel.value && alarmNotificationRef.value && vehicleMovementRef.value) {
    alarmNotificationRef.value.updateAlarmList(vehicleMovementRef.value.alarmList);
  }
}

function getRouteDrawControlExpose() {
  // 通过OpenLayersMap的ref获取RouteDrawControl的ref
  return mapRef.value?.$refs?.routeDrawControlRef;
}

function startDrawLine() {
  const routeDraw = getRouteDrawControlExpose();
  if (routeDraw && routeDraw.startDrawLine) {
    routeDraw.startDrawLine();
  }
}

function startDrawPolygon() {
  const routeDraw = getRouteDrawControlExpose();
  if (routeDraw && routeDraw.startDrawPolygon) {
    routeDraw.startDrawPolygon();
  }
}

function clearDraw() {
  const routeDraw = getRouteDrawControlExpose();
  if (routeDraw && routeDraw.clearDraw) {
    routeDraw.clearDraw();
  }
}

function exportRouteData() {
  const routeDraw = getRouteDrawControlExpose();
  if (routeDraw && routeDraw.exportRouteData) {
    routeDraw.exportRouteData();
  }
}

function importRouteData() {
  const routeDraw = getRouteDrawControlExpose();
  if (routeDraw && routeDraw.showImportDialog) {
    // 调用RouteDrawControl组件中的方法显示导入对话框
    routeDraw.showImportDialog = true;
  }
}

// 获取路口数据
async function getIntersections() {
  console.log('🔍 开始获取路口数据...');
  try {
    const response = await listIntersection();
    console.log('📡 API响应原始数据:', response);
    console.log('📊 响应数据类型:', typeof response, '是否为数组:', Array.isArray(response));
    
    if (response && Array.isArray(response)) {
      console.log('✅ 响应数据有效，路口数量:', response.length);
      
      intersections.value = response.map(item => {
        const mappedItem = {
          intersectionId: item.intersectionId,
          intersectionName: item.intersectionName,
          longitude: item.longitude,
          latitude: item.latitude,
          areaCode: item.areaCode || '',
          description: item.description || '',
          status: item.isActive ? '1' : '0',
          createTime: item.createdTime
        };
        console.log('🗺️ 映射路口数据:', mappedItem);
        return mappedItem;
      });
      
      console.log('✅ 获取路口数据成功，总数:', intersections.value.length);
      console.log('📍 处理后的路口数据:', intersections.value);
      
      // 渲染路口到地图上 - 已注释，只显示红绿灯
      // renderIntersectionsOnMap();
    } else {
      console.warn('⚠️ API响应数据无效或不是数组');
      intersections.value = [];
    }
  } catch (error) {
    console.error('❌ 获取路口列表失败:', error);
    console.error('❌ 错误详情:', error.message, error.stack);
    intersections.value = [];
  }
  
  // 添加固定位置的路口标记 - 已注释，只显示红绿灯
  // addFixedIntersectionMarker();
}

// 添加固定位置的路口标记
function addFixedIntersectionMarker() {
  if (!map.value) {
    console.warn('⚠️ 地图实例未初始化，无法添加固定路口标记');
    return;
  }
  
  console.log('📍 添加固定位置路口标记: 经度=120.0834104, 纬度=36.35406879');
  
  // 固定坐标
  const longitude = 120.0934104;
  const latitude = 36.35406879;
  
  // 将WGS84坐标转换为地图投影坐标 - 使用地图的投影系统
  const coordinate = transform([longitude, latitude], 'EPSG:4326', map.value.getView().getProjection());
  console.log('🔄 固定路口转换后的地图坐标:', coordinate);
  
  // 创建点几何对象
  const point = new Point(coordinate);
  
  // 创建特征对象
  const feature = new Feature({
    geometry: point,
    intersectionName: '固定路口标记',
    longitude: longitude,
    latitude: latitude,
    isFixed: true
  });
  
  // 设置样式
  feature.setStyle(createIntersectionStyle());
  
  // 创建矢量数据源
  const source = new VectorSource();
  source.addFeature(feature);
  
  // 创建矢量图层
  const fixedIntersectionLayer = new VectorLayer({
    source: source,
    zIndex: 2002, // 确保固定路口在最上层显示
  });
  
  // 添加到地图
  map.value.addLayer(fixedIntersectionLayer);
  console.log('✅ 固定路口标记已添加到地图');
}

// 创建路口图层样式
function createIntersectionStyle() {
  return new Style({
    image: new Icon({
      src: roadIcon, // 使用road.png图标
      scale: 0.05, // 增大图标缩放比例，确保可见
      anchor: [0.5, 0.5], // 图标锚点居中
      opacity: 1.0, // 确保完全不透明
    }),
  });
}

// 创建红绿灯图层样式
function createTrafficLightStyle(status = 'unknown', direction = 'ns') {
  // 根据状态选择不同的图标
  let iconSrc = trafficLightIcon; // 默认图标
  
  // 如果有状态信息，则根据状态选择图标
  if (status === 'red') {
    iconSrc = redTrafficLightIcon || trafficLightIcon;
  } else if (status === 'yellow') {
    iconSrc = yellowTrafficLightIcon || trafficLightIcon;
  } else if (status === 'green') {
    iconSrc = greenTrafficLightIcon || trafficLightIcon;
  }
  
  // 根据方向设置旋转角度
  const rotation = direction === 'ew' ? Math.PI / 2 : 0; // 东西方向旋转90度（π/2弧度）
  
  return new Style({
    image: new Icon({
      src: iconSrc, // 使用对应状态的图标
      scale: 0.2, // 设置图标缩放比例
      anchor: [0.5, 0.5], // 图标锚点居中
      opacity: 1.0, // 确保完全不透明
      rotation: rotation, // 设置旋转角度
    }),
  });
}

// 存储路口红绿灯状态
const intersectionTrafficLightStatus = ref({});

// 处理路口红绿灯状态更新
function handleIntersectionTrafficLightStatus(payload) {
  if (!payload) return;
  let status = 'unknown';
  if (payload.status) {
    status = payload.status;
  } else if (payload.ns_status || payload.ew_status) {
    status = payload.ns_status || payload.ew_status || 'unknown';
  } else {
    const sd = payload.serviceData ? payload.serviceData : payload;
    const phases = Array.isArray(sd && sd.phases) ? sd.phases : [];
    if (phases.length > 0) {
      const colors = phases.map(p => Number(p.phaseColor));
      if (colors.includes(3)) status = 'red';
      else if (colors.includes(4)) status = 'yellow';
      else if (colors.includes(2)) status = 'yellow';
      else if (colors.includes(1)) status = 'green';
    } else {
      const s = Number((sd && sd.trafficLightsStatus) ?? payload.trafficLightsStatus);
      if (s === 3) status = 'red';
      else if (s === 4) status = 'yellow';
      else if (s === 2) status = 'yellow';
      else if (s === 1) status = 'green';
    }
  }
  intersectionTrafficLightStatus.value.globalStatus = status;
  intersectionTrafficLightStatus.value.timestamp = Date.now();
  updateTrafficLightIconsOnMap();
}

// 更新地图上红绿灯图标
function updateTrafficLightIconsOnMap() {
  if (!trafficLightLayer.value || !trafficLightLayer.value.getSource()) {
    return;
  }
  
  const source = trafficLightLayer.value.getSource();
  const features = source.getFeatures();
  
  const status = intersectionTrafficLightStatus.value.globalStatus || 'unknown';
  features.forEach(feature => {
    const trafficLightData = feature.getProperties();
    if (trafficLightData.type !== 'trafficLight') return;
    feature.setStyle(createTrafficLightStyle(status, 'ns'));
  });
  source.changed();
}

// 将处理函数暴露给全局，以便VehicleMovementControlRefactored.vue可以调用
window.updateTrafficLightStatus = handleIntersectionTrafficLightStatus;

// 渲染路口到地图上
function renderIntersectionsOnMap() {
  console.log('🎨 开始渲染路口到地图...');
  console.log('🗺️ 地图实例状态:', map.value ? '已初始化' : '未初始化');
  console.log('📍 路口数据数量:', intersections.value.length);
  
  if (!map.value) {
    console.warn('⚠️ 地图实例未初始化，无法渲染路口');
    return;
  }
  
  if (!intersections.value.length) {
    console.warn('⚠️ 没有路口数据可渲染');
    return;
  }

  // 如果已存在路口图层，先移除
  if (intersectionLayer.value) {
    console.log('🗑️ 移除现有路口图层');
    map.value.removeLayer(intersectionLayer.value);
  }

  // 创建新的矢量数据源
  const source = new VectorSource();
  let validIntersectionCount = 0;
  let invalidIntersectionCount = 0;

  // 为每个路口创建特征点
  intersections.value.forEach((intersection, index) => {
    console.log(`🔍 处理第${index + 1}个路口:`, intersection);
    
    // 确保经纬度存在
    if (intersection.longitude && intersection.latitude) {
      const lon = parseFloat(intersection.longitude);
      const lat = parseFloat(intersection.latitude);
      
      console.log(`📍 路口 "${intersection.intersectionName}" 坐标: [${lon}, ${lat}]`);
      
      // 检查坐标是否有效
      if (isNaN(lon) || isNaN(lat)) {
        console.warn(`⚠️ 路口 "${intersection.intersectionName}" 坐标无效: [${intersection.longitude}, ${intersection.latitude}]`);
        invalidIntersectionCount++;
        return;
      }
      
      // 将WGS84坐标转换为地图投影坐标 - 使用地图的投影系统
      const coordinate = transform([lon, lat], 'EPSG:4326', map.value.getView().getProjection());
      console.log(`🔄 转换后的地图坐标:`, coordinate);
      
      // 创建点几何对象
      const point = new Point(coordinate);
      
      // 创建特征对象
      const feature = new Feature({
        geometry: point,
        ...intersection
      });
      
      // 设置样式
      feature.setStyle(createIntersectionStyle());
      
      // 添加到数据源
      source.addFeature(feature);
      validIntersectionCount++;
      
      console.log(`✅ 路口 "${intersection.intersectionName}" 已添加到地图`);
    } else {
      console.warn(`⚠️ 路口 "${intersection.intersectionName}" 缺少经纬度信息:`, {
        longitude: intersection.longitude,
        latitude: intersection.latitude
      });
      invalidIntersectionCount++;
    }
  });

  console.log(`📊 路口处理统计: 有效=${validIntersectionCount}, 无效=${invalidIntersectionCount}`);

  if (validIntersectionCount === 0) {
    console.warn('⚠️ 没有有效的路口坐标可以渲染');
    return;
  }

  // 添加一个测试路口点来验证图层是否正常工作
  const testCoordinate = transform([120.3, 36.1], 'EPSG:4326', map.value.getView().getProjection());
  const testFeature = new Feature({
    geometry: new Point(testCoordinate),
    name: '测试路口点'
  });
  testFeature.setStyle(createIntersectionStyle());
  source.addFeature(testFeature);
  console.log('🧪 已添加测试路口点用于验证图层显示');

  // 创建矢量图层
  intersectionLayer.value = new VectorLayer({
    source: source,
    zIndex: 2000, // 大幅提高zIndex确保在所有图层最上层显示
  });

  console.log('🎨 创建路口图层:', intersectionLayer.value);
  console.log('📍 图层特征数量:', source.getFeatures().length);

  // 添加到地图
  map.value.addLayer(intersectionLayer.value);
  console.log('✅ 路口图层已添加到地图');
  
  // 强制设置图层层级关系，确保路口图层在最上层
  setTimeout(() => {
    const layers = map.value.getLayers().getArray();
    layers.forEach((layer, index) => {
      if (layer.getSource && layer.getSource().constructor.name === 'TileSuperMapRest') {
        // 瓦片图层设置为最底层
        layer.setZIndex(0);
        console.log('🗺️ 设置瓦片图层zIndex为0');
      }
    });
    // 确保路口图层在最上层
    intersectionLayer.value.setZIndex(2000);
    console.log('🗺️ 设置路口图层zIndex为2000');
  }, 100);
  
  // 获取地图当前图层列表
  const layers = map.value.getLayers().getArray();
  console.log('🗺️ 地图当前图层数量:', layers.length);
  console.log('🗺️ 地图所有图层:', layers.map(layer => layer.constructor.name));
}

// 获取红绿灯数据
async function getTrafficLights() {
  console.log('🚦 开始获取红绿灯数据...');
  try {
    const response = await listTrafficLight();
    console.log('📡 红绿灯API响应原始数据:', response);
    console.log('📊 红绿灯响应数据类型:', typeof response, '是否为数组:', Array.isArray(response));
    
    let trafficLightData = [];
    if (Array.isArray(response)) {
      trafficLightData = response;
    } else if (response && response.rows && Array.isArray(response.rows)) {
      trafficLightData = response.rows;
    } else if (response && response.data && Array.isArray(response.data)) {
      trafficLightData = response.data;
    }
    
    if (trafficLightData.length > 0) {
      console.log('✅ 红绿灯响应数据有效，数量:', trafficLightData.length);
      
      // 处理红绿灯数据，根据intersectionId匹配路口信息
      console.log('🔍 开始处理红绿灯数据匹配...');
      console.log('📊 路口数据总数:', intersections.value.length);
      console.log('📊 红绿灯数据总数:', trafficLightData.length);
      
      // 输出路口ID列表用于调试
      const intersectionIds = intersections.value.map(i => i.intersectionId);
      console.log('📍 可用的路口ID列表:', intersectionIds);
      
      trafficLights.value = trafficLightData.map((trafficLight, index) => {
        console.log(`🔍 处理第${index + 1}个红绿灯:`, {
          deviceId: trafficLight.deviceId,
          deviceName: trafficLight.deviceName,
          intersectionId: trafficLight.intersectionId,
          intersectionIdType: typeof trafficLight.intersectionId
        });
        
        // 根据intersectionId查找对应的路口信息（支持类型转换匹配）
        const matchedIntersection = intersections.value.find(intersection => {
          // 严格匹配
          const strictMatch = intersection.intersectionId === trafficLight.intersectionId;
          // 字符串转换匹配
          const stringMatch = String(intersection.intersectionId) === String(trafficLight.intersectionId);
          // 数字转换匹配
          const numberMatch = Number(intersection.intersectionId) === Number(trafficLight.intersectionId);
          
          const match = strictMatch || stringMatch || numberMatch;
          
          if (!match) {
            console.log(`❌ 不匹配: 路口ID ${intersection.intersectionId}(${typeof intersection.intersectionId}) !== 红绿灯ID ${trafficLight.intersectionId}(${typeof trafficLight.intersectionId})`);
          } else if (!strictMatch) {
            console.log(`💡 类型转换匹配成功: 路口ID ${intersection.intersectionId} 与 红绿灯ID ${trafficLight.intersectionId}`);
          }
          
          return match;
        });
        
        if (matchedIntersection) {
          console.log(`✅ 找到匹配的路口: ${matchedIntersection.intersectionName} (ID: ${matchedIntersection.intersectionId})`);
          console.log('📍 路口坐标:', {
            longitude: matchedIntersection.longitude,
            latitude: matchedIntersection.latitude
          });
          return {
            ...trafficLight,
            intersectionName: matchedIntersection.intersectionName,
            longitude: matchedIntersection.longitude,
            latitude: matchedIntersection.latitude,
            areaCode: matchedIntersection.areaCode,
            description: matchedIntersection.description
          };
        } else {
          console.warn(`⚠️ 未找到匹配的路口，红绿灯intersectionId: ${trafficLight.intersectionId} (类型: ${typeof trafficLight.intersectionId})`);
          console.warn('🔍 尝试查找相似的路口ID...');
          intersections.value.forEach(intersection => {
            if (String(intersection.intersectionId) === String(trafficLight.intersectionId)) {
              console.log('💡 发现字符串匹配的路口:', intersection.intersectionName);
            }
          });
          return {
            ...trafficLight,
            intersectionName: '未知路口',
            longitude: null,
            latitude: null
          };
        }
      });
      
      console.log('✅ 获取红绿灯数据成功，总数:', trafficLights.value.length);
      console.log('📍 处理后的红绿灯数据:', trafficLights.value);
      
      // 渲染红绿灯到地图上
      renderTrafficLightsOnMap();
    } else {
      console.warn('⚠️ 红绿灯API响应数据无效或为空');
      trafficLights.value = [];
    }
  } catch (error) {
    console.error('❌ 获取红绿灯列表失败:', error);
    console.error('❌ 错误详情:', error.message, error.stack);
    trafficLights.value = [];
  }
}

// 渲染红绿灯到地图上
function renderTrafficLightsOnMap() {
  console.log('🚦 开始渲染红绿灯到地图...');
  console.log('🗺️ 地图实例状态:', map.value ? '已初始化' : '未初始化');
  console.log('📍 红绿灯数据数量:', trafficLights.value.length);
  
  if (!map.value) {
    console.warn('⚠️ 地图实例未初始化，无法渲染红绿灯');
    return;
  }

  // 如果已存在红绿灯图层，先移除
  if (trafficLightLayer.value) {
    console.log('🗑️ 移除现有红绿灯图层');
    map.value.removeLayer(trafficLightLayer.value);
  }

  // 创建新的矢量数据源
  const source = new VectorSource();
  let validTrafficLightCount = 0;
  let invalidTrafficLightCount = 0;

  // 添加用户提供的固定坐标点
  const testTrafficLights = [
    {
      id: 'fixed-1',
      longitude: 120.09986800557976,
      latitude: 36.35086289387643,
      intersectionName: '固定坐标点1',
      status: 'green'
    },
    {
      id: 'fixed-2', 
      longitude: 120.09437418546923,
      latitude: 36.34969069796734,
      intersectionName: '固定坐标点2',
      status: 'red'
    },
    {
      id: 'fixed-3',
      longitude: 120.0857115242345,
      latitude: 36.346946273836345,
      intersectionName: '固定坐标点3',
      status: 'yellow'
    }
  ];

  // 先渲染固定坐标点，并为每个点添加配对的红绿灯（右侧）
  testTrafficLights.forEach((trafficLight, index) => {
    console.log(`🔍 处理固定坐标点${index + 1}:`, trafficLight);
    
    const lon = parseFloat(trafficLight.longitude);
    const lat = parseFloat(trafficLight.latitude);
    
    console.log(`📍 固定坐标点 "${trafficLight.intersectionName}" 位置: [${lon}, ${lat}]`);
    
    // 将WGS84坐标转换为地图投影坐标
    const coordinate = transform([lon, lat], 'EPSG:4326', map.value.getView().getProjection());
    console.log(`🔄 转换后的地图坐标:`, coordinate);
    
    // 创建点几何对象
    const point = new Point(coordinate);
    
    // 创建特征对象
    const feature = new Feature({
      geometry: point,
      ...trafficLight,
      type: 'trafficLight',
      deviceName: trafficLight.intersectionName + ' (南北方向)',
      intersectionId: trafficLight.id,
      deviceId: trafficLight.id + '-ns'
    });
    
    // 设置样式（使用状态）
    feature.setStyle(createTrafficLightStyle(trafficLight.status, 'ns'));
    
    // 添加到数据源
    source.addFeature(feature);
    validTrafficLightCount++;
    
    console.log(`✅ 固定坐标点 "${trafficLight.intersectionName}" 已添加到地图`);
    
    // 为每个固定坐标点添加一个配对的红绿灯（在其右侧，表示东西方向）
    // 右侧约10米的位置（根据经纬度换算）
    const offsetLon = lon +0.0008; // 约10米的经度偏移
    const offsetLat = lat-0.0005;
    const offsetCoordinate = transform([offsetLon, offsetLat], 'EPSG:4326', map.value.getView().getProjection());
    const offsetPoint = new Point(offsetCoordinate);
    
    const offsetFeature = new Feature({
      geometry: offsetPoint,
      ...trafficLight,
      id: trafficLight.id + '-ew', // 东西方向标识
      longitude: offsetLon,
      latitude: offsetLat,
      type: 'trafficLight',
      deviceName: trafficLight.intersectionName + ' (东西方向)',
      intersectionId: trafficLight.id,
      deviceId: trafficLight.id + '-ew'
    });
    
    // offsetFeature.setStyle(createTrafficLightStyle(trafficLight.status, 'ew'));
    // source.addFeature(offsetFeature);
    // validTrafficLightCount++;
    
    // console.log(`✅ 固定坐标点 "${trafficLight.intersectionName}" 的配对红绿灯已添加到地图`);
  });

  // 为每个API获取的红绿灯创建特征点
  trafficLights.value.forEach((trafficLight, index) => {
    console.log(`🔍 处理第${index + 1}个红绿灯:`, trafficLight);
    
    // 确保经纬度存在（来自匹配的路口）
    if (trafficLight.longitude && trafficLight.latitude) {
      const lon = parseFloat(trafficLight.longitude);
      const lat = parseFloat(trafficLight.latitude);
      
      console.log(`📍 红绿灯 "${trafficLight.deviceName}" 位置: [${lon}, ${lat}] (路口: ${trafficLight.intersectionName})`);
      
      // 检查坐标是否有效
      if (isNaN(lon) || isNaN(lat)) {
        console.warn(`⚠️ 红绿灯 "${trafficLight.deviceName}" 坐标无效: [${trafficLight.longitude}, ${trafficLight.latitude}]`);
        invalidTrafficLightCount++;
        return;
      }
      
      // 将WGS84坐标转换为地图投影坐标
      const coordinate = transform([lon, lat], 'EPSG:4326', map.value.getView().getProjection());
      console.log(`🔄 转换后的地图坐标:`, coordinate);
      
      // 创建点几何对象
      const point = new Point(coordinate);
      
      // 创建特征对象
      const feature = new Feature({
        geometry: point,
        ...trafficLight,
        type: 'trafficLight', // 标识这是红绿灯特征
        deviceName: trafficLight.deviceName + ' (南北方向)',
        deviceId: trafficLight.deviceId + '-ns'
      });
      
      // 设置样式（使用状态）
      feature.setStyle(createTrafficLightStyle(trafficLight.status || 'unknown', 'ns'));
      
      // 添加到数据源
      source.addFeature(feature);
      validTrafficLightCount++;
      
      console.log(`✅ 红绿灯 "${trafficLight.deviceName}" 已添加到地图`);
      
      // 为API获取的每个红绿灯添加一个配对的红绿灯（在其右侧，表示东西方向）
      const offsetLon = lon + 0.0001; // 约10米的经度偏移
      
      const offsetCoordinate = transform([offsetLon, lat], 'EPSG:4326', map.value.getView().getProjection());
      const offsetPoint = new Point(offsetCoordinate);
      
      const offsetFeature = new Feature({
        geometry: offsetPoint,
        ...trafficLight,
        id: trafficLight.id + '-ew', // 东西方向标识
        longitude: offsetLon,
        latitude: lat,
        type: 'trafficLight',
        deviceName: (trafficLight.deviceName || trafficLight.intersectionName) + ' (东西方向)',
        deviceId: trafficLight.deviceId + '-ew'
      });
      
      offsetFeature.setStyle(createTrafficLightStyle(trafficLight.status || 'unknown', 'ew'));
      source.addFeature(offsetFeature);
      validTrafficLightCount++;
      
      console.log(`✅ 红绿灯 "${trafficLight.deviceName}" 的配对红绿灯已添加到地图`);
    } else {
      console.warn(`⚠️ 红绿灯 "${trafficLight.deviceName}" 缺少经纬度信息 (未匹配到路口):`, {
        intersectionId: trafficLight.intersectionId,
        longitude: trafficLight.longitude,
        latitude: trafficLight.latitude
      });
      invalidTrafficLightCount++;
    }
  });

  console.log(`📊 红绿灯处理统计: 有效=${validTrafficLightCount}, 无效=${invalidTrafficLightCount}`);

  if (validTrafficLightCount === 0) {
    console.warn('⚠️ 没有有效的红绿灯坐标可以渲染');
    return;
  }

  // 创建矢量图层
  trafficLightLayer.value = new VectorLayer({
    source: source,
    zIndex: 2001, // 设置在路口图层之上
  });

  console.log('🚦 创建红绿灯图层:', trafficLightLayer.value);
  console.log('📍 图层特征数量:', source.getFeatures().length);

  // 添加到地图
  map.value.addLayer(trafficLightLayer.value);
  console.log('✅ 红绿灯图层已添加到地图');
  
  // 初始化所有红绿灯图标
  updateTrafficLightIconsOnMap();
  
  // 强制设置图层层级关系
  setTimeout(() => {
    // 确保红绿灯图层在路口图层之上
    trafficLightLayer.value.setZIndex(2001);
    console.log('🗺️ 设置红绿灯图层zIndex为2001');
  }, 100);
}

// 组件激活时检查WebSocket状态
onActivated(() => {
  console.log('平台概览组件被激活');
  // 延迟检查，确保子组件已激活
  setTimeout(() => {
    if (vehicleMovementRef.value) {
      const wsConnected = vehicleMovementRef.value.wsConnected;
      console.log('WebSocket连接状态:', wsConnected);
      
      // 如果WebSocket未连接，尝试重连
      if (!wsConnected) {
        console.log('WebSocket未连接，尝试重新连接');
        vehicleMovementRef.value.reconnectWebSocket();
      }
    }
  }, 1000);
});

onMounted(() => {
  document.querySelector('.app-main')?.classList.add('platform-no-padding');
  
  // 初始化时间
  updateCurrentTime();
  
  // 设置定时器更新时间
  const timeInterval = setInterval(updateCurrentTime, 1000);
  
  // 获取地图实例
  if (mapRef.value) {
    // 等待地图实例初始化完成
    setTimeout(async () => {
      map.value = mapRef.value.map;
      console.log('地图实例已获取:', map.value);
      
      // 获取路口数据并渲染
      await getIntersections();
      
      // 获取红绿灯数据并渲染（需要等待路口数据加载完成）
      // await getTrafficLights(); // 已注释，不通过API获取红绿灯数据
      
      // 直接渲染固定的红绿灯坐标点
      renderTrafficLightsOnMap();
      
      // 添加地图点击事件监听器
      map.value.on('click', handleTrafficLightClick);
    }, 1000);
  }
  
  // 组件卸载时清理定时器
  onUnmounted(() => {
    clearInterval(timeInterval);
    // 移除地图监听器
    if (mapMoveListener.value) {
      unByKey(mapMoveListener.value);
    }
  });
  
  // 将处理函数暴露给全局，以便VehicleMovementControlRefactored.vue可以调用
  window.updateTrafficLightStatus = handleIntersectionTrafficLightStatus;
  
  // 移除了模拟告警定时器，现在使用真实告警数据
});

onUnmounted(() => {
  document.querySelector('.app-main')?.classList.remove('platform-no-padding');
  // 移除路口图层
  if (map.value && intersectionLayer.value) {
    map.value.removeLayer(intersectionLayer.value);
  }
  // 移除地图监听器
  if (mapMoveListener.value) {
    unByKey(mapMoveListener.value);
  }
});

// 监听地图实例引用变化
watch(() => mapRef.value?.map, (newMap) => {
  if (newMap) {
    map.value = newMap;
    console.log('地图实例已更新:', map.value);
    
    // 获取路口数据并渲染
    getIntersections();
  }
});
</script>

<style scoped lang="scss">
.platform-overview {
  width: 100%;
  height:calc(100vh - 60px);
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  z-index:1;
}

/* 告警统计卡片 */
.alarm-stats-card {
  position: absolute;
  top: 23%;
  left: 28px;
  width: 246px;
  height: 147px;
  // background: linear-gradient(to top,#94B0DB,#4F81CC,#3D629A);
  border-radius: 9px;
  box-shadow: 0 10px 15px rgba(2, 2, 2, 0.25);
  color: #fff;
  z-index: 1000;
  backdrop-filter: blur(5px);
  border: 0.5px solid rgba(222, 213, 213, 0.53);
  overflow: hidden;
}
 

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 10px; /* 减小内边距 */
  background-color: #343744;
  border-bottom: 0.5px solid rgba(222, 213, 213, 0.53);
}

.stats-title {
  font-size: 16px;
  font-weight: bold;
  color: rgba(255, 255, 255, 1);
}

.stats-time {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.65);
  font-family: 'PingFang SC', monospace;
}

.stats-content {
  width: 246px;
  height: 116px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1px;
  background-color: #424851;
  padding: 1px;
}

.stats-item {
  
  position: relative;
  padding: 8px 10px; /* 减小内边距 */
  display: flex;
  flex-direction: row; /* 改为水平布局 */
  align-items: center;
  width: 123px;
  height: 58px;
  // background-color: rgba(41, 44, 56, 0.95);
  transition: all 0.3s ease;
  
  // &:hover {
    
  //   background-color: rgba(52, 122, 226, 0.1);
  // }
  
  &.has-new {
    // background-color: rgba(255, 77, 79, 0.15);
    // 线性渐变角度
    background: linear-gradient(135deg,rgba(240, 97, 97, 1) ,rgba(237, 180, 180, 0.48));
    animation: pulse 1.5s infinite;
    
    .stats-count {
      color: rgba(204, 14, 14, 1);
    }
  }
}

.stats-icon {

  margin-right: 10px; /* 图标和文字之间的间距 */
  width: 39px;
  height: 39px;
  object-fit: contain;
  // border:1px solid red;
}


.stats-text {
  display: flex;
  flex-direction: column;
  width: 56px;
  height: 37px;
  justify-content: center;
}

.stats-count {
  font-size: 16px;
  font-weight: bold;
  width: 20px;
  height: 20px;
  color: rgba(255, 255, 255, 1);
}

.stats-label {
  font-size: 14px;
  font-weight: bold;
  color: rgba(255, 255, 255, 1);
  margin-top: 2px;
  width: 56px;
  height: 20px;
}

.new-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 6px;
  height: 6px;
  background-color: #FF4D4F;
  border-radius: 50%;
  box-shadow: 0 0 5px rgba(255, 77, 79, 0.5);
}

@keyframes pulse {
  0% {
    background-color: rgba(255, 77, 79, 0.15);
  }
  50% {
    background-color: rgba(255, 77, 79, 0.3);
  }
  100% {
    background-color: rgba(255, 77, 79, 0.15);
  }
}

/* 报警通知按钮 */
.alarm-btn {
  position: absolute;
  left: 25px;
  top: 15%;
  width: 40px;
  height: 40px;
  background-color: rgba(53, 61, 72, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1001;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.alarm-icon {
  width: 24px;
  height: 24px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23ffffff"><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/></svg>');
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
}

.alarm-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: #FF4D4F;
  color: white;
  font-size: 12px;
  min-width: 18px;
  height: 18px;
  border-radius: 9px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 4px;
}

/* 右侧展开/收起按钮样式 */
.eventlist-toggle-btn {
  position: absolute;
  top: 50%;
  right: 0;
  z-index: 2001;
  width: 30px;
  height: 58px;
  transform: translateY(-50%);
  cursor: pointer;
  transition: right 0.3s ease;
}

/* 按钮打开状态 - 移到左侧 */
.eventlist-toggle-btn.btn-opened {
  right: 405px; 
}

/* 测试按钮 - 仅开发阶段使用 */
.test-controls {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 2000;
}

.test-btn {
  padding: 8px 16px;
  background-color: rgba(33, 150, 243, 0.8);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.test-btn:hover {
  background-color: rgba(33, 150, 243, 1);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

/* 绘制工具栏 */
.draw-toolbar {
  position: absolute;
  top: 20px;
  right: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  z-index: 2000;
  width: 200px;
  overflow: hidden;
}

.toolbar-title {
  padding: 10px;
  background-color: #0096ff;
  color: white;
  font-weight: bold;
  text-align: center;
}

.toolbar-buttons {
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.toolbar-button {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f5f5f5;
  cursor: pointer;
  transition: all 0.2s;
}

.toolbar-button:hover {
  background-color: #e0e0e0;
}

.toolbar-button.clear {
  background-color: #f44336;
  color: white;
  border-color: #d32f2f;
}

.toolbar-button.clear:hover {
  background-color: #d32f2f;
}

.toolbar-button.export {
  background-color: #4caf50;
  color: white;
  border-color: #388e3c;
}

.toolbar-button.export:hover {
  background-color: #388e3c;
}

.toolbar-button.import {
  background-color: #ff9800;
  color: white;
  border-color: #f57c00;
}

.toolbar-button.import:hover {
  background-color: #f57c00;
}

/* 只影响本页，精准去除AppMain的左右padding */
// :deep(.platform-no-padding) .app-main {
//   padding-left: 0 !important;
//   padding-right: 0 !important;
// }
</style>

<style>
.app-main.platform-no-padding {
  padding-left: 0 !important;
  padding-right: 0 !important;
}
</style>
