<template>
  <!-- 气象监测站弹窗 -->
  <div class="weather-station-container" v-if="weatherStationVisible">
    <div class="weather-station-box">
      <div class="weather-station-header">
        <span>气象监测站</span>
        <img  class="weather-station-close"  src="../../../assets/images/close_icon.png" alt="" @click="weatherStationVisible = false" />
      </div>
      <div class="weather-station-content">
        <div class="weather-station-title">
          <span>信号灯XH001 | 实时监测</span>
          <!-- <span class="weather-station-status">✓</span> -->
          <img class="weather-station-status" src="../../../assets/images/weather_icon.png" alt="气象监测站" />
        </div>
        <div class="weather-station-info-container">
          <div class="weather-station-info-row">
            <div class="weather-station-info-item">
              <span class="weather-info-label">温度:</span>
              <span class="weather-info-value">{{ weatherData.temperature }}°C</span>
            </div>
            <div class="weather-station-info-item">
              <span class="weather-info-label">湿度:</span>
              <span class="weather-info-value">{{ weatherData.humidity }}%</span>
            </div>
          </div>
          <div class="weather-station-info-row">
            <div class="weather-station-info-item">
              <span class="weather-info-label">风速:</span>
              <span class="weather-info-value">{{ weatherData.windSpeed }}m/s</span>
            </div>
            <div class="weather-station-info-item">
              <span class="weather-info-label">能见度:</span>
              <span class="weather-info-value">{{ weatherData.visibility }}km</span>
            </div>
          </div>
          <div class="weather-station-info-row">
            <div class="weather-station-info-item">
              <span class="weather-info-label">风向:</span>
              <span class="weather-info-value">{{ weatherData.windDirection }}</span>
            </div>
            <div class="weather-station-info-item">
              <span class="weather-info-label">湿滑程度:</span>
              <span class="weather-info-value">{{ weatherData.wetness }}</span>
            </div>
          </div>
          <div class="weather-station-info-row">
            <div class="weather-station-info-item">
              <span class="weather-info-label">气压:</span>
              <span class="weather-info-value">{{ weatherData.pressure }}hPa</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 车辆详情弹窗 -->
  <div class="vehicle-detail-popup" v-if="vehicleDetailVisible" :style="detailPopupStyle">
    <div class="vehicle-detail-header">
      <div class="vehicle-detail-title">车辆详情</div>
      <div class="vehicle-detail-close" @click="vehicleDetailVisible = false">×</div>
    </div>
    <div class="vehicle-detail-content">
      <div class="vehicle-detail-info-row">
        <div class="vehicle-detail-info-item">
          <span class="vehicle-info-label">车辆ID:</span>
          <span class="vehicle-info-value">{{ vehicleDetail.id }}</span>
        </div>
        <div class="vehicle-detail-info-item">
          <span class="vehicle-info-label">车辆类型:</span>
          <span class="vehicle-info-value">{{ vehicleDetail.type }}</span>
        </div>
      </div>
      <div class="vehicle-detail-info-row">
        <div class="vehicle-detail-info-item">
          <span class="vehicle-info-label">状态:</span>
          <span class="vehicle-info-value">{{ vehicleDetail.status }}</span>
        </div>
        <div class="vehicle-detail-info-item">
          <span class="vehicle-info-label">开始时间:</span>
          <span class="vehicle-info-value">{{ vehicleDetail.startTime }}</span>
        </div>
      </div>
      <div class="vehicle-detail-info-row">
        <div class="vehicle-detail-info-item">
          <span class="vehicle-info-label">当前位置:</span>
          <span class="vehicle-info-value">{{ vehicleDetail.currentLocation }}</span>
        </div>
        <div class="vehicle-detail-info-item">
          <span class="vehicle-info-label">总距离:</span>
          <span class="vehicle-info-value">{{ vehicleDetail.totalDistance }}</span>
        </div>
      </div>
      <div class="vehicle-detail-info-row">
        <div class="vehicle-detail-info-item">
          <span class="vehicle-info-label">起始位置:</span>
          <span class="vehicle-info-value">{{ vehicleDetail.startLocation }}</span>
        </div>
        <div class="vehicle-detail-info-item">
          <span class="vehicle-info-label">目标位置:</span>
          <span class="vehicle-info-value">{{ vehicleDetail.endLocation }}</span>
        </div>
      </div>
      <div class="vehicle-detail-info-row">
        <div class="vehicle-detail-info-item">
          <span class="vehicle-info-label">电量:</span>
          <span class="vehicle-info-value">{{ vehicleDetail.battery }}</span>
        </div>
        <div class="vehicle-detail-info-item">
          <span class="vehicle-info-label">负责人:</span>
          <span class="vehicle-info-value">{{ vehicleDetail.manager }}</span>
        </div>
      </div>
      <div class="vehicle-detail-info-row">
        <div class="vehicle-detail-info-item">
          <span class="vehicle-info-label">联系电话:</span>
          <span class="vehicle-info-value">{{ vehicleDetail.phone }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, onActivated, onDeactivated } from 'vue';
import { Vector as VectorSource } from 'ol/source';
import { Vector as VectorLayer } from 'ol/layer';
import { Style, Icon } from 'ol/style';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import Overlay from 'ol/Overlay';
import { transform } from 'ol/proj';
// 导入WebSocketService
import WebSocketService, { createWebSocket, resetWebSocketInstance } from '../../../utils/websocket.js';

// 为SockJS提供polyfill
if (typeof window !== 'undefined' && !window.global) {
  window.global = window;
}

// 导入车辆图标
import carIcon from '../../../assets/images/noPeopleCar.png';
import aircraftIcon from '../../../assets/images/Aircraft.png';
import aircraft1Icon from '../../../assets/images/Aircraft1.png';
import labelBg from '../../../assets/images/label_bg.png';
import airportBg from '../../../assets/images/airport_bg.png';
import airportOutBg from '../../../assets/images/airport_out.png';
import alarmBg from '../../../assets/images/alarm_bg.png';
import warningBg from '../../../assets/images/warning_bg.png';
import warningCarIcon from '../../../assets/images/warning_car.png'; // 超速警告车辆图标

// 定义props接收地图实例
const props = defineProps({
  map: Object
});

// 气象监测站数据
const weatherStationVisible = ref(true); // 默认显示

// 气象数据
const weatherData = ref({
  temperature: '22.5',
  humidity: '68',
  windSpeed: '3.2',
  visibility: '8.5',
  pressure: '1013.2',
  windDirection: '北风',
  wetness: '干燥',
  updateTime: Date.now()
});

// 车辆详情数据
const vehicleDetailVisible = ref(false); // 修改为默认隐藏
const vehicleDetail = ref({
  id: 'QN001',
  type: '驱鸟车',
  status: '任务中',
  startTime: '11-19 11:30',
  currentLocation: 'A区T3点',
  startLocation: 'T1航站楼',
  endLocation: 'T3航站楼',
  totalDistance: '1.3km',
  battery: '60%',
  manager: '张三',
  phone: '18661910988'
});

// 弹窗位置样式
const detailPopupStyle = ref({
  left: '0px',
  top: '0px'
});

// WebSocket连接状态
const wsConnected = ref(false);
let wsService = null;
let reconnectTimer = null;

// 车辆数据存储
const vehicles = ref({});
let vehicleLayer = null;
let vehicleSource = null;

// 车辆超速状态超时计时器存储
const speedViolationTimers = {};

// 动态收集所有车辆/航空器类别
const vehicleCategories = ref({});

// 创建车辆图层
function createVehicleLayer() {
  if (!props.map) return;
  
  // 创建矢量数据源
  vehicleSource = new VectorSource();
  
  // 创建矢量图层
  vehicleLayer = new VectorLayer({
    source: vehicleSource,
    zIndex: 20, // 确保在其他图层之上
  });
  
  // 添加图层到地图
  props.map.addLayer(vehicleLayer);
  console.log('车辆移动图层已创建');
  
  // 设置地图监听器
  setupMapListeners();
  
  // 添加点击事件监听
  props.map.on('click', handleMapClick);
}

// 处理地图点击事件
function handleMapClick(event) {
  const feature = props.map.forEachFeatureAtPixel(event.pixel, function(feature) {
    return feature;
  });
  
  if (feature) {
    const objectId = feature.getId();
    if (objectId && vehicles.value[objectId]) {
      // 获取车辆数据
      const vehicle = vehicles.value[objectId];
      
      // 更新车辆详情
      vehicleDetail.value = {
        id: objectId,
        type: vehicle.type,
        status: '任务中', // 可以根据实际数据设置
        startTime: '11-19 11:30', // 示例数据，实际应从vehicle中获取
        currentLocation: '当前位置', // 可以转换坐标为地理位置描述
        startLocation: 'T1航站楼',
        endLocation: 'T3航站楼',
        totalDistance: '1.3km',
        battery: '60%',
        manager: '张三',
        phone: '18661910988'
      };
      
      // 获取点击位置在屏幕上的坐标
      const pixel = event.pixel;
      const viewportPosition = props.map.getViewport().getBoundingClientRect();
      
      // 设置弹窗位置，右下角
      detailPopupStyle.value = {
        left: (viewportPosition.left + pixel[0] + 10) + 'px',
        top: (viewportPosition.top + pixel[1] + 10) + 'px'
      };
      
      // 显示详情弹窗
      vehicleDetailVisible.value = true;
    } else {
      // 如果点击的不是车辆图标，隐藏弹窗
      vehicleDetailVisible.value = false;
    }
  } else {
    // 如果点击的不是任何特性，隐藏弹窗
    vehicleDetailVisible.value = false;
  }
}

// 更新车辆位置
function updateVehiclePosition(vehicleData) {
  if (!vehicleSource || !props.map) return;
  
  const { object_id, object_type, position, heading, speed } = vehicleData;
  console.log(`接收到位置数据: ${object_id}`, position);
  
  let coordinates;

    
    coordinates = transform(
      [position.longitude, position.latitude], 
      'EPSG:4326', 
      props.map.getView().getProjection()
    );
 
  
  // 检查该车辆是否已存在
  let feature = vehicleSource.getFeatureById(object_id);
  
  // 根据车辆ID前缀和类型进行分类
  // 1. 判断航空器类型
  const isAircraftIn = object_type.toLowerCase().includes('aircraft') && !object_id.toLowerCase().includes('ac001');
  const isAircraftOut = object_id.toLowerCase().includes('ac001');
  const isAircraft = isAircraftIn || isAircraftOut;
  
  // 2. 判断无人车类型
  const isUnmannedVehicle = object_type === 'UNMANNED_VEHICLE' || object_id.toLowerCase().startsWith('qn');
  
  // 3. 判断特勤车类型
  const isSpecialVehicle = object_id.toLowerCase().startsWith('tq');
  
  // 4. 判断摆渡车类型
  const isShuttleVehicle = object_id.toLowerCase().startsWith('bd');
  
  // 选择图标 - 根据类型和告警状态选择不同图标
  let iconSrc;
  
  // 检查车辆是否已存在并且有状态标记
  const existingVehicle = vehicles.value[object_id];
  const hasInfoStatus = existingVehicle && existingVehicle.info;
  const hasWarningStatus = existingVehicle && existingVehicle.warning;
  const hasAlarmStatus = existingVehicle && existingVehicle.alarm;
  const hasCriticalStatus = existingVehicle && existingVehicle.critical;
  
  // 根据车辆类型和状态选择图标
  if (isAircraftIn) {
    iconSrc = aircraftIcon; // 滑入航空器
  } else if (isAircraftOut) {
    iconSrc = aircraft1Icon; // 滑出航空器
  } else if (hasInfoStatus || hasWarningStatus || hasCriticalStatus) {
    // 超速、预警和严重违规状态使用警告车辆图标
    iconSrc = warningCarIcon; 
  } else if (hasAlarmStatus) {
    // 告警状态
    iconSrc = carIcon; // 或者使用其他告警图标
  } else {
    iconSrc = carIcon; // 普通车辆
  }
  
  // 动态收集类别
  let typeKey = object_type; // 默认使用对象类型作为键
  
  // 根据车辆特性进一步细化分类
  if (isAircraftIn) {
    typeKey = 'AIRCRAFT_IN'; 
  } else if (isAircraftOut) {
    typeKey = 'AIRCRAFT_OUT';
  } else if (isUnmannedVehicle) {
    typeKey = 'UNMANNED_VEHICLE';
  } else if (isSpecialVehicle) {
    typeKey = 'SPECIAL_VEHICLE';
  } else if (isShuttleVehicle) {
    typeKey = 'SHUTTLE_VEHICLE';
  }
  
  // 根据typeKey收集分类
  if (!vehicleCategories.value[typeKey]) {
    vehicleCategories.value[typeKey] = {
      name: isAircraftIn ? '滑入航空器' : 
            isAircraftOut ? '滑出航空器' : 
            isUnmannedVehicle ? '无人车' :
            isSpecialVehicle ? '特勤车' :
            isShuttleVehicle ? '摆渡车' : object_type,
      icon: iconSrc,
      visible: true,
      showLabel: true
    };
  }
  
  // 创建样式 - 只有当类别设置为可见时才显示图标
  const style = vehicleCategories.value[typeKey].visible ? 
    new Style({
      image: new Icon({
        src: iconSrc,
        scale: 1.5,
        anchor: [0.5, 0.5],
        rotation: ((heading - 72) * Math.PI) / 180,
      })
    }) : new Style({}); // 使用空样式替代null，完全隐藏图标

  if (!feature) {
    // 创建新的Feature
    feature = new Feature({
      geometry: new Point(coordinates),
      name: `${object_type} ${object_id}`,
      type: object_type,
      speed: speed,
      isAircraftIn: isAircraftIn,
      isAircraftOut: isAircraftOut,
      isAircraft: isAircraft,
      isUnmannedVehicle: isUnmannedVehicle,
      isSpecialVehicle: isSpecialVehicle,
      isShuttleVehicle: isShuttleVehicle
    });
    
    feature.setId(object_id);
    feature.setStyle(style);
    vehicleSource.addFeature(feature);
    
    // 存储车辆信息
    vehicles.value[object_id] = {
      id: object_id,
      type: object_type,
      position: coordinates,
      heading: heading,
      speed: speed,
      feature: feature,
      isAircraftIn: isAircraftIn,
      isAircraftOut: isAircraftOut,
      isAircraft: isAircraft,
      isUnmannedVehicle: isUnmannedVehicle,
      isSpecialVehicle: isSpecialVehicle,
      isShuttleVehicle: isShuttleVehicle
    };
    
    // 只有当设置显示标签时才创建标签
    if (vehicleCategories.value[typeKey].showLabel) {
      updateVehicleLabel(object_id, coordinates, speed);
    }
  } else {
    // 更新现有Feature
    feature.getGeometry().setCoordinates(coordinates);
    feature.setStyle(style); // 应用最新的样式，可能是null（隐藏）
    
    // 更新存储的车辆信息
    vehicles.value[object_id] = {
      ...vehicles.value[object_id],
      position: coordinates,
      heading: heading,
      speed: speed,
      isAircraftIn: isAircraftIn,
      isAircraftOut: isAircraftOut,
      isAircraft: isAircraft,
      isUnmannedVehicle: isUnmannedVehicle,
      isSpecialVehicle: isSpecialVehicle,
      isShuttleVehicle: isShuttleVehicle
    };
    
    // 只有当设置显示标签时才更新标签
    if (vehicleCategories.value[typeKey].showLabel) {
      updateVehicleLabel(object_id, coordinates, speed);
    } else if (vehicles.value[object_id].overlay) {
      // 如果不显示标签但存在overlay，需要移除它
      try { 
        props.map.removeOverlay(vehicles.value[object_id].overlay); 
      } catch(e) {}
    }
  }
}

// 更新车辆标签
function updateVehicleLabel(id, position, speed, violationInfo) {
  if (!props.map || !vehicles.value[id]) return;
  
  console.log(`更新标签位置: ${id}, 位置: [${position[0]}, ${position[1]}]`);
  
  // 如果存在旧的overlay，先移除它
  if (vehicles.value[id].overlay) {
    props.map.removeOverlay(vehicles.value[id].overlay);
  }
  
  // 获取车辆类型信息
  const vehicle = vehicles.value[id];
  const isAircraftIn = vehicle.isAircraftIn;
  const isAircraftOut = vehicle.isAircraftOut;
  const isUnmannedVehicle = vehicle.isUnmannedVehicle;
  const isSpecialVehicle = vehicle.isSpecialVehicle;
  const isShuttleVehicle = vehicle.isShuttleVehicle;
  const alarm = vehicle.alarm;
  const warning = vehicle.warning;
  const critical = vehicle.critical;
  const info = vehicle.info;
  
  // 确定车辆类别的key
  let typeKey = vehicle.type;
  if (isAircraftIn) typeKey = 'AIRCRAFT_IN';
  else if (isAircraftOut) typeKey = 'AIRCRAFT_OUT';
  else if (isUnmannedVehicle) typeKey = 'UNMANNED_VEHICLE';
  else if (isSpecialVehicle) typeKey = 'SPECIAL_VEHICLE';
  else if (isShuttleVehicle) typeKey = 'SHUTTLE_VEHICLE';
  
  // 选择背景图片 - 根据车辆类型和告警状态选择不同背景
  let backgroundImage;
  if (alarm) {
    backgroundImage = alarmBg; // 告警背景 - 红色
  } else if (warning || info || critical) {
    backgroundImage = warningBg; // 预警/超速/越界背景 - 黄色
  } else if (isAircraftOut) {
    backgroundImage = airportOutBg; // 滑出航空器背景 - 黄色
  } else if (isAircraftIn) {
    backgroundImage = airportBg; // 滑入航空器背景 - 蓝色
  } else {
    backgroundImage = labelBg; // 普通车辆背景
  }
  
  // 重新创建标签元素
  const labelDiv = document.createElement('div');
  labelDiv.className = `vehicle-label ${isAircraftIn ? 'vehicle-aircraft-in' : ''} ${isAircraftOut ? 'vehicle-aircraft-out' : ''} ${isUnmannedVehicle ? 'vehicle-unmanned' : ''} ${isSpecialVehicle ? 'vehicle-special' : ''} ${isShuttleVehicle ? 'vehicle-shuttle' : ''}`;
  
  // 添加告警状态类
  if (alarm) labelDiv.className += ' vehicle-alarm';
  else if (warning) labelDiv.className += ' vehicle-warning';
  else if (critical) labelDiv.className += ' vehicle-critical';
  else if (info) labelDiv.className += ' vehicle-info';
  
  // 根据车辆类型和状态设置不同的标签内容
  let labelText = `${id} ${speed.toFixed(2)} km/h`;
  
  // 如果是超速状态(info)，使用特殊格式
  if (info && violationInfo) {
    // 第一行：车辆ID和当前速度
    labelText = `${id} ${speed.toFixed(2)} km/h`;
    
    // 第二行：超速描述
    if (violationInfo.description) {
      labelText += `<br>${violationInfo.description}`;
    }
    
    // 第三行：限速和实际车速详情
    if (violationInfo.limitValue !== undefined && violationInfo.actualValue !== undefined) {
      labelText += `<br>当前车辆限制车速${violationInfo.limitValue.toFixed(1)} 实际车速${violationInfo.actualValue.toFixed(1)}`;
    }
  }
  
  labelDiv.innerHTML = labelText;
  labelDiv.style.backgroundImage = `url(${backgroundImage})`;
  labelDiv.style.backgroundSize = '100% 100%';
  labelDiv.style.color = '#fff';
  labelDiv.style.padding = '5px 10px';
  
  // 创建新的Overlay
  const overlay = new Overlay({
    element: labelDiv,
    position: position,
    positioning: 'bottom-center', // 标签底部中心对准位置点
    offset: [0, -30], // 向上偏移，确保在图标上方
    stopEvent: false,
    insertFirst: true, // 确保在DOM中优先插入
    autoPan: false, // 禁用自动平移
  });
  
  // 更新引用
  vehicles.value[id].overlay = overlay;
  vehicles.value[id].labelDiv = labelDiv;
  
  // 添加到地图 - 不再需要额外检查图标是否可见
  props.map.addOverlay(overlay);
}

// 监听地图变化，确保标签位置正确更新
function setupMapListeners() {
  if (!props.map) return;
  
  // 监听地图移动结束事件
  props.map.on('moveend', () => {
    // 更新所有标签位置
    Object.keys(vehicles.value).forEach(id => {
      const vehicle = vehicles.value[id];
      if (vehicle.feature) {
        const coordinates = vehicle.feature.getGeometry().getCoordinates();
        updateVehicleLabel(id, coordinates, vehicle.speed);
      }
    });
  });
}

// 模拟更新气象数据
function updateWeatherData() {
  // 这里可以通过API获取实时气象数据 用模拟数据
  weatherData.value = {
    temperature: '22.5',
    humidity: '68',
    windSpeed: '3.2',
    visibility: '8.5',
    pressure: '1013.2',
    updateTime: Date.now()
  };
}

// 组件挂载时初始化
onMounted(() => {
  // 创建图层并连接WebSocket
  if (props.map) {
    createVehicleLayer();
  }
  
  // 连接WebSocket
  connectWebSocket();
  
  // 设置定时发送心跳
  const pingInterval = setInterval(() => {
    if (wsService && wsConnected.value) {
      sendPing();
    }
  }, 30000); // 每30秒发送一次心跳
  
  // 设置定时更新气象数据
  const weatherUpdateInterval = setInterval(() => {
    updateWeatherData();
  }, 60000); // 每分钟更新一次气象数据
  
  // 组件卸载时清理资源
  onUnmounted(() => {
    clearInterval(pingInterval);
    clearInterval(weatherUpdateInterval);
    if (reconnectTimer) {
      clearTimeout(reconnectTimer);
      reconnectTimer = null;
    }
    cleanup();
  });
});

// 组件被激活时（切换回该路由时）
onActivated(() => {
  console.log('VehicleMovementControl组件被激活');
  // 如果WebSocket未连接，重新连接
  if (!wsConnected.value && !wsService) {
    console.log('组件激活，WebSocket未连接，正在重新连接...');
    // 延迟一点时间再连接，确保DOM已完全渲染
    reconnectTimer = setTimeout(() => {
      connectWebSocket();
    }, 500);
  } else {
    console.log('组件激活，WebSocket已连接');
  }
});

// 组件被停用时（切换到其他路由时）
onDeactivated(() => {
  console.log('VehicleMovementControl组件被停用');
  // 可以选择在这里关闭WebSocket，也可以保持连接
  // 如果希望在组件隐藏时断开连接，可以取消下面的注释
  /*
  if (wsService) {
    console.log('组件停用，关闭WebSocket连接');
    wsService.close();
    wsService = null;
    wsConnected.value = false;
  }
  */
});

// 连接WebSocket
function connectWebSocket() {
  // 重置WebSocket实例以强制创建新实例
  resetWebSocketInstance();
  
  try {
    // 使用WebSocketService创建连接
    const wsUrl = import.meta.env.VITE_APP_WEBSOCKET_URL;
    console.log(`正在连接WebSocket: ${wsUrl}`);
    
    wsService = createWebSocket(wsUrl, {
      reconnectInterval: 3000,
      maxReconnectAttempts: 5
    });
    
    // 注册事件监听
    wsService.on('open', (event) => {
      console.log('WebSocket连接成功!');
      wsConnected.value = true;
      
      // 连接成功后自动订阅消息
      setTimeout(() => {
        sendSubscribe();
      }, 1000); // 延迟1秒发送订阅，确保连接稳定
    });
    
    wsService.on('message', (data) => {
      handleWsMessage(data);
    });
    
    wsService.on('error', (event) => {
      console.error('WebSocket错误:', event);
      wsConnected.value = false;
    });
    
    wsService.on('close', (event) => {
      console.log(`WebSocket连接关闭: ${event.code} - ${event.reason}`);
      wsConnected.value = false;
    });
    
    wsService.on('reconnect_failed', () => {
      console.error('WebSocket重连失败，已达到最大重试次数');
      wsConnected.value = false;
    });
    
  } catch (error) {
    console.error('创建WebSocket连接失败:', error);
  }
}

// 处理WebSocket消息
function handleWsMessage(message) {
  try {
    const data = JSON.parse(message);
    
    // 根据消息类型处理
    switch (data.type) {
      case 'connection':
        console.log(`连接确认: ${data.message}`);
        break;
      case 'position_update':
        // 确保payload存在
        if (data.payload && data.payload.object_id) {
          // 检查是否需要清除车辆的告警状态
          clearVehicleAlertStatus(data.payload);
          
          // 更新车辆位置
          updateVehiclePosition(data.payload);
        } else {
          console.error('位置更新消息格式错误:', data);
        }
        break;
      case 'pong':
        console.log('收到心跳响应');
        break;
      case 'rule_violation':
        console.log('收到规则违规:', data.payload);
        if (data.payload) {
          // 获取车辆ID和告警信息
          const vehicleId = data.payload.object_id || data.payload.vehicleId || data.payload.vehicleLicense || '未知车辆';
          const violationType = data.payload.violationType || '未知违规';
          const alertLevel = data.payload.alertLevel || 'INFO';
          const description = data.payload.description || '';
          const limitValue = data.payload.limitValue;
          const actualValue = data.payload.actualValue;
          
          // 检查是否为超速违规
          const isSpeedViolation = violationType === 'SPEED_VIOLATION';
          // 检查是否为超速结束
          const isSpeedViolationEnd = violationType === 'SPEED_VIOLATION_END';
          
          // 如果是超速违规，特殊处理
          if (isSpeedViolation) {
            console.log(`检测到超速违规: ${vehicleId}, 实际速度: ${actualValue}, 限速: ${limitValue}`);
            
            // 在地图上标记该车辆的超速状态
            if (vehicles.value[vehicleId]) {
              vehicles.value[vehicleId].info = true;
              vehicles.value[vehicleId].alarm = false;
              vehicles.value[vehicleId].warning = false;
              vehicles.value[vehicleId].critical = false;
              
              // 更新车辆图标为超速警告图标
              if (vehicles.value[vehicleId].feature) {
                vehicles.value[vehicleId].feature.setStyle(new Style({
                  image: new Icon({
                    src: warningCarIcon,
                    scale: 1.5,
                    anchor: [0.5, 0.5],
                    rotation: ((vehicles.value[vehicleId].heading - 72) * Math.PI) / 180,
                  })
                }));
              }
              
              // 更新标签显示为超速状态
              if (vehicles.value[vehicleId].position) {
                updateVehicleLabel(vehicleId, vehicles.value[vehicleId].position, vehicles.value[vehicleId].speed, {
                  description: description || `超速违规`,
                  limitValue: limitValue,
                  actualValue: actualValue
                });
              }
              
              // 设置或重置超速状态自动清除计时器
              if (speedViolationTimers[vehicleId]) {
                clearTimeout(speedViolationTimers[vehicleId]);
              }
              
              // 设置新的超时计时器，如果在一定时间内（如5秒）没有再次接收到超速消息，则自动清除超速状态
              speedViolationTimers[vehicleId] = setTimeout(() => {
                // 确保车辆仍然存在
                if (vehicles.value[vehicleId]) {
                  console.log(`超速状态超时: ${vehicleId}, 自动清除超速状态`);
                  
                  // 清除超速状态
                  vehicles.value[vehicleId].info = false;
                  
                  // 更新车辆图标为默认图标
                  if (vehicles.value[vehicleId].feature) {
                    // 根据车辆类型选择适当的图标
                    let iconSrc = carIcon; // 默认普通车图标
                    
                    // 检查是否是特殊类型车辆
                    if (vehicles.value[vehicleId].isAircraftIn) {
                      iconSrc = aircraftIcon;
                    } else if (vehicles.value[vehicleId].isAircraftOut) {
                      iconSrc = aircraft1Icon;
                    }
                    
                    // 应用普通样式
                    vehicles.value[vehicleId].feature.setStyle(new Style({
                      image: new Icon({
                        src: iconSrc,
                        scale: 1.5,
                        anchor: [0.5, 0.5],
                        rotation: ((vehicles.value[vehicleId].heading - 72) * Math.PI) / 180,
                      })
                    }));
                  }
                  
                  // 更新标签显示为正常状态
                  if (vehicles.value[vehicleId].position) {
                    updateVehicleLabel(vehicleId, vehicles.value[vehicleId].position, vehicles.value[vehicleId].speed);
                  }
                  
                  // 清除计时器引用
                  delete speedViolationTimers[vehicleId];
                }
              }, 5000); // 5秒超时，可以根据需要调整
            }
            return; // 已处理超速情况，不再进入下面的alertLevel处理
          }

          // 如果是超速结束，清除超速状态
          if (isSpeedViolationEnd) {
            console.log(`检测到超速结束: ${vehicleId}`);
            
            // 在地图上清除该车辆的超速状态
            if (vehicles.value[vehicleId]) {
              // 清除所有告警状态
              vehicles.value[vehicleId].info = false;
              vehicles.value[vehicleId].alarm = false;
              vehicles.value[vehicleId].warning = false;
              vehicles.value[vehicleId].critical = false;
              
              // 更新车辆图标为默认图标
              if (vehicles.value[vehicleId].feature) {
                // 根据车辆类型选择适当的图标
                let iconSrc = carIcon; // 默认普通车图标
                
                // 检查是否是特殊类型车辆
                if (vehicles.value[vehicleId].isAircraftIn) {
                  iconSrc = aircraftIcon;
                } else if (vehicles.value[vehicleId].isAircraftOut) {
                  iconSrc = aircraft1Icon;
                }
                
                // 应用普通样式
                vehicles.value[vehicleId].feature.setStyle(new Style({
                  image: new Icon({
                    src: iconSrc,
                    scale: 1.5,
                    anchor: [0.5, 0.5],
                    rotation: ((vehicles.value[vehicleId].heading - 72) * Math.PI) / 180,
                  })
                }));
              }
              
              // 更新标签显示为正常状态
              if (vehicles.value[vehicleId].position) {
                updateVehicleLabel(vehicleId, vehicles.value[vehicleId].position, vehicles.value[vehicleId].speed);
              }
            }
            return; // 已处理超速结束情况，不再进入下面的alertLevel处理
          }
          
          // 根据alertLevel处理其他类型的告警
          switch (alertLevel.toUpperCase()) {
            case 'Info': // 预警
              // 在地图上标记该车辆的预警状态
              if (vehicles.value[vehicleId]) {
                vehicles.value[vehicleId].warning = true;
                vehicles.value[vehicleId].alarm = false;
                vehicles.value[vehicleId].critical = false;
                vehicles.value[vehicleId].info = false;
                
                // 更新车辆图标为警告图标
                if (vehicles.value[vehicleId].feature) {
                  vehicles.value[vehicleId].feature.setStyle(new Style({
                    image: new Icon({
                      src: warningCarIcon,
                      scale: 1.5,
                      anchor: [0.5, 0.5],
                      rotation: ((vehicles.value[vehicleId].heading - 72) * Math.PI) / 180,
                    })
                  }));
                }
                
                // 更新标签显示
                if (vehicles.value[vehicleId].position) {
                  updateVehicleLabel(vehicleId, vehicles.value[vehicleId].position, vehicles.value[vehicleId].speed, {
                    description: description,
                    limitValue: limitValue,
                    actualValue: actualValue
                  });
                }
              }
              break;
              
            case 'ALERT': // 告警
              // 在地图上标记该车辆的告警状态
              if (vehicles.value[vehicleId]) {
                vehicles.value[vehicleId].alarm = true;
                vehicles.value[vehicleId].warning = false;
                vehicles.value[vehicleId].critical = false;
                vehicles.value[vehicleId].info = false;
                
                // 更新车辆图标为告警图标（与其他警告保持一致使用warningCarIcon）
                if (vehicles.value[vehicleId].feature) {
                  vehicles.value[vehicleId].feature.setStyle(new Style({
                    image: new Icon({
                      src: warningCarIcon,
                      scale: 1.5,
                      anchor: [0.5, 0.5],
                      rotation: ((vehicles.value[vehicleId].heading - 72) * Math.PI) / 180,
                    })
                  }));
                }
                
                // 更新标签显示
                if (vehicles.value[vehicleId].position) {
                  updateVehicleLabel(vehicleId, vehicles.value[vehicleId].position, vehicles.value[vehicleId].speed, {
                    description: description,
                    limitValue: limitValue,
                    actualValue: actualValue
                  });
                }
              }
              break;
              
            case 'CRITICAL': // 越界
              // 在地图上标记该车辆的严重告警状态
              if (vehicles.value[vehicleId]) {
                vehicles.value[vehicleId].critical = true;
                vehicles.value[vehicleId].alarm = false;
                vehicles.value[vehicleId].warning = false;
                vehicles.value[vehicleId].info = false;
                
                // 更新车辆图标为警告图标
                if (vehicles.value[vehicleId].feature) {
                  vehicles.value[vehicleId].feature.setStyle(new Style({
                    image: new Icon({
                      src: warningCarIcon,
                      scale: 1.5,
                      anchor: [0.5, 0.5],
                      rotation: ((vehicles.value[vehicleId].heading - 72) * Math.PI) / 180,
                    })
                  }));
                }
                
                // 更新标签显示
                if (vehicles.value[vehicleId].position) {
                  updateVehicleLabel(vehicleId, vehicles.value[vehicleId].position, vehicles.value[vehicleId].speed, {
                    description: description,
                    limitValue: limitValue,
                    actualValue: actualValue
                  });
                }
              }
              break;
              
            case 'WARNING': // 超速
              // 在地图上标记该车辆的超速状态
              if (vehicles.value[vehicleId]) {
                vehicles.value[vehicleId].info = true;
                vehicles.value[vehicleId].alarm = false;
                vehicles.value[vehicleId].warning = false;
                vehicles.value[vehicleId].critical = false;
                
                // 更新车辆图标为警告图标
                if (vehicles.value[vehicleId].feature) {
                  vehicles.value[vehicleId].feature.setStyle(new Style({
                    image: new Icon({
                      src: warningCarIcon,
                      scale: 1.5,
                      anchor: [0.5, 0.5],
                      rotation: ((vehicles.value[vehicleId].heading - 72) * Math.PI) / 180,
                    })
                  }));
                }
                
                // 更新标签显示为超速状态
                if (vehicles.value[vehicleId].position) {
                  updateVehicleLabel(vehicleId, vehicles.value[vehicleId].position, vehicles.value[vehicleId].speed, {
                    description: description,
                    limitValue: limitValue,
                    actualValue: actualValue
                  });
                }
              }
              break;
              
            default:
              console.log(`未处理的告警级别: ${alertLevel}`);
          }
        }
        break;
      case 'vehicle_command':
        console.log('收到车辆控制指令:', data.payload);
        break;
      default:
        // 其他类型的消息可以根据需要处理
        console.log(`收到其他类型消息: ${data.type}`, data);
        break;
    }
  } catch (e) {
    console.error('处理WebSocket消息出错:', e, message);
  }
}

// 清除车辆告警状态（如果需要）
function clearVehicleAlertStatus(vehicleData) {
  const { object_id, speed } = vehicleData;
  
  // 检查该车辆是否已存在且有告警状态
  const existingVehicle = vehicles.value[object_id];
  if (!existingVehicle) return;
  
  // 检查是否有任何告警状态
  const hasAlertStatus = existingVehicle.info || existingVehicle.warning || 
                       existingVehicle.alarm || existingVehicle.critical;
  
  // 如果有告警状态，需要检查是否应该清除
  if (hasAlertStatus) {
    // 只处理超速状态(info)的自动恢复
    // 1. 判断是否为超速状态
    const isSpeedViolation = existingVehicle.info;
    
    // 2. 判断当前速度是否已降低到安全值
    // 这里使用一个默认阈值判断，实际应用中最好使用服务端返回的限速值
    // 假设超速阈值为50km/h
    const SPEED_THRESHOLD = 50; // 超速阈值，单位km/h
    const isBelowThreshold = speed < SPEED_THRESHOLD;
    
    // 3. 如果是超速状态且当前速度已降低到阈值以下，清除超速状态
    if (isSpeedViolation && isBelowThreshold) {
      console.log(`检测到车辆${object_id}速度降低到${speed.toFixed(1)}km/h，低于阈值${SPEED_THRESHOLD}km/h，自动清除超速状态`);
      
      // 清除超速状态
      existingVehicle.info = false;
      
      // 更新车辆图标为默认图标
      if (existingVehicle.feature) {
        // 根据车辆类型选择适当的图标
        let iconSrc = carIcon; // 默认普通车图标
        
        // 检查是否是特殊类型车辆
        if (existingVehicle.isAircraftIn) {
          iconSrc = aircraftIcon;
        } else if (existingVehicle.isAircraftOut) {
          iconSrc = aircraft1Icon;
        }
        
        // 应用普通样式
        existingVehicle.feature.setStyle(new Style({
          image: new Icon({
            src: iconSrc,
            scale: 1.5,
            anchor: [0.5, 0.5],
            rotation: ((existingVehicle.heading - 72) * Math.PI) / 180,
          })
        }));
      }
      
      // 更新标签显示为正常状态
      if (existingVehicle.position) {
        updateVehicleLabel(object_id, existingVehicle.position, speed);
      }
      
      console.log(`已清除${object_id}的超速状态，恢复为普通状态`);
    } else {
      console.log(`车辆${object_id}有告警状态，但不符合自动清除条件，保持该状态`);
    }
  }
}

// 发送心跳
function sendPing() {
  if (wsService) {
    wsService.send('ping');
    console.log('发送心跳: ping');
  }
}

// 订阅消息
function sendSubscribe() {
  if (wsService) {
    const message = JSON.stringify({
      type: 'subscribe',
      topics: ['position_update', 'collision_warning', 'rule_violation'],
      timestamp: Date.now()
    });
    wsService.send(message);
    console.log('发送订阅请求');
  }
}

// 清理资源
function cleanup() {
  // 断开WebSocket连接
  if (wsService) {
    wsService.close();
    wsService = null;
  }
  
  if (reconnectTimer) {
    clearTimeout(reconnectTimer);
    reconnectTimer = null;
  }
  
  // 清理所有超速状态计时器
  Object.keys(speedViolationTimers).forEach(vehicleId => {
    clearTimeout(speedViolationTimers[vehicleId]);
    delete speedViolationTimers[vehicleId];
  });
  
  // 移除图层
  if (vehicleLayer && props.map) {
    props.map.removeLayer(vehicleLayer);
    vehicleLayer = null;
  }
  
  // 移除标签
  if (props.map) {
    Object.values(vehicles.value).forEach(vehicle => {
      if (vehicle.overlay) {
        console.log(`移除标签: ${vehicle.id}`);
        props.map.removeOverlay(vehicle.overlay);
        vehicle.overlay = null;
      }
    });
  }
  
  // 清空车辆数据
  vehicles.value = {};
}

// 监听地图实例变化
watch(() => props.map, (newMap) => {
  if (newMap) {
    createVehicleLayer();
  }
});

// 向外暴露方法
defineExpose({
  updateVehiclePosition,
  wsConnected,
  sendPing,
  sendSubscribe,
  vehicleCategories,
  weatherStationVisible,
  weatherData,
  vehicleDetailVisible,
  vehicleDetail,
  toggleWeatherStationVisibility() {
    weatherStationVisible.value = !weatherStationVisible.value;
  },
  toggleVehicleDetailVisibility() {
    vehicleDetailVisible.value = !vehicleDetailVisible.value;
  },
  updateVehicleDetail(data) {
    if (data) {
      vehicleDetail.value = {...vehicleDetail.value, ...data};
      vehicleDetailVisible.value = true;
    }
  },
  showVehicleDetail(vehicleId, pixelPosition) {
    if (vehicles.value[vehicleId]) {
      // 更新车辆详情
      vehicleDetail.value = {
        id: vehicleId,
        type: vehicles.value[vehicleId].type,
        status: '任务中',
        startTime: '11-19 11:30',
        currentLocation: '当前位置',
        startLocation: 'T1航站楼',
        endLocation: 'T3航站楼',
        totalDistance: '1.3km',
        battery: '60%',
        manager: '张三',
        phone: '18661910988'
      };
      
      // 设置弹窗位置
      if (pixelPosition) {
        const viewportPosition = props.map.getViewport().getBoundingClientRect();
        detailPopupStyle.value = {
          left: (viewportPosition.left + pixelPosition[0] + 10) + 'px',
          top: (viewportPosition.top + pixelPosition[1] + 10) + 'px'
        };
      }
      
      // 显示详情弹窗
      vehicleDetailVisible.value = true;
    }
  },
  setCategoryVisibility(type, { visible, showLabel }) {
    if (vehicleCategories.value[type]) {
      // 更新分类设置
      vehicleCategories.value[type].visible = visible;
      vehicleCategories.value[type].showLabel = showLabel;
      
      // 立即应用更改 - 更新所有属于此类别的车辆
      Object.values(vehicles.value).forEach(vehicle => {
        let vehicleTypeKey = vehicle.type;
        if (vehicle.isAircraftIn) vehicleTypeKey = 'AIRCRAFT_IN';
        else if (vehicle.isAircraftOut) vehicleTypeKey = 'AIRCRAFT_OUT';
        else if (vehicle.isUnmannedVehicle) vehicleTypeKey = 'UNMANNED_VEHICLE';
        else if (vehicle.isSpecialVehicle) vehicleTypeKey = 'SPECIAL_VEHICLE';
        else if (vehicle.isShuttleVehicle) vehicleTypeKey = 'SHUTTLE_VEHICLE';
        
        // 如果车辆属于当前修改的类别
        if (vehicleTypeKey === type) {
          // 更新图标可见性 - 如果不可见，则完全移除图标样式
          if (vehicle.feature) {
            if (visible) {
              // 显示图标
              vehicle.feature.setStyle(
                new Style({
                  image: new Icon({
                    src: vehicleCategories.value[type].icon,
                    scale: 1.5,
                    anchor: [0.5, 0.5],
                    rotation: ((vehicle.heading - 72) * Math.PI) / 180,
                  })
                })
              );
            } else {
              // 完全隐藏图标，使用空样式而非null
              vehicle.feature.setStyle(new Style({}));
            }
          }
          
          // 单独控制文本标签可见性，与图标显示状态无关
          if (vehicle.overlay) {
            if (showLabel) {
              try { props.map.removeOverlay(vehicle.overlay); } catch (e) {}
              props.map.addOverlay(vehicle.overlay);
            } else {
              try { props.map.removeOverlay(vehicle.overlay); } catch (e) {}
            }
          }
        }
      });
    }
  },
  reconnectWebSocket() {
    console.log('手动重连WebSocket');
    connectWebSocket();
  }
});
</script>

<style scoped>
/* 气象监测站样式 */
.weather-station-container {
  position: fixed;
  top: 100px;
  right: 20px;
  z-index: 2000;
  width: 300px;
}

.weather-station-box {
  background-color: #424851;
  border-radius: 8px;
  overflow: hidden;
}

.weather-station-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom:1px solid #777777;
  background-color: #424851;
  color: #fff;
  padding: 8px 12px;
  font-size: 16px;
}

.weather-station-close {
  cursor: pointer;
  font-size: 20px;
  font-weight: bold;
}

.weather-station-content {
  padding: 12px;
  color: #fff;
}

.weather-station-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.weather-station-status {
  color: #4CAF50;
  font-weight: bold;
}

.weather-station-info-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.weather-station-info-row {
  display: flex;
  justify-content: space-between;
}

.weather-station-info-item {
  flex: 1;
}

.weather-info-label {
    color: #EEEEEE;
  font-size: 14px;
  margin-right: 4px;
}

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

/* 车辆详情弹窗样式 */
.vehicle-detail-popup {
  position: fixed;
  z-index: 2000;
  width: 380px;
  background-color: #424851;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  border: 1px solid #777777;
}

.vehicle-detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom:1px solid #777777;
  background-color: #424851;
  color: #fff;
  padding: 8px 12px;
  font-size: 16px;
}

.vehicle-detail-title {
  color: #fff;
  font-size: 16px;
  font-weight: bolder;
}

.vehicle-detail-close {
  cursor: pointer;
  font-size: 20px;
  font-weight: bold;
  color: #fff;
}

.vehicle-detail-content {
  padding: 12px;
  color: #fff;
}

.vehicle-detail-info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.vehicle-detail-info-item {
  flex: 1;
}

.vehicle-info-label {
  color: #EEEEEE;
  font-size: 14px;
  margin-right: 4px;
}

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

/* 车辆标签样式 */
:deep(.vehicle-label) {
  position: absolute;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  pointer-events: none;
  transform: translateX(-50%);
  text-align: center;
  background-repeat: no-repeat;
  background-position: center;
  min-width: 80px;
  min-height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 30; /* 确保标签在图标上方 */
  transition: transform 0.3s ease, left 0.3s ease, top 0.3s ease; /* 平滑移动效果 */
  will-change: transform, left, top; /* 提示浏览器优化这些属性的变化 */
  bottom: 0; /* 确保标签底部对齐定位点 */
}

/* 滑入航空器标签样式 */
:deep(.vehicle-aircraft-in) {
  color: #fff;
}

/* 滑出航空器标签样式 */
:deep(.vehicle-aircraft-out) {
  color: #333;
}

/* 无人车标签样式 */
:deep(.vehicle-unmanned) {
  color: #fff;
}

/* 特勤车标签样式 */
:deep(.vehicle-special) {
  color: #fff;
}

/* 摆渡车标签样式 */
:deep(.vehicle-shuttle) {
  color: #fff;
}

/* 告警标签样式 */
:deep(.vehicle-alarm) {
  color: #fff;
  font-weight: bold;
}

/* 预警标签样式 */
:deep(.vehicle-warning) {
  color: #fff;
}

/* 严重违规标签样式 */
:deep(.vehicle-critical) {
  color: #fff;
}

/* 信息级别(超速等)标签样式 */
:deep(.vehicle-info) {
  color: #fff;
  line-height: 1.4;
  white-space: normal;
  width: 160px; /* 适当增加宽度以容纳更多文本 */
  text-align: center;
}
</style> 
