<template>
  <!-- 标签容器，不在模板中渲染任何内容，标签由JS动态创建 -->
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { Overlay } from 'ol';
import selectIcon from '@/assets/images/select_icon.png';
// 定义props
const props = defineProps({
  map: Object,
  vehicles: Object
});
// 导入图片
const select_icon = '../../../assets/images/select_icon.png';
// 存储标签覆盖物
const vehicleLabels = ref({});
// 添加标签更新时间记录
const labelUpdateTimes = ref({});
// 定义更新间隔常量(毫秒)
const UPDATE_INTERVAL = 500; // 每500ms更新一次标签

// 创建或更新车辆标签
function updateVehicleLabel(vehicleId, coordinates, speed, alertInfo) {
  if (!props.map) return;
  
  // 获取当前时间
  const now = Date.now();
  
  // 检查标签是否已存在
  if (vehicleLabels.value[vehicleId]) {
    // 标签已存在：只在满足更新频率限制时更新文本内容，不再重新调用 setPosition 修改坐标
    // 位置更新完全交给动画渲染循环（60fps）进行平滑同步，避免瞬间跳跃产生巨大错位与间隔
    if (!labelUpdateTimes.value[vehicleId] || 
        (now - labelUpdateTimes.value[vehicleId]) > UPDATE_INTERVAL) {
      updateLabelContent(vehicleId, speed, alertInfo);
      labelUpdateTimes.value[vehicleId] = now;
    }
  } else {
    // 首次创建新标签：直接创建并初始化位置坐标，不受更新频率限制，确保新航空器出现时立即显示标签
    createNewLabel(vehicleId, coordinates, speed, alertInfo);
    labelUpdateTimes.value[vehicleId] = now;
  }
}


// 创建新标签
function createNewLabel(vehicleId, coordinates, speed, alertInfo) {
  // 创建标签DOM元素
  const labelElement = document.createElement('div');
  labelElement.className = 'vehicle-label';
  labelElement.id = `label-${vehicleId}`;
  
  // 设置标签内容
  const labelContent = createLabelContent(vehicleId, speed, alertInfo);
  labelElement.innerHTML = labelContent;
  
  // 创建覆盖物
  const overlay = new Overlay({
    element: labelElement,
    position: coordinates,
    offset: [34, -34], // 位于图标右上方，并留出间距
    positioning: 'bottom-left',
    stopEvent: false,
    insertFirst: true, // 确保在DOM中优先插入
    autoPan: false, // 禁用自动平移
  });
  
  // 将覆盖物添加到地图
  props.map.addOverlay(overlay);
  
  // 存储覆盖物引用
  vehicleLabels.value[vehicleId] = overlay;
  
  // 添加点击事件监听器
  setupTabClickListeners(vehicleId);
}

// 更新标签内容
function updateLabelContent(vehicleId, speed, alertInfo) {
  const labelElement = document.getElementById(`label-${vehicleId}`);
  if (!labelElement) return;
  
  // 更新标签内容
  const labelContent = createLabelContent(vehicleId, speed, alertInfo);
  labelElement.innerHTML = labelContent;
  
  // 重新设置点击事件监听器
  setupTabClickListeners(vehicleId);
}

// 创建标签内容
function createLabelContent(vehicleId, speed, alertInfo = {}) {
  // 获取车辆信息
  const vehicle = props.vehicles[vehicleId];
  if (!vehicle) return '';
  
  // 格式化速度，保留1位小数
  const formattedSpeed = speed ? `${speed.toFixed(1)}km/h` : '0.0km/h';
  
  // 检查是否存在各类告警
  const hasWarning = vehicle.warning || (alertInfo && alertInfo.isWarning);
  const hasAlarm = vehicle.alarm || (alertInfo && alertInfo.isAlarm);
  const hasSpeedViolation = vehicle.speedViolation || (alertInfo && alertInfo.isSpeedViolation);
  const hasUnauthorizedEntry = vehicle.critical || (alertInfo && alertInfo.isUnauthorizedEntry);
  
  // 检查是否有任何告警
  const hasAnyAlert = hasWarning || hasAlarm || hasSpeedViolation || hasUnauthorizedEntry;
  
  // 如果没有任何告警，只显示车牌号和车速
  if (!hasAnyAlert) {
    return `
      <div class="label-container simple-label">
        <div class="label-header">
          <span class="vehicle-id">${vehicleId}</span>
          <span class="vehicle-speed">${formattedSpeed}</span>
        </div>
      </div>
    `;
  }
  
  // 有告警时，显示完整的Tab栏
  let html = `
    <div class="label-container">
      <div class="label-tabs">
        <div class="tab-buttons">
          <button class="tab-button ${hasWarning ? 'warning-icon' : 'unwarning-icon'}" data-tab="warning" data-vehicle="${vehicleId}">
          </button>
          <button class="tab-button ${hasAlarm ? 'alarm-icon' : 'unalarm-icon'}" data-tab="alarm" data-vehicle="${vehicleId}">
          </button>
           <button class="tab-button ${hasUnauthorizedEntry ? 'boundary-icon' : 'unboundary-icon'}" data-tab="boundary" data-vehicle="${vehicleId}">
          </button>
          <button class="tab-button ${hasSpeedViolation ? 'speed-icon ' : 'unspeed-icon '}" data-tab="speed" data-vehicle="${vehicleId}">
          </button>
         
        </div>
        <div class="tab-content">
  `;
  
  // 默认显示第一个有内容的标签页
  let activeTabContent = '';
  let activeTabFound = false;
  
  // 冲突预警内容
  if (hasWarning) {
    const warningMessage = alertInfo?.description || '与其他车辆距离过近，请注意避让！';
    activeTabContent = `
      <div class="tab-pane ${!activeTabFound ? 'active' : ''}" data-tab-content="warning" data-vehicle="${vehicleId}">
        <div class="alert">
          <img src="${selectIcon}" alt="Select">
            <span>冲突预警</span>
        </div>
        <div class="alert-message">${warningMessage}</div>
      </div>
    `;
    activeTabFound = true;
  }
  
  // 冲突告警内容
  if (hasAlarm) {
    const alarmMessage = alertInfo?.description || '与其他车辆存在冲突风险！';
    activeTabContent += `
      <div class="tab-pane ${!activeTabFound ? 'active' : ''}" data-tab-content="alarm" data-vehicle="${vehicleId}">
          <div class="alert">
            <img src="${selectIcon}" alt="Select">
            <span>冲突告警</span>
        </div>
        <div class="alert-message">${alarmMessage}</div>
      </div>
    `;
    if (!activeTabFound) activeTabFound = true;
  }
  
  // 超速告警内容
  if (hasSpeedViolation) {
    const limitValue = alertInfo?.limitValue || vehicle.limitValue || 30;
    const actualValue = alertInfo?.actualValue || vehicle.actualValue || speed;
    activeTabContent += `
      <div class="tab-pane ${!activeTabFound ? 'active' : ''}" data-tab-content="speed" data-vehicle="${vehicleId}">
           <div class="alert">
            <img src="${selectIcon}" alt="Select">
            <span>超速告警</span>
        </div>
        <div class="speed-info">
          <div>规定速度: <span class="limit-value">${limitValue}km/h</span></div>
          <div>当前速度: <span class="actual-value">${actualValue.toFixed(1)}km/h</span></div>
        </div>
      </div>
    `;
    if (!activeTabFound) activeTabFound = true;
  }
  
  // 越界告警内容
  if (hasUnauthorizedEntry) {
    const boundaryMessage = alertInfo?.description || '车辆已进入禁行区域！';
    activeTabContent += `
      <div class="tab-pane ${!activeTabFound ? 'active' : ''}" data-tab-content="boundary" data-vehicle="${vehicleId}">
          <div class="alert">
            <img src="${selectIcon}" alt="Select">
            <span>越界告警</span>
        </div>
        <div class="alert-message">${boundaryMessage}</div>
      </div>
    `;
    if (!activeTabFound) activeTabFound = true;
  }
  
  html += activeTabContent;
  html += `
        </div>
      </div>
  `;
  html+=`
   <div class="label-header">
        <span class="vehicle-id">${vehicleId}</span>
        <span class="vehicle-speed">${formattedSpeed}</span>
      </div>
      </div>
      `
  return html;
}

// 设置标签页点击事件监听器
function setupTabClickListeners(vehicleId) {
  setTimeout(() => {
    const tabButtons = document.querySelectorAll(`.tab-button[data-vehicle="${vehicleId}"]`);
    
    tabButtons.forEach(button => {
      // 移除现有事件监听器
      button.removeEventListener('click', handleTabClick);
      
      // 添加新的事件监听器
      button.addEventListener('click', handleTabClick);
    });
    
    // 默认选中第一个非禁用的标签页
    const firstActiveButton = document.querySelector(`.tab-button.active[data-vehicle="${vehicleId}"]`);
    if (firstActiveButton && !firstActiveButton.classList.contains('current')) {
      firstActiveButton.click();
    }
  }, 100);
}

// 处理标签页点击事件
function handleTabClick(event) {
  const button = event.currentTarget;
  const tabName = button.getAttribute('data-tab');
  const vehicleId = button.getAttribute('data-vehicle');
  
  // 如果按钮被禁用，不执行任何操作
  if (button.classList.contains('disabled')) {
    return;
  }
  
  // 获取所有相关元素
  const tabButtons = document.querySelectorAll(`.tab-button[data-vehicle="${vehicleId}"]`);
  const tabPanes = document.querySelectorAll(`[data-tab-content][data-vehicle="${vehicleId}"]`);
  
  // 移除所有活动状态
  tabButtons.forEach(btn => btn.classList.remove('current'));
  tabPanes.forEach(pane => pane.classList.remove('active'));
  
  // 设置当前活动状态
  button.classList.add('current');
  const activePane = document.querySelector(`[data-tab-content="${tabName}"][data-vehicle="${vehicleId}"]`);
  if (activePane) {
    activePane.classList.add('active');
  }
  
  // 阻止事件冒泡，避免触发地图点击事件
  event.stopPropagation();
}

// 移除车辆标签
function removeVehicleLabel(vehicleId) {
  if (vehicleLabels.value[vehicleId]) {
    props.map.removeOverlay(vehicleLabels.value[vehicleId]);
    delete vehicleLabels.value[vehicleId];
  }
}

// 设置标签可见性
function setLabelVisibility(vehicleId, visible) {
  if (vehicleLabels.value[vehicleId]) {
    const labelElement = vehicleLabels.value[vehicleId].getElement();
    if (labelElement) {
      labelElement.style.display = visible ? 'block' : 'none';
    }
  }
}

function updateLabelPosition(vehicleId, coordinates) {
  if (vehicleLabels.value[vehicleId]) {
    vehicleLabels.value[vehicleId].setPosition(coordinates);
  }
}

// 更新所有标签位置
function updateAllLabels() {
  if (!props.map || !props.vehicles) return;
  
  Object.keys(vehicleLabels.value).forEach(vehicleId => {
    if (props.vehicles[vehicleId] && props.vehicles[vehicleId].position) {
      vehicleLabels.value[vehicleId].setPosition(props.vehicles[vehicleId].position);
    }
  });
}

// 组件卸载时清理资源
onUnmounted(() => {
  if (props.map) {
    Object.values(vehicleLabels.value).forEach(overlay => {
      props.map.removeOverlay(overlay);
    });
  }
  vehicleLabels.value = {};
});

// 监听地图变化
watch(() => props.map, (newMap) => {
  if (newMap) {
    // 地图实例变化时，重新创建所有标签
    Object.keys(vehicleLabels.value).forEach(vehicleId => {
      if (props.vehicles[vehicleId] && props.vehicles[vehicleId].position) {
        removeVehicleLabel(vehicleId);
        updateVehicleLabel(
          vehicleId, 
          props.vehicles[vehicleId].position, 
          props.vehicles[vehicleId].speed
        );
      }
    });
  }
});

// 向外暴露方法
defineExpose({
  updateVehicleLabel,
  removeVehicleLabel,
  setLabelVisibility,
  updateLabelPosition,
  updateAllLabels
});
</script>

<style>
/* 标签容器样式 */
.vehicle-label {
  position: absolute;
  transform: none;
  z-index: 1000;
  pointer-events: auto;
}

.label-container {
  background: rgba(238, 236, 225, 0.1);
  border-radius: 6px;
  color: #000;
  padding: 10px;
  padding-bottom: 0px;
  min-width: 280px;
  max-width: 380px;
  box-shadow: 0 10px 15px rgba(2, 2, 2, 0.25);
  border: 1px solid #40506a;
}

/* 简化标签样式 */
.simple-label {
  padding: 6px 10px;
  min-width: 150px;
  max-width: 220px;
}

/* 标签头部样式 */
.label-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  /* border-bottom: 1px solid rgba(255, 255, 255, 0.2); */
  padding-bottom: 5px;
}

.simple-label .label-header {
  margin-bottom: 0;
  border-bottom: none;
  padding-bottom: 0;
}

.vehicle-id {
  font-weight: bold;
  font-size: 16px;
}

.vehicle-speed {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.65);
  font-weight: bold;
}

/* 标签页按钮样式 */
.tab-buttons {
  display: flex;
  gap: 5px;
  margin-bottom: 6px;
  justify-content: flex-start;
  align-items: center;
}

.tab-content {
  min-width: 0;
}

.tab-button {
  border: none;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  padding: 0;
  background: transparent;
}

/* .tab-button.active {
  background-color: rgba(52, 152, 219, 0.7);
}

.tab-button.current {
  background-color: rgba(52, 152, 219, 1);
  box-shadow: 0 0 5px rgba(52, 152, 219, 0.7);
}

.tab-button.disabled {
  background-color: rgba(80, 80, 80, 0.3);
  cursor: not-allowed;
}

.tab-button.disabled .tab-icon {
  opacity: 0.5;
  filter: grayscale(100%);
} */

/* 标签图标样式 */
/* .tab-icon {
  width: 13px;
  height: 13px;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
}  */

.warning-icon {
  background-image: url(../../../assets/images/select_warning.png);
  background-size: cover;
}
.unwarning-icon {
  background-image: url(../../../assets/images/unselect_warning.png);
  background-size: 100% 100%;
}

.alarm-icon {
  background-image: url(../../../assets/images/select_alarm.png);
 background-size: cover;
}
.unalarm-icon {
  background-image: url(../../../assets/images/unselect_alarm.png);
  background-size: 100% 100%;
}
.speed-icon {
  background-image: url(../../../assets/images/select_speed.png);
  background-size: 100% 100%;
}
.unspeed-icon {
  background-image: url(../../../assets/images/unselect_speed.png);
  background-size: 100% 100%;
}
.boundary-icon {
  background-image: url(../../../assets/images/select_boundary.png);
  background-size: 100% 100%;
}
.unboundary-icon {
  background-image: url(../../../assets/images/unselect_boundary.png);
  background-size: 100% 100%;
}
.tab-pane {
  display: none;
}

.tab-pane.active {
  display: flex;
  align-items: center;
  min-width: 0;
}

/* 告警消息样式 */
.alert-message {
  font-size: 12px;
  font-weight: Medium;
  line-height: 1.2;
  padding: 2px 0;
  border-radius: 2px;
  background-color: transparent;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/* 具体告警提示 */
.alert{
  font-size: 14px;
  font-weight: bold;
  margin: 0 8px 0 0;
  display: inline-flex;
  align-items: center;
  flex: 0 0 auto;
}

.alert img {
  width: 14px;
  height: 14px;
  margin-right: 4px;
}

/* 超速信息样式 */
.speed-info {
  font-size: 12px;
  line-height: 1.4;
  padding: 5px;
  border-radius: 2px;
  background-color: transparent;
}

.limit-value {
  color: #4CAF50;
}

.actual-value {
  color: #FF4D4F;
  font-weight: bold;
}
</style> 
