<template>
  <div class="platform-overview platform-no-padding">
    <OpenLayersMap 
      ref="mapRef" 
      :vehicleMovementControl="vehicleMovementRef"
      :vehicleCategories="vehicleCategories" 
      @setCategoryVisibility="handleSetCategoryVisibility"
    />
    <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 v-if="showAlarmPanel" @close="showAlarmPanel = false" />
    <!-- 报警通知按钮 -->
    <div class="alarm-btn" @click="showAlarmPanel = !showAlarmPanel">
      <i class="alarm-icon"></i>
      <span class="alarm-badge" v-if="alarmCount > 0">{{ alarmCount }}</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" /> -->


    <!-- 绘制工具栏 -->
    <!-- <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 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';

const showEventList = ref(false); // 默认不显示列表
const showAlarmPanel = ref(false); // 默认不显示报警面板
const alarmCount = ref(4); // 报警数量
const mapRef = ref(null);
const vehicleMovementRef = ref(null);
const map = ref(null); // 存储地图实例

// 告警统计数据
const warningCount = ref(2);  // 冲突预警
const alertCount = ref(1);    // 冲突告警
const boundaryCount = ref(3); // 越界告警
const speedCount = ref(5);    // 超速告警

// 新告警标记
const hasNewWarning = ref(false);
const hasNewAlert = ref(false);
const hasNewBoundary = ref(false);
const hasNewSpeed = ref(false);

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

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

// 模拟接收新告警
function simulateNewAlarm() {
  // 随机选择一种告警类型
  const alarmType = Math.floor(Math.random() * 4);
  
  switch(alarmType) {
    case 0:
      warningCount.value++;
      hasNewWarning.value = true;
      setTimeout(() => { hasNewWarning.value = false; }, 10000);
      break;
    case 1:
      alertCount.value++;
      hasNewAlert.value = true;
      setTimeout(() => { hasNewAlert.value = false; }, 10000);
      break;
    case 2:
      boundaryCount.value++;
      hasNewBoundary.value = true;
      setTimeout(() => { hasNewBoundary.value = false; }, 10000);
      break;
    case 3:
      speedCount.value++;
      hasNewSpeed.value = true;
      setTimeout(() => { hasNewSpeed.value = false; }, 10000);
      break;
  }
  
  // 更新总告警数量
  alarmCount.value = 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);
  }
}

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

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

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;
  }
}



// 组件激活时检查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(() => {
      map.value = mapRef.value.map;
      console.log('地图实例已获取:', map.value);
      
      // 可以在这里启动测试
      // testVehicleMovement();
    }, 1000);
  }
  
  // 组件卸载时清理定时器
  onUnmounted(() => {
    clearInterval(timeInterval);
  });
  
  // 设置模拟告警定时器（仅开发环境）
  if (isDevelopment) {
    setInterval(simulateNewAlarm, 5000); // 每5秒模拟一次新告警
  }
});

onUnmounted(() => {
  document.querySelector('.app-main')?.classList.remove('platform-no-padding');
});

// 监听地图实例引用变化
watch(() => mapRef.value?.map, (newMap) => {
  if (newMap) {
    map.value = newMap;
    console.log('地图实例已更新:', map.value);
  }
});
</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: 25%;
  left: 20px;
  width: 240px;
  background-color: rgba(41, 44, 56, 0.85);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  color: #fff;
  z-index: 1000;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  overflow: hidden;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 10px; /* 减小内边距 */
  background-color: rgba(0, 0, 0, 0.2);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.stats-title {
  font-size: 14px;
  font-weight: bold;
}

.stats-time {
  font-size: 12px;
  color: #A0A8B7;
  font-family: 'Courier New', monospace;
}

.stats-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1px;
  // background-color: rgba(255, 255, 255, 0.05);
  padding: 1px;
}

.stats-item {
  
  position: relative;
  padding: 8px 10px; /* 减小内边距 */
  display: flex;
  flex-direction: row; /* 改为水平布局 */
  align-items: center;
  // 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);
    animation: pulse 1.5s infinite;
    
    .stats-count {
      color: #FF4D4F;
    }
  }
}

.stats-icon {

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


.stats-text {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.stats-count {
  font-size: 16px;
  font-weight: bold;
  line-height: 1;
}

.stats-label {
  font-size: 12px;
  color: #A0A8B7;
  margin-top: 2px;
}

.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>