<template>
  <!-- 模板部分保持不变 -->
  <div id="cesiumContainer" style="height: 100%;width: 100%;"></div>

  <!-- 控制按钮 -->
  <div class="control-buttons">
    <button class="control-btn" @click="goToHomeView" title="返回首页视角">
      <i class="fas fa-home"></i>
    </button>
    <button class="control-btn" @click="togglePOIDisplay" title="显示/隐藏POI点">
      <i class="fas fa-map-marker-alt" :class="{ 'active': poiVisible }"></i>
    </button>
    <button class="control-btn" @click="toggleTyphoon" title="显示/隐藏台风并切换视角">
      <i class="fas fa-wind" :class="{ 'active': typhoonVisible }"></i>
    </button>
  </div>

  <!-- 自定义弹框组件 - POI点 -->
  <div v-if="selectedPoint" class="custom-popup" :style="{
    left: `${popupPosition.x}px`,
    top: `${popupPosition.y}px`
  }">
    <div class="popup-content" :class="{ 'bottom': popupPosition.bottom }">
      <h3>{{ selectedPoint.STNM || '未知点' }}</h3>
      <p><strong>经度:</strong> {{ selectedPoint.LGTD }}</p>
      <p><strong>纬度:</strong> {{ selectedPoint.LTTD }}</p>
      <div class="popup-arrow"></div>
    </div>
  </div>

  <!-- 台风路径点信息弹窗 -->
  <div v-if="typhoonInfoVisible && typhoonVisible" class="typhoon-popup" :style="{
    left: `${typhoonPopupPosition.x}px`,
    top: `${typhoonPopupPosition.y}px`
  }">
    <div class="popup-content" :class="{ 'bottom': typhoonPopupPosition.bottom }">
      <h3>{{ typhoonInfo.name }}({{ typhoonInfo.enname }})</h3>
      <p>{{ typhoonInfo.time }}</p>
      <p><strong>中心位置:</strong> {{ typhoonInfo.lng }}° / {{ typhoonInfo.lat }}°</p>
      <p><strong>风速风力:</strong> {{ typhoonInfo.speed }} m/s ({{ typhoonInfo.power }}级)</p>
      <p><strong>中心气压:</strong> {{ typhoonInfo.pressure }} hPa</p>
      <p><strong>移速移向:</strong> {{ typhoonInfo.movedirection }} {{ typhoonInfo.movespeed }} km/h</p>
      <p><strong>七级半径:</strong> {{ typhoonInfo.radius7 || '--' }}</p>
      <p><strong>十级半径:</strong> {{ typhoonInfo.radius10 || '--' }}</p>
      <p><strong>十二级半径:</strong> {{ typhoonInfo.radius12 || '--' }}</p>
      <div class="popup-arrow"></div>
    </div>
  </div>

  <!-- 台风图例面板 -->
  <ul class="legend" v-if="typhoonVisible">
    <li>
      <span class="dot green"></span>
      <span>热带低压</span>
    </li>
    <li>
      <span class="dot blue"></span>
      <span>热带风暴</span>
    </li>
    <li>
      <span class="dot yellow"></span>
      <span>强热带风暴</span>
    </li>
    <li>
      <span class="dot orange"></span>
      <span>台风</span>
    </li>
    <li>
      <span class="dot red"></span>
      <span>超强台风</span>
    </li>
  </ul>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as Cesium from 'cesium';
import "cesium/Build/CesiumUnminified/Widgets/widgets.css";
import JYLData from '@/assets/Data/THJYL.json'
import axios from 'axios'

// 变量定义保持不变
const TDTTK = "d9e7aa2ad204aba6aeedea6f5ab48ed9";
const selectedPoint = ref(null);
const popupPosition = ref({ x: 0, y: 0, bottom: false });
let handler = null;
let viewer = null;

const typhoonInfoVisible = ref(false);
const typhoonInfo = ref({});
const typhoonPopupPosition = ref({ x: 0, y: 0, bottom: false });
const typhoonPointDataMap = ref(new Map());
const currentTyphoonEntity = ref(null);

const poiVisible = ref(true);
const typhoonVisible = ref(true);
const poiEntities = ref([]);

const fengquanLayers = ref([]);
const myEntityCollection = ref(null);
const tbentity = ref(null);
const iii = ref(0);
const currentPointObj = ref(null);
let typhoonInterval = null;
const typhoonRelatedEntities = ref({
  paths: [],
  forecasts: [],
  warnings: []
});

const popupUpdateCallbacks = ref({
  typhoon: null,
  poi: null
});

// 获取Cesium容器元素
const getCesiumContainer = () => {
  return document.getElementById('cesiumContainer');
};

// 获取Cesium容器的位置信息
const getCesiumContainerRect = () => {
  const container = getCesiumContainer();
  return container ? container.getBoundingClientRect() : { left: 0, top: 0, width: 0, height: 0 };
};

// 更新台风弹窗位置 - 确保箭头落在节点上
const updateTyphoonPopupPosition = (entity) => {
  if (popupUpdateCallbacks.value.typhoon) {
    viewer.scene.postRender.removeEventListener(popupUpdateCallbacks.value.typhoon);
    popupUpdateCallbacks.value.typhoon = null;
  }

  if (!entity || !entity.position || !typhoonInfoVisible.value) return;

  popupUpdateCallbacks.value.typhoon = () => {
    const container = getCesiumContainer();
    const containerRect = container.getBoundingClientRect();
    const entityPosition = viewer.scene.cartesianToCanvasCoordinates(
      entity.position.getValue(viewer.clock.currentTime)
    );

    if (entityPosition) {
      nextTick(() => {
        const popupEl = document.querySelector('.typhoon-popup .popup-content');
        if (!popupEl) return;

        // 获取弹窗尺寸和样式信息
        const popupRect = popupEl.getBoundingClientRect();
        const popupWidth = popupRect.width;
        const popupHeight = popupRect.height;
        const arrowHeight = 10; // 箭头高度

        // 获取台风点大小（用于精确对齐）
        const pointSize = entity.point?.pixelSize || getDynamicPointSize();
        const pointRadius = pointSize / 2; // 点的半径

        // 计算弹窗水平位置，增加微调修正偏右问题
        // 新增offsetX微调参数，可根据实际情况调整
        const offsetX = -15; // 向左微调2px，解决偏右问题
        let x = (entityPosition.x - containerRect.left) - (popupWidth / 2) + offsetX;

        // 计算弹窗垂直位置，解决上方显示时遮挡问题
        let y, bottom = false;

        // 上方显示时，增加额外间距避免遮挡
        const topSpacing = 35; // 额外间距
        y = (entityPosition.y - containerRect.top) - popupHeight - arrowHeight - pointRadius - topSpacing;

        // 如果上方空间不足，显示在点的下方
        if (y < 0) {
          y = (entityPosition.y - containerRect.top) + pointRadius + arrowHeight;
          bottom = true;
        }

        // 边界检查 - 确保弹窗不会超出容器
        if (x < 0) x = 0;
        if (x + popupWidth > containerRect.width) {
          x = containerRect.width - popupWidth;
        }

        // 更新弹窗位置
        typhoonPopupPosition.value = { x, y, bottom };
      });
    }
  };

  viewer.scene.postRender.addEventListener(popupUpdateCallbacks.value.typhoon);
  popupUpdateCallbacks.value.typhoon();
};

// 更新POI弹窗位置 - 同样确保箭头精准对齐
const updatePOIPopupPosition = (entity) => {
  if (popupUpdateCallbacks.value.poi) {
    viewer.scene.postRender.removeEventListener(popupUpdateCallbacks.value.poi);
    popupUpdateCallbacks.value.poi = null;
  }

  if (!entity || !entity.position || !selectedPoint.value) return;

  popupUpdateCallbacks.value.poi = () => {
    const container = getCesiumContainer();
    const containerRect = container.getBoundingClientRect();
    const entityPosition = viewer.scene.cartesianToCanvasCoordinates(
      entity.position.getValue(viewer.clock.currentTime)
    );

    if (entityPosition) {
      nextTick(() => {
        const popupEl = document.querySelector('.custom-popup .popup-content');
        if (!popupEl) return;

        const popupRect = popupEl.getBoundingClientRect();
        const popupWidth = popupRect.width;
        const popupHeight = popupRect.height;
        const arrowHeight = 10;

        // 计算POI点大小
        const billboardScale = entity.billboard?.scale || 0.4;
        const pointRadius = (20 * billboardScale) / 2; // 基于图标的大致半径

        // 计算弹窗位置
        let x = (entityPosition.x - containerRect.left) - (popupWidth / 2);
        let y, bottom = false;

        // 默认显示在点的上方
        y = (entityPosition.y - containerRect.top) - popupHeight - arrowHeight - pointRadius;

        // 如果上方空间不足，显示在点的下方
        if (y < 0) {
          y = (entityPosition.y - containerRect.top) + pointRadius + arrowHeight;
          bottom = true;
        }

        // 边界检查
        if (x < 0) x = 0;
        if (x + popupWidth > containerRect.width) {
          x = containerRect.width - popupWidth;
        }

        popupPosition.value = { x, y, bottom };
      });
    }
  };

  viewer.scene.postRender.addEventListener(popupUpdateCallbacks.value.poi);
  popupUpdateCallbacks.value.poi();
};

const getScaleRatio = () => {
  const designWidth = 1920;
  const designHeight = 1080;
  return Math.min(window.innerWidth / designWidth, window.innerHeight / designHeight);
};

const getPixelRatio = () => {
  return window.devicePixelRatio || 1;
};

const goToHomeView = () => {
  if (viewer) {
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(120.169103, 31.226174, 500000),
      orientation: {
        heading: Cesium.Math.toRadians(0),
        pitch: Cesium.Math.toRadians(-90),
      },
      duration: 1
    });
  }
};

const togglePOIDisplay = () => {
  poiVisible.value = !poiVisible.value;
  poiEntities.value.forEach(entity => {
    if (entity && entity.billboard) {
      entity.billboard.show = poiVisible.value;
      entity.label.show = poiVisible.value;
    }
  });
};

// 修改toggleTyphoon函数，确保显示时重新加载数据
const toggleTyphoon = () => {
  typhoonVisible.value = !typhoonVisible.value;

  console.log("台风显示状态切换为:", typhoonVisible.value);

  if (myEntityCollection.value) {
    myEntityCollection.value.show = typhoonVisible.value;
  }

  fengquanLayers.value.forEach(entity => {
    if (entity) {
      entity.show = typhoonVisible.value;
    }
  });

  typhoonRelatedEntities.value.paths.forEach(entity => {
    if (entity) {
      entity.show = typhoonVisible.value;
    }
  });

  typhoonRelatedEntities.value.forecasts.forEach(entity => {
    if (entity) {
      entity.show = typhoonVisible.value;
    }
  });

  typhoonRelatedEntities.value.warnings.forEach(entity => {
    if (entity) {
      entity.show = typhoonVisible.value;
    }
  });

  if (tbentity.value) {
    tbentity.value.show = typhoonVisible.value;
  }

  if (!typhoonVisible.value) {
    hideTyphoonPopup();
    if (typhoonInterval) {
      clearInterval(typhoonInterval);
      typhoonInterval = null;
    }
    removeTFLayer();
  } else {
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(120, 20, 4025692.0),
    });

    // 关键修复：强制重新加载台风数据
    if (myEntityCollection.value) {
      viewer.dataSources.remove(myEntityCollection.value);
    }
    myEntityCollection.value = new Cesium.CustomDataSource("typhoonPoints");
    viewer.dataSources.add(myEntityCollection.value);

    iii.value = 0;
    removeTFLayer();
    if (typhoonInterval) {
      clearInterval(typhoonInterval);
      typhoonInterval = null;
    }
    initPoints();
  }
};

const getDynamicPointSize = () => {
  const baseSize = 8;
  const scaleRatio = getScaleRatio();
  const pixelRatio = getPixelRatio();
  return Math.max(baseSize * scaleRatio * pixelRatio, 6);
};

const getDynamicPickRadius = () => {
  const baseRadius = 10;
  const scaleRatio = getScaleRatio();
  return baseRadius * (1 / scaleRatio);
};

const isPointInClickRange = (clickPosition, pointPosition, radius) => {
  const dx = clickPosition.x - pointPosition.x;
  const dy = clickPosition.y - pointPosition.y;
  return Math.sqrt(dx * dx + dy * dy) <= radius;
};

const checkTyphoonPointClick = (clickPosition) => {
  if (!myEntityCollection.value || !myEntityCollection.value.entities) return null;

  const radius = getDynamicPickRadius();
  const pixelRatio = getPixelRatio();
  const scaledClickPos = {
    x: clickPosition.x * pixelRatio,
    y: clickPosition.y * pixelRatio
  };

  const entities = myEntityCollection.value.entities.values;
  for (let i = 0; i < entities.length; i++) {
    const entity = entities[i];
    if (entity.id && entity.id.startsWith('typhoon-point-') && entity.position) {
      const pointPosition = viewer.scene.cartesianToCanvasCoordinates(entity.position._value);
      if (pointPosition && isPointInClickRange(scaledClickPos, pointPosition, radius)) {
        return entity;
      }
    }
  }

  return null;
};

const hideTyphoonPopup = () => {
  typhoonInfoVisible.value = false;
  if (popupUpdateCallbacks.value.typhoon) {
    viewer.scene.postRender.removeEventListener(popupUpdateCallbacks.value.typhoon);
    popupUpdateCallbacks.value.typhoon = null;
  }
};

const hidePOIPopup = () => {
  selectedPoint.value = null;
  if (popupUpdateCallbacks.value.poi) {
    viewer.scene.postRender.removeEventListener(popupUpdateCallbacks.value.poi);
    popupUpdateCallbacks.value.poi = null;
  }
};

onMounted(async () => {


  // 初始化Cesium viewer
  viewer = new Cesium.Viewer('cesiumContainer', {
    timeline: false,
    baseLayer: false,
    geocoder: false,
    homeButton: false,
    sceneModePicker: false,
    navigationHelpButton: false,
    animation: false,
    fullscreenButton: false,
    vrButton: false,
    selectionIndicator: false,
    infoBox: false,
    // 加载地形效果
    terrainProvider: await Cesium.createWorldTerrainAsync({
      requestVertexNormals: true,
    })
  });

  // 监听窗口大小变化，动态调整台风点大小
  window.addEventListener('resize', () => {
    updateTyphoonPointSizes();
    viewer.resize();
  });

  // 多块倾斜摄影瓦片集的URL列表
  const tilesetUrls = [
    "http://localhost:9003/model/TSQ1234/tileset.json",
    "http://localhost:9003/model/SY123/tileset.json",
  ];

  // 存储加载成功的瓦片集
  const loadedTilesets = [];

  // 批量加载瓦片集
  async function loadMultipleTilesets() {
    try {
      const promises = tilesetUrls.map(async (url, index) => {
        try {
          const tileset = await Cesium.Cesium3DTileset.fromUrl(url, {
            maximumScreenSpaceError: 32,
            dynamicScreenSpaceError: true,
            skipLevelOfDetail: true,
            maximumConcurrentRequests: 5,
            tileCacheSize: 100
          });
          viewer.scene.primitives.add(tileset);
          loadedTilesets.push(tileset);
          console.log(`第${index + 1}块瓦片集加载完成`);
          return tileset;
        } catch (error) {
          console.error(`第${index + 1}块瓦片集加载失败：`, error);
          return null;
        }
      });

      await Promise.all(promises);
      console.log("所有瓦片集加载操作已完成");
    } catch (error) {
      console.error("批量加载逻辑出错：", error);
    }
  }

  // 执行加载
  loadMultipleTilesets();

  // 定义距离显示条件和缩放属性
  const distanceDisplayCondition = new Cesium.DistanceDisplayCondition(0, 10000000);
  const pointNearFarScalar = new Cesium.NearFarScalar(10000, 1.0, 1000000, 0.3);
  const labelNearFarScalar = new Cesium.NearFarScalar(10000, 1.0, 400000, 0);

  // 存储实体与数据的映射
  const entityDataMap = new Map();
  JYLData.forEach((item) => {
    const position = Cesium.Cartesian3.fromDegrees(
      parseFloat(item.LGTD),
      parseFloat(item.LTTD)
    );
    const entity = viewer.entities.add({
      position: position,
      billboard: {
        image: '/src/assets/icon/blue.png',
        scale: 0.4,
        color: Cesium.Color.YELLOW,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        distanceDisplayCondition: distanceDisplayCondition,
        scaleByDistance: pointNearFarScalar
      },
      label: {
        text: item.STNM || '未知点',
        font: '25px 微软雅黑',
        fillColor: Cesium.Color.WHITE,
        backgroundColor: new Cesium.Color(0.1, 0.1, 0.1, 0.7),
        backgroundPadding: new Cesium.Cartesian2(8, 4),
        showBackground: true,
        cornerRadius: 4,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 1,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(0, -32),
        scale: 1.0,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        distanceDisplayCondition: distanceDisplayCondition,
        scaleByDistance: labelNearFarScalar
      },
      id: `point-${item.STCD || item.LGTD + '-' + item.LTTD}`,
      properties: {
        data: item
      }
    });
    entityDataMap.set(entity.id, item);
    poiEntities.value.push(entity);
  });

  // 添加天地图图层
  const tdtLayer = new Cesium.WebMapTileServiceImageryProvider({
    url: `https://t0.tianditu.com/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&tk=${TDTTK}`,
    layer: "tdt",
    style: "default",
    format: "image/jpeg",
    tileMatrixSetID: "w",
    maximumLevel: 16,
    show: true,
  });
  viewer.imageryLayers.addImageryProvider(tdtLayer);

  const tdtAnnotionLayer = new Cesium.WebMapTileServiceImageryProvider({
    url: `http://t0.tianditu.com/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&tk=${TDTTK}`,
    layer: "tdtAnno",
    style: "default",
    format: "image/jpeg",
    tileMatrixSetID: "w",
    maximumLevel: 18,
    show: false,
  });
  viewer.imageryLayers.addImageryProvider(tdtAnnotionLayer);

  // 初始化视图
  viewer.cesiumWidget.creditContainer.style.display = "none";
  viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(120.169103, 31.226174, 500000),
    orientation: {
      heading: Cesium.Math.toRadians(0),
      pitch: Cesium.Math.toRadians(-90),
    },
  });

  // 点击事件处理
  handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  handler.setInputAction((click) => {
    const scaleRatio = getScaleRatio();
    const pixelRatio = getPixelRatio();
    const correctedX = click.position.x / scaleRatio;
    const correctedY = click.position.y / scaleRatio;

    // 先尝试标准拾取
    const pickedObject = viewer.scene.pick(new Cesium.Cartesian2(correctedX, correctedY));

    // 如果标准拾取未命中，尝试自定义范围拾取台风点
    const typhoonPoint = pickedObject ? null : checkTyphoonPointClick(click.position);
    const finalPickedObject = pickedObject || typhoonPoint;

    // 隐藏所有弹窗
    hideTyphoonPopup();
    hidePOIPopup();

    if (Cesium.defined(finalPickedObject) && Cesium.defined(finalPickedObject.id)) {
      const entityId = finalPickedObject.id.id;
      const data = entityDataMap.get(entityId) ||
        typhoonPointDataMap.value.get(entityId) ||
        finalPickedObject.id.properties?.data?.getValue();

      if (data) {
        // 判断是POI点还是台风点
        if (entityId.startsWith('typhoon-point-')) {
          // 处理台风点点击
          currentTyphoonEntity.value = finalPickedObject.id;
          typhoonInfo.value = data;
          typhoonInfoVisible.value = true;
          updateTyphoonPopupPosition(finalPickedObject.id);
        } else {
          // 处理POI点点击
          selectedPoint.value = data;
          updatePOIPopupPosition(finalPickedObject.id);
        }

        viewer.flyTo(finalPickedObject.id, {
          offset: new Cesium.HeadingPitchRange(0, -0.5, 1500)
        });
      }
    } else {
      selectedPoint.value = null;
      currentTyphoonEntity.value = null;
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  // 添加鼠标移动事件处理 - 用于台风路径点悬停
  handler.setInputAction((movement) => {
    // 只有台风可见时才处理台风信息弹窗
    if (!typhoonVisible.value) {
      hideTyphoonPopup();
      return;
    }

    const scaleRatio = getScaleRatio();
    const correctedX = movement.endPosition.x / scaleRatio;
    const correctedY = movement.endPosition.y / scaleRatio;

    // 先尝试标准拾取
    const pickedObject = viewer.scene.pick(new Cesium.Cartesian2(correctedX, correctedY));
    // 如果标准拾取未命中，尝试自定义范围拾取台风点
    const typhoonPoint = pickedObject ? null : checkTyphoonPointClick(movement.endPosition);
    const finalPickedObject = pickedObject || typhoonPoint;

    // 检查是否悬停在台风路径点上
    if (Cesium.defined(finalPickedObject) && Cesium.defined(finalPickedObject.id)) {
      const entityId = finalPickedObject.id.id;
      // 检查是否是台风路径点
      if (entityId && entityId.startsWith('typhoon-point-')) {
        const typhoonData = typhoonPointDataMap.value.get(entityId);
        if (typhoonData) {
          // 显示台风信息弹窗
          currentTyphoonEntity.value = finalPickedObject.id;
          typhoonInfo.value = typhoonData;
          typhoonInfoVisible.value = true;
          updateTyphoonPopupPosition(finalPickedObject.id);
          return; // 找到台风点后不再处理其他逻辑
        }
      }
    }

    // 如果不是台风路径点，隐藏台风信息弹窗
    hideTyphoonPopup();
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  // 初始化台风相关功能
  initTyphoonVisualization();

  // 初始触发一次 resize 确保地图正确显示
  viewer.resize();
});

// 其余函数保持不变
const updateTyphoonPointSizes = () => {
  if (!myEntityCollection.value || !myEntityCollection.value.entities) return;

  const newSize = getDynamicPointSize();
  const entities = myEntityCollection.value.entities.values;

  for (let i = 0; i < entities.length; i++) {
    const entity = entities[i];
    if (entity.id && entity.id.startsWith('typhoon-point-') && entity.point) {
      entity.point.pixelSize = newSize;
    }
  }
};

const initTyphoonVisualization = () => {
  Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI1ODIwOGQ2Ny1hMTFhLTQ4OGQtODJhZi0wNmMzZGNhNjU5OWMiLCJpZCI6NTkzMTMsImlhdCI6MTYyMzk4ODQ4NX0.40CU0i0LswshdxVXAXEJgfEDJN3EK_jPbo_S8lece9E';

  myEntityCollection.value = new Cesium.CustomDataSource("typhoonPoints");
  viewer.dataSources.add(myEntityCollection.value);

  initJJ();
  initPoints();
};

// 在initPoints函数中修改测试数据部分
const initPoints = () => {
  const jsonUrl = new URL('../assets/Data/202508.json', import.meta.url).href;

  axios.get(jsonUrl)
    .then(response => {
      const typhoonData = response.data;
      // 验证数据结构是否正确
      if (typhoonData && typhoonData.points && Array.isArray(typhoonData.points)) {
        processPoints(typhoonData.points, typhoonData);
        updateTyphoonPointSizes();
      } else {
        console.error('台风数据结构不正确，使用测试数据');
        useTestData();
      }
    })
    .catch(error => {
      console.error('加载台风JSON数据失败，使用测试数据', error);
      useTestData();
    });
};

// 新增一个专门的函数来提供测试数据
const useTestData = () => {
  const testTyphoonData = {
    "name": "竹节草",
    "enname": "CO-MAY",
    "points": [
      {
        "time": "2025-07-23 14:00:00",
        "lng": "119.20",
        "lat": "18.40",
        "strong": "热带低压",
        "power": "7",
        "speed": "15",
        "pressure": "998",
        "movespeed": "14",
        "movedirection": "南西",
        "radius7": "180|120|200|150",
        "radius10": "",
        "radius12": "",
        "forecast": [
          {
            "tm": "中国",
            "forecastpoints": [
              { "lng": 121, "lat": 19 },
              { "lng": 122, "lat": 18 }
            ]
          }
        ]
      },
      {
        "time": "2025-07-23 17:00:00",
        "lng": "119.10",
        "lat": "18.00",
        "strong": "热带低压",
        "power": "7",
        "speed": "15",
        "pressure": "996",
        "movespeed": "13",
        "movedirection": "南南西",
        "radius7": "180|120|200|150",
        "radius10": "",
        "radius12": "",
        "forecast": []
      }
    ]
  };
  
  // 确保points是数组
  if (!testTyphoonData.points || !Array.isArray(testTyphoonData.points)) {
    testTyphoonData.points = [];
  }
  
  processPoints(testTyphoonData.points, testTyphoonData);
  updateTyphoonPointSizes();
};


// 修改processPoints函数，确保路径正确创建
const processPoints = (points, typhoonData) => {
  const lineArr = [];
  const pointSize = getDynamicPointSize();

  // 清除现有台风点
  if (myEntityCollection.value && myEntityCollection.value.entities) {
    myEntityCollection.value.entities.removeAll();
  }

  // 重新添加所有台风点
  points.forEach((element, index) => {
    const lng = Number(element.lng);
    const lat = Number(element.lat);

    let color = Cesium.Color.RED;
    switch (element.strong) {
      case "热带低压":
        color = Cesium.Color.GREEN;
        break;
      case "热带风暴":
        color = Cesium.Color.BLUE;
        break;
      case "强热带风暴":
        color = Cesium.Color.YELLOW;
        break;
      case "台风":
        color = Cesium.Color.fromCssColorString("#FBC712");
        break;
      case "强台风":
        color = Cesium.Color.PLUM;
        break;
      case "超强台风":
        color = Cesium.Color.RED;
        break;
    }

    lineArr.push(lng, lat);
    const pointId = `typhoon-point-${index}`;
    const entity = new Cesium.Entity({
      id: pointId,
      position: Cesium.Cartesian3.fromDegrees(lng, lat),
      point: {
        pixelSize: pointSize,
        color: color,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 2,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        show: typhoonVisible.value // 确保点的可见性与台风显示状态一致
      }
    });
    myEntityCollection.value.entities.add(entity);

    typhoonPointDataMap.value.set(pointId, {
      name: typhoonData.name || '',
      enname: typhoonData.enname || '',
      time: element.time || '',
      lng: element.lng,
      lat: element.lat,
      speed: element.speed,
      power: element.power,
      pressure: element.pressure,
      movedirection: element.movedirection,
      movespeed: element.movespeed,
      radius7: element.radius7 || '--',
      radius10: element.radius10 || '--',
      radius12: element.radius12 || '--'
    });
  });

  // 确保路径正确创建和显示
  // 先清除现有路径
  typhoonRelatedEntities.value.paths.forEach(entity => {
    viewer.entities.remove(entity);
  });
  typhoonRelatedEntities.value.paths = [];

  // 仅当有足够的点时创建路径
  if (lineArr.length >= 4) { // 至少需要两个点(每个点包含经纬度)
    const pathEntity = viewer.entities.add({
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArray(lineArr),
        width: 3,
        clampToGround: true,
        material: Cesium.Color.RED,
        show: typhoonVisible.value // 确保路径可见性
      }
    });
    typhoonRelatedEntities.value.paths.push(pathEntity);
    console.log("台风路径已创建，点数量:", lineArr.length / 2);
  } else {
    console.warn("点数量不足，无法创建台风路径");
  }

  if (points.length > 0) {
    // 清除现有预报
    typhoonRelatedEntities.value.forecasts.forEach(entity => {
      viewer.entities.remove(entity);
    });
    typhoonRelatedEntities.value.forecasts = [];

    initForeast(points[points.length - 1]);

    // 确保从初始状态开始动画
    iii.value = 0;
    removes();
    adds(points, typhoonData);
  }
};

// 修改removes函数，在移除风圈时同时移除风眼图标
const removes = () => {
  // 移除风圈
  fengquanLayers.value.forEach(entity => {
    viewer.entities.remove(entity);
  });
  fengquanLayers.value = [];

  // 移除风眼图标
  if (tbentity.value) {
    viewer.entities.remove(tbentity.value);
    tbentity.value = null;
  }
};


const initForeast = (data) => {
  const forecast = data.forecast || [];
  const colorArr = [
    Cesium.Color.fromCssColorString("#2D12FB"),
    Cesium.Color.fromCssColorString("#15E5E7"),
    Cesium.Color.fromCssColorString("#15E74A"),
    Cesium.Color.fromCssColorString("#E76F15"),
    Cesium.Color.fromCssColorString("#15D9E7")
  ];

  forecast.forEach((ele, ii) => {
    if (ele.forecastpoints && ele.forecastpoints.length > 0) {
      const lineArr = [];
      ele.forecastpoints.forEach(e => {
        const lng = Number(e.lng);
        const lat = Number(e.lat);
        lineArr.push(lng, lat);

        const entity = new Cesium.Entity({
          position: Cesium.Cartesian3.fromDegrees(lng, lat),
          point: {
            pixelSize: getDynamicPointSize() * 0.8,
            color: colorArr[ii % colorArr.length]
          }
        });
        myEntityCollection.value.entities.add(entity);
      });

      const forecastEntity = viewer.entities.add({
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArray(lineArr),
          width: 2,
          clampToGround: true,
          material: new Cesium.PolylineDashMaterialProperty({
            color: colorArr[ii % colorArr.length]
          })
        }
      });
      typhoonRelatedEntities.value.forecasts.push(forecastEntity);
    }
  });
};

const initJJ = () => {
  // 24小时警戒线
  const line24h = viewer.entities.add({
    name: '24小时警戒线',
    polyline: {
      positions: Cesium.Cartesian3.fromDegreesArray([
        127, 34, 127, 22, 119, 18, 119, 11, 113, 4.5, 105, 0
      ]),
      width: 2,
      material: Cesium.Color.RED,
      clampToGround: true
    }
  });
  typhoonRelatedEntities.value.warnings.push(line24h);

  // 48小时警戒线
  const line48h = viewer.entities.add({
    name: '48小时警戒线',
    polyline: {
      positions: Cesium.Cartesian3.fromDegreesArray([
        132, 34, 132, 22, 119, 0, 105, 0
      ]),
      width: 2,
      material: Cesium.Color.YELLOW,
      clampToGround: true
    }
  });
  typhoonRelatedEntities.value.warnings.push(line48h);

  // 警戒线标签
  const label24h = viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(126.129019, 29.104287),
    label: {
      fillColor: Cesium.Color.RED,
      text: '24小时警戒线',
      font: '14pt monospace'
    }
  });
  typhoonRelatedEntities.value.warnings.push(label24h);

  const label48h = viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(132, 20),
    label: {
      fillColor: Cesium.Color.YELLOW,
      text: '48小时警戒线',
      font: '14pt monospace'
    }
  });
  typhoonRelatedEntities.value.warnings.push(label48h);
};

// 在adds函数中修改定时器逻辑
const adds = (data, typhoonData) => {
  addTB(typhoonData);

  // 清除可能存在的旧定时器
  if (typhoonInterval) {
    clearInterval(typhoonInterval);
    typhoonInterval = null;
  }

  // 重置计数器
  iii.value = 0;

  // 创建新的定时器，只播放一次
  typhoonInterval = setInterval(() => {
    if (!typhoonVisible.value) return;

    // 当计数器达到数据长度时，清除定时器，停止动画
    if (iii.value >= data.length) {
      clearInterval(typhoonInterval);
      typhoonInterval = null;
      return;
    }

    const kkk = iii.value * 2;
    const currentData = data[iii.value];
    currentPointObj.value = {
      lon: Number(currentData.lng),
      lat: Number(currentData.lat),
      circle7: {
        radius1: 350 - kkk,
        radius2: 450 - kkk,
        radius3: 400 - kkk,
        radius4: 350 - kkk
      },
      circle10: {
        radius1: 250 - kkk,
        radius2: 270 - kkk,
        radius3: 250 - kkk,
        radius4: 220 - kkk
      },
      circle12: {
        radius1: 170 - kkk,
        radius2: 150 - kkk,
        radius3: 150 - kkk,
        radius4: 170 - kkk
      }
    };

    if (tbentity.value) {
      tbentity.value.position = Cesium.Cartesian3.fromDegrees(
        Number(currentData.lng),
        Number(currentData.lat)
      );
    }

    // 继续下一个帧
    iii.value++;
    removeTFLayer();
    if (typhoonVisible.value) {
      addTyphoonCircle();
    }
  }, 200);
};

const addTB = (typhoonData) => {
  const SuperGif = window.SuperGif;
  if (typeof SuperGif !== 'function') {
    console.warn('SuperGif未加载成功，使用默认标记');
    useDefaultMarker(typhoonData);
    return;
  }

  const img = document.createElement('img');
  img.src = '/tf.gif';

  img.onload = () => {
    try {
      const rub = new SuperGif({ gif: img });
      rub.load(() => {
        tbentity.value = viewer.entities.add({
          position: Cesium.Cartesian3.fromDegrees(
            Number(typhoonData.centerlng || 123.75),
            Number(typhoonData.centerlat || 28.95)
          ),
          billboard: {
            image: new Cesium.CallbackProperty(() => {
              return rub.get_canvas().toDataURL('image/png');
            }, false),
            scale: 0.1 * getScaleRatio()
          }
        });
      });
    } catch (error) {
      console.error('GIF处理失败，使用默认标记', error);
      useDefaultMarker(typhoonData);
    }
  };

  img.onerror = () => {
    console.error('GIF加载失败，使用默认标记');
    useDefaultMarker(typhoonData);
  };
};

const useDefaultMarker = (typhoonData) => {
  tbentity.value = viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(
      Number(typhoonData.centerlng || 123.75),
      Number(typhoonData.centerlat || 28.95)
    ),
    point: {
      pixelSize: getDynamicPointSize() * 1.5,
      color: Cesium.Color.RED,
      outlineColor: Cesium.Color.WHITE,
      outlineWidth: 2
    }
  });
};

const removeTFLayer = () => {
  fengquanLayers.value.forEach(entity => {
    viewer.entities.remove(entity);
  });
  fengquanLayers.value = [];
};

const addTyphoonCircle = () => {
  if (!currentPointObj.value || !typhoonVisible.value) return;

  const circles = ['circle7', 'circle10', 'circle12'];
  circles.forEach(item => {
    const entity = viewer.entities.add({
      id: `tf_polygon_${item}`,
      polygon: {
        hierarchy: new Cesium.CallbackProperty(() => {
          const points = currentPointObj.value[item]
            ? getTyphoonPolygonPoints(currentPointObj.value, item)
            : [];
          return new Cesium.PolygonHierarchy(
            Cesium.Cartesian3.fromDegreesArray(points)
          );
        }, false),
        material: Cesium.Color.ORANGE.withAlpha(0.05),
        extrudedHeight: 1000,
        outline: true,
        outlineColor: Cesium.Color.ORANGE,
        outlineWidth: 2
      },
      polyline: {
        positions: new Cesium.CallbackProperty(() => {
          const points = currentPointObj.value[item]
            ? getTyphoonPolygonPoints(currentPointObj.value, item)
            : [];
          return Cesium.Cartesian3.fromDegreesArray(points);
        }, false),
        material: Cesium.Color.ORANGE,
        width: 2,
        height: 1000
      }
    });
    fengquanLayers.value.push(entity);
  });
};

const getTyphoonPolygonPoints = (pointObj, cNum) => {
  const points = [];
  const center = [Number(pointObj.lon), Number(pointObj.lat)];
  const radiusList = [
    pointObj[cNum].radius1,
    pointObj[cNum].radius2,
    pointObj[cNum].radius3,
    pointObj[cNum].radius4
  ];
  const startAngleList = [0, 90, 180, 270];
  let fx, fy;

  startAngleList.forEach((startAngle, index) => {
    const radius = radiusList[index] / 100;
    const pointNum = 90;
    const endAngle = startAngle + 90;

    for (let i = 0; i <= pointNum; i++) {
      const angle = startAngle + ((endAngle - startAngle) * i) / pointNum;
      const sin = Math.sin((angle * Math.PI) / 180);
      const cos = Math.cos((angle * Math.PI) / 180);
      const x = center[0] + radius * sin;
      const y = center[1] + radius * cos;
      points.push(x, y);

      if (startAngle === 0 && i === 0) {
        fx = x;
        fy = y;
      }
    }
  });

  points.push(fx, fy);
  return points;
};

onUnmounted(() => {
  if (typhoonInterval) {
    clearInterval(typhoonInterval);
  }

  if (popupUpdateCallbacks.value.typhoon) {
    viewer.scene.postRender.removeEventListener(popupUpdateCallbacks.value.typhoon);
  }
  if (popupUpdateCallbacks.value.poi) {
    viewer.scene.postRender.removeEventListener(popupUpdateCallbacks.value.poi);
  }

  window.removeEventListener('resize', updateTyphoonPointSizes);

  if (handler) {
    handler.destroy();
    handler = null;
  }

  if (viewer && !viewer.isDestroyed()) {
    viewer.destroy();
  }
});
</script>

<style scoped>
/* 控制按钮样式保持不变 */
.control-buttons {
  position: absolute;
  top: 200px;
  left: 150px;
  z-index: 100;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.control-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.9);
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #333;
}

.control-btn:hover {
  background-color: white;
  transform: scale(1.1);
}

.control-btn .active {
  color: #1E88E5;
}


/* 弹窗样式 - 关键调整确保箭头精准对齐 */
.custom-popup,
.typhoon-popup {
  position: absolute;
  z-index: 1000;
  pointer-events: none;
  /* 确保弹窗相对于Cesium容器定位 */
  top: 0;
  left: 0;
}

.popup-content {
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  padding: 10px 15px;
  width: 240px;
  pointer-events: all;
  min-width: 200px;
  box-sizing: border-box;
  position: relative;
  /* 确保箭头定位正确 */
}

/* 箭头样式优化 - 确保尖端精准指向节点中心 */
.popup-arrow {
  position: absolute;
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  left: 50%;
  transform: translateX(-50%);
  /* 微调箭头水平位置，解决偏右 */
}

/* 上方弹窗的箭头（指向下方节点） */
.popup-content:not(.bottom) .popup-arrow {
  bottom: -10px;
  /* 箭头底部与弹窗底部对齐 */
  border-top: 10px solid white;
}

/* 下方弹窗的箭头（指向上方节点） */
.popup-content.bottom .popup-arrow {
  top: -10px;
  /* 箭头上部与弹窗顶部对齐 */
  border-bottom: 10px solid white;
}

.popup-content h3 {
  margin-top: 0;
  margin-bottom: 8px;
  color: #333;
  font-size: 16px;
}

.popup-content p {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}

/* 台风图例样式保持不变 */
.legend {
  position: absolute;
  z-index: 100;
  bottom: 30px;
  right: 10px;
  color: #fff;
  background: rgba(0, 0, 0, 0.8);
  list-style: none;
  padding: 10px 15px;
  border-radius: 4px;
  margin: 0;
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.legend li {
  display: flex;
  align-items: center;
  margin: 5px 0;
}

.dot {
  border-radius: 50%;
  width: 10px;
  height: 10px;
  display: inline-block;
  margin-right: 8px;
}

.green {
  background: green;
}

.blue {
  background: blue;
}

.yellow {
  background: yellow;
}

.orange {
  background: #FBC712;
}

.red {
  background: red;
}

/* 响应式调整保持不变 */
@media (max-width: 1200px) {
  .control-buttons {
    top: 150px;
    left: 20px;
  }

  .legend {
    padding: 5px 10px;
  }

  .legend li {
    font-size: 12px;
    margin: 3px 0;
  }
}

@media (max-width: 768px) {
  .popup-content {
    width: 200px;
    padding: 8px 12px;
  }

  .popup-content h3 {
    font-size: 14px;
  }

  .popup-content p {
    font-size: 12px;
    margin: 3px 0;
  }
}

/* 高DPI屏幕适配保持不变 */
@media (min-resolution: 192dpi) {
  .popup-content {
    transform: scale(0.95);
  }

  .popup-content.bottom {
    transform-origin: center bottom;
  }
}
</style>