<template>
  <div class="mapBox">
    <div id="cesiumContainer" style="width: 100%; height: 100vh"></div>
    <div class="menuComC" v-if="0">
      <!-- @handleWindspeed="switchWindLayer"
        @handleCloudLayer="switchCloudLayer"
        @handleRainLayer="switchRainLayer"
        @handleTemperatureLayerr="switchTemperatureLayerr"
        @handleCity="switchCity" -->
      <menuCom
        :showwindspeed="false"
        :showcloud="false"
        :showrainfall="false"
        :showtemperature="false"
        :showcity="false"
        @handleInit="initresetViewport"
        @handleBaseMap="setMapImageryProvider"
        @handleTopographicMap="switchTopographicMap"
      />
    </div>
    <div
      class="tag"
      :style="`left:${userClickLeft}px;top:${userClickTop}px`"
      v-if="tagMsg || tagMsg === ''"
    >
      <el-icon class="is-loading" v-if="tagMsg === ''">
        <Loading />
      </el-icon>
      <span v-else>{{ tagMsg || "" }}</span>
    </div>
    <!-- Loading 层 -->
    <div id="loading" class="dataLoading">加载中...</div>
    <!-- <div class="devInfoBox" v-if="showDevInfoBox">
      <div class="item">===&nbsp;帧率与内存&nbsp;===</div>
      <div class="item">运行帧率:&nbsp;{{ fps }}</div>
      <div class="item">响应时长:&nbsp;{{ ms }}</div>
      <div class="item">内存占用:&nbsp;{{ jsHeapSize }}</div>
      <template v-if="gVendor || gRenderer">
        <div class="item" style="margin-top: 12px">
          ====&nbsp;显卡信息&nbsp;====
        </div>
        <el-tooltip
          effect="dark"
          :content="gVendor"
          placement="top-end"
          v-if="gVendor"
        >
          <div class="item">制造商:&nbsp;{{ gVendor }}</div>
        </el-tooltip>
        <el-tooltip
          effect="dark"
          :content="gRenderer"
          placement="top-end"
          v-if="gRenderer"
        >
          <div class="item">型号:&nbsp;{{ gRenderer }}</div>
        </el-tooltip>
      </template>
    </div>  -->
    <!-- <div class="tempImg" v-if="showtempImg">
      <img src="../assets/cesiumImg/temp.png" />
    </div> -->
    <el-drawer
      v-model="windDrawer"
      direction="rtl"
      class="windModelDrawer"
      :before-close="handleClose"
    >
      <template #header>
        <h3 style="font-weight: bold">{{ windDrawerHeader }}</h3>
      </template>
      <template #default>
        <div class="windDrawerCla">
          <div class="line" v-if="!showModelMsg">
            <div class="leftContent">
              <span>{{ windDrawerTitle }}</span>
            </div>
          </div>
          <div class="jcxx" v-if="showBasicMsg">
            <windHome :modelValItem="modelVal" />
          </div>
          <div class="spjk" v-if="showVideoMsg">
            <!-- src="https://www.bilibili.com/video/BV1421DYCELw?t=12.1" -->
            <iframe
              src="/public/static/windVideo.mp4"
              frameborder="0"
              style="width: 100%; height: 100%"
            ></iframe>
            <!-- src="https://www.bilibili.com/video/BV1421DYCELw?t=12.1" -->
            <video ref="videoPlayer" controls width="95%">
              <source src="/public/static/windVideo.mp4" type="video/mp4" />
            </video>
          </div>
          <div class="gzck" v-if="showProblemMsg">
            <windPro />
          </div>
        </div>
      </template>
    </el-drawer>
    <cesiumweatherView
      :viewer="viewer"
      :sidebarRightData="sidebarRightData"
      :stationValue="stationValue"
      @coverOnChange="coverOnChange"
      @changeType="changeType"
      v-if="showTypeViewer"
    />
    <cesiumwindView
      v-if="showWindDetail"
      @showDetail="menuComTSty"
      @backStations="backStations"
    />
  </div>
</template>

<script>
// import * as Cesium from "../Cesium";
// import "../Cesium/Widgets/widgets.css";
import * as Cesium from "cesium";
import "cesium/Build/Cesium/Widgets/widgets.css";
import { createWind } from "../assets/wind/Windy.js";

// import { parseGIF } from 'gifuct-js';
// import { decompressFrames } from 'gifuct-js';

import cesiumweatherView from "./weatherComponents/cesiumweatherView.vue";
import jsonData from "./weatherComponents/weatherBase.json";
import allStationJson from "./cesiumComponents/allStationJson.json";
import fjLonLatJson from "./cesiumComponents/fjLonLat.json";

import { WindLayer } from "cesium-wind";

import output from "../assets/WechatIMG1693.jpg";
import rainoutput from "../assets/rainoutput.jpg";

import cloudJson from "/public/static/exportData/cloud/layer.json";
import rainJson from "/public/static/exportData/rain/layer.json";
import tempJson from "/public/static/exportData/tmp/layer.json";
import windJson from "/public/static/exportData/wind/layer.json";

import basicGeoJson from "../assets/geoJson/basic.json";
import windLineJson from "./cesiumComponents/windspeed.json";
import windGridData from "./cesiumComponents/windGridData.json";

import axios from "axios";

import ModelUnpack from "@/components/modelUnpack.vue";
import menuCom from "./menuCom.vue";
import { getTempData, getBaiduTempData, getWWTempData } from "@/api/index.js";

//风场展示图标
import fc from "@/assets/windimgs/fanSvg/feng.gif";
// import fc1 from "@/assets/windimgs/fanSvg/feng.mp4"
//火电展示图标
import hd from "@/assets/windimgs/fanSvg/huo.gif";
// import hd1 from "@/assets/windimgs/fanSvg/huo.mp4"
//光伏电站展示图标
import gf from "@/assets/windimgs/fanSvg/guang.gif";
// import gf1 from "@/assets/windimgs/fanSvg/guang.mp4"
//储能展示图标
import chu from "@/assets/windimgs/fanSvg/chu.gif";
// import chu1 from "@/assets/windimgs/fanSvg/chu.mp4"
//待机
import dj from "@/assets/windimgs/fanSvg/dj.svg";
//动图使用柱子和扇叶
import bwzhu from "@/assets/windimgs/fanSvg/bwzhu.svg";
import bwshan from "@/assets/windimgs/fanSvg/bwshan.png";

import windHome from "@/components/windHome/index.vue";
import windPro from "@/components/windProDetail/windProblem.vue";
import cesiumwindView from "./cesiumComponents/cesiumwindView.vue";

export default {
  name: "CesiumMap",

  components: {
    ModelUnpack,
    menuCom,
    cesiumweatherView,
    windHome,
    windPro,
    cesiumwindView,
  },

  data() {
    return {
      modelUnpackType: "fengji",
      checkMode: false, // 调试模式
      allyShow: true,
      viewer: null,
      windLayer: null, // 风场图
      windLayerTimmer: null, // 风场图计时器
      cloudImagesLayer: [], // 卫星云图
      cloudLayer: null, // 卫星云图
      cloudintervalId: null,
      rainImagesLayer: [], // 降雨图
      rainLayer: null, // 降雨图
      rainintervalId: null, // 降雨图
      tempImagesLayer: [], //温度图
      temperatureLayer: null, //温度图
      tempintervalId: null, //温度图
      basicMapId: "gaodeyingxiang", // 地球底图 ID
      basicMapList: [
        {
          id: "gaodeyingxiang",
          name: "高德影像地图",
          url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
          minimumLevel: 3,
          maximumLevel: 17,
          credit: "basicMap",
        },
        {
          id: "gaodeshiliang",
          name: "高德矢量地图",
          url: "https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
          minimumLevel: 3,
          maximumLevel: 17,
          credit: "basicMap",
        },
        {
          id: "carto",
          name: "Carto地图",
          url: "http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png",
          credit: "basicMap",
        },
      ],
      earthLayer: [],
      userClickLeft: 0,
      userClickTop: 0,
      tagMsg: null,
      systemInfoTimmer: null,
      showDevInfoBox: true,
      fps: "", // 设备帧率
      ms: "", // 设备响应时间
      jsHeapSize: "", // 内存占用
      gVendor: "",
      gRenderer: "",
      labelLayer: null, // 城市名称 label 集合
      loadDone: false, // 地球首次加载滚动到 reset 位置是否完成
      showtempImg: false,
      handlerAction: null,
      sidebarRightData: null,
      imageryProviderV: null,
      isWindVisible: true,
      minSpeed: 0,
      maxSpeed: 0,

      showcomModelDia: false,
      modelVal: null,
      menuComTStyB: false,
      modelUnpackType: "fengji",
      windDrawer: false,
      windDrawerTitle: "",
      windDrawerHeader: "",
      showBasicMsg: false,
      showVideoMsg: false,
      showProblemMsg: false,
      showModelMsg: false,
      showWindDetail: false,
      allStationentitys: [],
      allWindEntitys: [],
      showTypeViewer: true,
      stationValue: [],
    };
  },
  created() {
    this.getWeatherData();
  },
  mounted() {
    this.initEventListener();
    this.initCesium();
    if (this.showDevInfoBox) {
      this.initSystemInfo();
    }
    // this.getData();
    // this.test();
  },

  unmounted() {
    if (this.windLayer !== null) {
      this.windLayer.destroy();
      this.windLayer = null;
    }

    clearInterval(this.systemInfoTimmer);
    this.systemInfoTimmer = null;
  },

  methods: {
    changeType(value) {
      this.stationValue = value;
      this.allStationentitys.forEach(({ entity, handler }) => {
        this.viewer.entities.remove(entity); // 移除实体
        if (!handler.isDestroyed()) {
          handler.destroy(); // 销毁事件处理器（关键！）
        }
      });
      this.allStationentitys = [];
      let showStation = [];
      value.forEach((it) => {
        allStationJson.station.forEach((ic) => {
          if (it === ic.energytype) {
            showStation.push(ic);
          }
        });
      });
      this.showAllStation(this.viewer, showStation);
    },
    coverOnChange(val) {
      if (val.value === "风场") {
        this.switchWindLayer(val.check);
      } else if (val.value === "云层") {
        this.switchCloudLayer(val.check);
      } else if (val.value === "降雨") {
        this.switchRainLayer(val.check);
      } else if (val.value === "温度") {
        this.switchTemperatureLayerr(val.check);
      }
    },
    test() {
      axios
        // .get("http://localhost:3007/api/test", {
        .post("http://localhost:3007/weather/getWeatherWindData", {
          longitude: 106.169866,
          latitude: 38.46637,
          level: "surface",
          variable: "PRATE,PRES,SUNSD,VEG,VIS,VRATE,LCDC",
        })
        .then((res) => {
          console.log(11111, res.data);
        });
    },

    async getWeatherData() {
      let that = this;
      await that.weatherJsonChange(jsonData.data);
    },
    weatherJsonChange(datas) {
      let obj = {
        base: datas.base,
        weather: datas.weather,
        zhishu: datas.recommend_zhishu,
        pm25: datas.ps_pm25,
        position: datas.position,
        // fiftyDay: datas['15_day_forecast'],
        "15tq": datas["15_day_forecast"].info,
        "24tg": datas["24_hour_forecast"].info,
        "40tq": datas["long_day_forecast"].info,
        feature: datas.feature,
      };
      this.sidebarRightData = obj;
    },

    getData() {
      getWWTempData().then((res) => {
        console.log("res===>>>", res);
      });
    },

    // 初始化一些监听事件
    initEventListener() {
      const mapBox = document.querySelector(".mapBox");
      mapBox.addEventListener("click", (e) => {
        const rect = mapBox.getBoundingClientRect();
        this.userClickLeft = (e.clientX - rect.left).toFixed(0);
        this.userClickTop = (e.clientY - rect.top + 20).toFixed(0);
      });
    },

    // 初始化地球
    async initCesium() {
      // 需要从 https://cesium.com/ion/signup 获取
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwYTQwNDk3MC05YTZkLTQ2ZTEtODc0MS1lZTFkYjFlOTFmNmQiLCJpZCI6MTcyNDQ1LCJpYXQiOjE3NTQ4ODA4MzF9.KnhENYiHxNwTkhTWRA-lHqG59coLVT2FsIyOru2TV3E";

      // 修改 Cesium 默认地图视角为宁夏，狗东西没效果不知道为什么
      // Cesium.Camera.DEFAULT_VIEW_RACTANGLE = Cesium.Rectangle.fromDegrees(
      //   104.17,
      //   35.14,
      //   107.72,
      //   39.23
      // );

      //   const cesiumOptions = {
      //     geocoder: false, // 地址搜索控件
      //     homeButton: false, // 返回地图初始位置控件
      //     infoBox: false, // 地图默认的信息控件
      //     sceneModePicker: false, // 场景模式切换控件
      //     baseLayerPicker: false, // 底图切换控件
      //     navigationHelpButton: false, // 帮助控件
      //     animation: false, // 动画控制控件
      //     timeline: false, // 时间线控件
      //     fullscreenButton: false, // 全屏按钮控件
      //     // imageryProvider: false, // 是否显示 Cesium 默认地图的底图
      //     vrButton: false,
      //     selectionIndicator: false,
      //     shouldAnimate: true,
      //     // terrain: Cesium.Terrain.fromWorldTerrain(),
      //     // terrainProvider: new Cesium.CesiumTerrainProvider({
      //     //   url: "/static/layer.json", // 对应 public/terrain-data 目录
      //     //   requestVertexNormals: true, // 保留法线数据（光照效果）
      //     //   requestWaterMask: false, // 本地地形通常无水面效果（需自定义）
      //     // }),
      //   };

      //   const viewer = new Cesium.Viewer("cesiumContainer", cesiumOptions);

      const cesiumOptions = {
        // terrainProvider: Cesium.createWorldTerrain(),
        baseLayerPicker: false, //是否显示底图切换按钮
        animation: false, //是否显示动画控制按钮
        vrButton: false,
        geocoder: false, //是否显示地理编码按钮
        homeButton: false, //是否显示地图导航按钮
        infoBox: false,
        sceneModePicker: false, //是否显示场景模式切换按钮
        selectionIndicator: false,
        timeline: false, //是否显示时间轴
        fullscreenButton: false, //是否显示全屏按钮
        navigationHelpButton: false,
        shouldAnimate: true,
        imageryProvider: false, //控制默认底图的显示
        // terrain: Cesium.Terrain.fromWorldTerrain(),
      };

      const viewer = new Cesium.Viewer("cesiumContainer", cesiumOptions);

      // 隐藏 Cesium Logo
      viewer.cesiumWidget.creditContainer.style.display = "none";
      viewer.scene.globe.baseColor = Cesium.Color.BLACK;

      this.viewer = viewer;

      // this.setMapImageryProvider();
      this.initCesiumTerrain();
      this.initCesiumBaseMapImage();
    //   this.switchWindLayer();
      this.showAllStation(viewer, allStationJson.station);
      this.initGeoJsonData();
    },

    // 初始化地形
    async initCesiumTerrain() {
      const terrainProvider = await Cesium.CesiumTerrainProvider.fromUrl(
        // "http://localhost:3007/tiles/dixing",
        "./public/static/dixing",
        {
          requestWaterMask: true, // 如果需要水效果，设置为true
          requestVertexNormals: true, // 如果需要光照效果，设置为true
          requestMetadata: true, // 请求元数据
          // minimumLevel: 10,
          maximumLevel: 15,
        }
      );

      this.viewer.scene.verticalExaggeration = 14.0;
      this.viewer.scene.verticalExaggerationRelativeHeight = 2400.0;

      this.viewer.terrainProvider = terrainProvider;

      // const terrainProvider = new Cesium.CesiumTerrainProvider({
      //   url: "http://localhost:3007/tiles/dixing", // 地形数据所在目录的URL
      //   requestWaterMask: true, // 如果需要水效果，设置为true
      //   requestVertexNormals: true, // 如果需要光照效果，设置为true
      //   minimumLevel: 10,
      //   maximumLevel: 15,
      // });
      // this.viewer.terrainProvider = terrainProvider;
      // console.log(111, terrainProvider);

      // const imageryProvider = new Cesium.UrlTemplateImageryProvider({
      //   url: "http://localhost:3007/tiles/dixing/{z}/{x}/{y}",
      //   // url: "./public/static/dixing/{z}/{x}/{y}.terrain",
      //   credit: "地形数据",
      // });

      // this.viewer.imageryLayers.addImageryProvider(imageryProvider);

      // this.viewer.scene.globe.depthTestAgainstTerrain = true; //地形遮挡效果开关，打开后 地形会遮挡看不到的区域
      // this.viewer.scene.globe.enableLighting = true; //对大气和雾启用动态照明效
    },

    // 初始化底图
    async initCesiumBaseMapImage() {
      const imageryProvider = await new Cesium.UrlTemplateImageryProvider({
        url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
        // url: "http://localhost:3007/tiles/map/{z}/{x}/{y}",
        // url: "./public/static/ditu/{z}/{x}/{y}.png",
        credit: "影像地图",
      });
      imageryProvider.alpha = 0.55; // 透明度
      imageryProvider.brightness = 1; // 亮度
      imageryProvider.contrast = 1; // 对比度

      this.viewer.imageryLayers.addImageryProvider(imageryProvider);
    },

    // 初始化城市
    async initCityCesium() {
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwYTQwNDk3MC05YTZkLTQ2ZTEtODc0MS1lZTFkYjFlOTFmNmQiLCJpZCI6MTcyNDQ1LCJpYXQiOjE3NTQ4ODA4MzF9.KnhENYiHxNwTkhTWRA-lHqG59coLVT2FsIyOru2TV3E";

      const cesiumOptions = {
        geocoder: false, // 地址搜索控件
        homeButton: false, // 返回地图初始位置控件
        infoBox: false, // 地图默认的信息控件
        sceneModePicker: false, // 场景模式切换控件
        baseLayerPicker: false, // 底图切换控件
        navigationHelpButton: false, // 帮助控件
        animation: false, // 动画控制控件
        timeline: false, // 时间线控件
        fullscreenButton: false, // 全屏按钮控件
        // imageryProvider: false, // 是否显示 Cesium 默认地图的底图
        vrButton: false,
        selectionIndicator: false,
        shouldAnimate: true,
        terrain: Cesium.Terrain.fromWorldTerrain(),
        // terrainProvider: new Cesium.CesiumTerrainProvider({
        //   url: "/static/layer.json", // 对应 public/terrain-data 目录
        //   requestVertexNormals: true, // 保留法线数据（光照效果）
        //   requestWaterMask: false, // 本地地形通常无水面效果（需自定义）
        // }),
      };

      const viewer = new Cesium.Viewer("cesiumContainer", cesiumOptions);

      // 隐藏 Cesium Logo
      viewer.cesiumWidget.creditContainer.style.display = "none";

      this.viewer = viewer;

      // this.setMapImageryProvider();
      this.initGeoJsonData();
    },

    // 初始化Cesium内部鼠标事件
    initEventInputAction() {
      this.$nextTick(() => {
        const viewer = this.viewer;
        // 添加点击事件显示坐标
        viewer.screenSpaceEventHandler.setInputAction((movement) => {
          const ray = this.viewer.camera.getPickRay(movement.position);
          if (!ray) {
            this.tagMsg = null;
            console.log("无法获取射线");
            return;
          }

          const position = this.viewer.scene.globe.pick(ray, this.viewer.scene);
          if (!position) {
            this.tagMsg = null;
            console.log("未找到地球表面交点");
            return;
          }

          const cartographic = Cesium.Cartographic.fromCartesian(position);
          if (!cartographic) {
            this.tagMsg = null;
            console.log("坐标转换失败");
            return;
          }

          this.getClickCloudOpacity(cartographic);
          this.getLocationData(cartographic);
          return;

          const cartesian = viewer.camera.pickEllipsoid(
            movement.position,
            viewer.scene.globe.ellipsoid
          );
          if (cartesian) {
            const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
            const lon = Cesium.Math.toDegrees(cartographic.longitude).toFixed(
              5
            );
            const lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(5);

            viewer.entities.removeAll();
            viewer.entities.add({
              position: cartesian,
              point: {
                pixelSize: 10,
                color: Cesium.Color.RED,
              },
              label: {
                text: `经度: ${lon}°, 纬度: ${lat}°`,
                font: '16px "Microsoft YaHei"',
                fillColor: Cesium.Color.WHITE,
                outlineColor: Cesium.Color.BLACK,
                outlineWidth: 2,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                pixelOffset: new Cesium.Cartesian2(0, -30),
              },
            });
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        // 监听鼠标滚轮事件
        viewer.screenSpaceEventHandler.setInputAction((wheelment) => {
          this.tagMsg = null;
        }, Cesium.ScreenSpaceEventType.WHEEL);

        viewer.scene.camera.moveEnd.addEventListener(() => {
          //获取当前相机高度
          // const height = Math.ceil(earth.camera.positionCartographic.height);
        });

        // 监听鼠标移动事件
        // viewer.screenSpaceEventHandler.setInputAction((movement) => {
        //   this.getHoverCityLabel(movement);
        // }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      });
    },

    // 获取鼠标划过位置的城市名称 label
    getHoverCityLabel(movement) {
      const picked = this.viewer.scene.pick(movement.startPosition);
      const label = picked ? picked.primitive : null;

      if (label) {
        this.viewer.scene.canvas.style.cursor = "pointer";
      } else {
        this.viewer.scene.canvas.style.cursor = "default";
      }

      this.labelLayer._labels.forEach((ele) => {
        if (ele.id === label?.id) {
          label.fillColor = Cesium.Color.YELLOW;
          label.outlineColor = Cesium.Color.BLACK;
        } else {
          ele.fillColor = Cesium.Color.fromCssColorString("#000");
          ele.outlineColor = Cesium.Color.WHITE;
        }
      });
    },

    // 根据经纬度获取周围一定范围城市基础信息
    getLocationData({ latitude, longitude }) {
      const lat = Cesium.Math.toDegrees(latitude);
      const lon = Cesium.Math.toDegrees(longitude);
      axios
        .get(
          `/ventusky/ventusky_location.json.php?lat=${lat}&lon=${lon}&zoom=${this.getZoomLevel()}`
        )
        .then((res) => {
          console.log(111, res.data);
          // https://api.waqi.info/feed/geo:35.3286804492;108.9025100708/?token=904a1bc6edf77c428347f2fe54cf663bcffaec21
          // res.data.city
        });
    },

    // 获取 zoom 级别
    getZoomLevel() {
      let zoomLevel = 0;
      const tilesToRender = this.viewer.scene.globe._surface._tilesToRender;
      if (tilesToRender.length !== 0) {
        zoomLevel = tilesToRender[0].level;
      }
      return zoomLevel - 1;
    },

    // 初始化性能监控
    async initSystemInfo() {
      this.viewer.scene.debugShowFramesPerSecond = false;

      // 性能监控变量
      let lastFrameTime = performance.now();
      let frameCount = 0;
      let fps = 0;
      let frameTime = 0;

      // 获取帧率与响应时长
      this.viewer.scene.postRender.addEventListener(() => {
        const now = performance.now();
        const delta = now - lastFrameTime;

        frameCount++;

        // 每秒更新一次数据（避免更新太频繁）
        if (delta >= 1000) {
          fps = Math.round((frameCount * 1000) / delta);
          frameTime = delta / frameCount;

          // 更新显示
          this.fps = `${fps} FPS`;
          this.ms = `${frameTime.toFixed(1) + " ms"}`;

          // 重置计数器
          frameCount = 0;
          lastFrameTime = now;
        }
      });

      // 获取内存占用
      if (window.performance && performance.memory) {
        const jsHeapSize = performance.memory.usedJSHeapSize / 1048576;
        this.jsHeapSize = `${parseInt(jsHeapSize)} MB`;
        // const memory = performance.memory;
        // console.log("已分配堆内存:", memory.totalJSHeapSize / 1048576 + " MB");
        // console.log("已使用堆内存:", memory.usedJSHeapSize / 1048576 + " MB");
        // console.log("堆内存限制:", memory.jsHeapSizeLimit / 1048576 + " MB");
      }

      // 获取显卡信息
      const canvas = document.createElement("canvas");
      const gl = canvas.getContext("webgl");
      if (gl) {
        const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");
        if (debugInfo) {
          const gVendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
          const gRenderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);

          // console.log("GPU厂商:", gVendor);
          // console.log("GPU型号:", gRenderer);

          this.gVendor = gVendor;
          this.gRenderer = gRenderer.split(",")?.[1]
            ? gRenderer.split(",")?.[1]
            : "";
        }
      }
    },

    getClickCloudOpacity(cartographic) {
      try {
        const level = this.calculateTileLevel(this.viewer);
        const tilingScheme = new Cesium.WebMercatorTilingScheme();

        // 确保 tilingScheme 有 positionToTileXY 方法
        if (!tilingScheme.positionToTileXY) {
          console.error("tilingScheme没有positionToTileXY方法");
          return;
        }

        if (!this.cloudLayer) {
          this.tagMsg = null;
        } else {
          this.tagMsg = "";
        }
        const tileXY = tilingScheme.positionToTileXY(cartographic, level);

        this.checkMode &&
          console.log(`瓦片坐标: 级别=${level}, X=${tileXY.x}, Y=${tileXY.y}`);

        const clickTileUrl = this.replaceTemplate(
          "https://tile.openweathermap.org/map/clouds_new/{z}/{x}/{y}.png?appid=3b66d35579770393051599f8d518df4a",
          level,
          tileXY
        );

        this.checkMode && console.log(`用户点击位置瓦片url: ${clickTileUrl}`);

        // 存储当前瓦片信息
        const layer = this.viewer.imageryLayers.get(0);
        const provider = layer.imageryProvider;
        const currentTile = {
          x: tileXY.x,
          y: tileXY.y,
          level: level,
          rectangle: tilingScheme.tileXYToRectangle(tileXY.x, tileXY.y, level),
          size: {
            width: provider.tileWidth || 256,
            height: provider.tileHeight || 256,
          },
        };

        // 计算并显示在瓦片内的位置
        const clickPos = this.calculateTilePosition(cartographic, currentTile);

        if (this.cloudLayer) {
          this.getTileImageOpacity(
            clickTileUrl,
            clickPos.pixelX,
            clickPos.pixelY
          ).then((imgSource) => {
            const {
              rawAlpha, // 原始透明度值 (0-255)
              alphaPercentage, // 透明度百分比
              whiteScore, // 白色程度得分 (0-100)
            } = imgSource;
            this.checkMode && console.log(111, alphaPercentage);
            this.tagMsg = `${alphaPercentage * 2}%`;
          });
        }

        if (this.checkMode) {
          const tileRectangle = tilingScheme.tileXYToRectangle(
            tileXY.x,
            tileXY.y,
            level
          );
          this.highlightTile(viewer, tileRectangle);
        }
      } catch (error) {
        console.error("获取瓦片时出错:", error);
      }
    },

    // 计算瓦片级别的辅助函数
    calculateTileLevel(viewer) {
      // 方法1：根据相机高度估算
      const height = viewer.camera.positionCartographic.height;
      if (!height) return 12; // 默认值

      // 高度与级别的近似关系（根据实际需求调整）
      const level = Math.floor(20 - Math.log(height / 1000) / Math.log(2));
      return Math.max(0, Math.min(18, level)); // 限制在0-18级之间

      // 方法2：使用当前视图的细节层次
      // return viewer.scene.globe.maximumScreenSpaceError;
    },

    // 高亮显示瓦片的辅助函数
    highlightTile(viewer, rectangle) {
      // 移除之前的高亮
      viewer.entities.removeById("highlighted-tile");

      // 添加新的高亮
      viewer.entities.add({
        id: "highlighted-tile",
        rectangle: {
          coordinates: rectangle,
          material: Cesium.Color.RED.withAlpha(0.3),
          outline: true,
          outlineColor: Cesium.Color.RED,
          outlineWidth: 2,
        },
      });
    },

    // 计算在瓦片内的位置
    calculateTilePosition(cartographic, tile) {
      const rect = tile.rectangle;
      const size = tile.size;

      // 计算在瓦片内的归一化位置
      const lonNormalized =
        (cartographic.longitude - rect.west) / (rect.east - rect.west);
      const latNormalized =
        (cartographic.latitude - rect.south) / (rect.north - rect.south);

      // 转换为像素坐标（原点在左上角）
      const pixelX = Math.floor(lonNormalized * size.width);
      const pixelY = Math.floor((1 - latNormalized) * size.height); // 翻转Y轴

      this.checkMode && console.log(`left:${pixelX},top:${pixelY}`);
      return { pixelX, pixelY };
    },

    // canvas 获取地图瓦片颜色信息
    async getTileImageOpacity(imageUrl, left, top) {
      // 1. 创建临时图像加载网络图片
      const img = new Image();
      img.crossOrigin = "Anonymous"; // 解决跨域问题
      img.src = imageUrl;

      // 2. 图片加载完成后处理
      await new Promise((resolve) => (img.onload = resolve));

      // 3. 创建Canvas并绘制图像
      const canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0);

      // 4. 获取鼠标点击位置的像素数据
      const pixelData = ctx.getImageData(left, top, 1, 1).data;
      const [r, g, b, alpha] = pixelData;

      // 5. 计算白色程度（RGB接近255的程度）
      const whiteRatio = (r + g + b) / (3 * 255); // RGB平均值归一化
      const whiteScore = Math.round(whiteRatio * 100); // 映射到0-100

      // 6. 返回结果
      return {
        rawAlpha: alpha, // 原始透明度值 (0-255)
        alphaPercentage: Math.round((alpha / 255) * 100), // 透明度百分比
        whiteScore: whiteScore, // 白色程度得分 (0-100)
      };
    },

    // 替换底图 xyz 值为鼠标点击位置的值并返回
    replaceTemplate(str, level, tileXY) {
      return str.replace(/\{([xyz])\}/g, (match, key) => {
        switch (key) {
          case "x":
            return tileXY.x;
          case "y":
            return tileXY.y;
          case "z":
            return level;
          default:
            return match; // 未匹配时返回原内容（理论上不会执行）
        }
      });
    },

    // 设置地球底图
    setMapImageryProvider(val) {
      if (this.imageryProvider) {
        this.viewer.imageryLayers.remove(this.imageryProvider);
        this.imageryProvider = null;
      }
      let imageryProvider = null;
      if (val) {
        imageryProvider = val;
      } else {
        imageryProvider = this.basicMapList.find((ele) => {
          return ele.id === this.basicMapId;
        });
      }

      this.imageryProvider = new Cesium.UrlTemplateImageryProvider(
        imageryProvider
      );

      // 添加底图
      this.viewer.imageryLayers.addImageryProvider(this.imageryProvider);
    },

    // 初始化 geoJson 数据
    async initGeoJsonData() {
      // 创建GeoJSON数据源
      await new Cesium.GeoJsonDataSource.load(basicGeoJson, {
        stroke: Cesium.Color.GRAY, // 边界线颜色
        fill: Cesium.Color.BLACK.withAlpha(0), // 填充颜色
        strokeWidth: 1, // 边界线宽度
        markerSymbol: "?", // 点要素的符号
        clampToGround: true, // 贴地
        height: 0,
      }).then((dataSource) => {
        // 添加到视图
        this.viewer.dataSources.add(dataSource);
        var entities = dataSource.entities.values;
        for (let i = 0; i < entities.length; i++) {
          let entity = entities[i];

          entity.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
          //单独设置线条样式
          var positions = entity.polygon.hierarchy._value.positions;

          entity.polyline = {
            positions: positions,
            width: 2,
            outline: false,
            clampToGround: true,
          };
        }

        // 添加中文标签图层
        const labelLayer = new Cesium.LabelCollection();
        this.viewer.scene.primitives.add(labelLayer);
        const cities = [];
        basicGeoJson?.features?.forEach((ele) => {
          if (Array.isArray(ele.properties.centroid)) {
            const name = ele.properties.name;
            const lon = ele.properties.centroid[0];
            const lat = ele.properties.centroid[1];
            cities.push({ name, lon, lat });
          }
        });

        cities.forEach((city, index) => {
          labelLayer.add({
            id: index,
            name: "cityLabel",
            position: Cesium.Cartesian3.fromDegrees(city.lon, city.lat, 10),
            text: city.name,
            font: 'bold 14px "Microsoft YaHei", sans-serif',
            fillColor: Cesium.Color.fromCssColorString("#000"),
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 2,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            pixelOffset: new Cesium.Cartesian2(0, 0), // 设置为0
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 水平居中
            verticalOrigin: Cesium.VerticalOrigin.CENTER, // 垂直居中
          });
        });

        this.labelLayer = labelLayer;
        // this.csceneElliposid(this.viewer, null)
        // this.resetViewport1();
      });
    },

    initresetViewport() {
      this.resetViewport1();
    },
    // 城市视角重置视角
    resetViewport(height = 0, callback) {
      // 设置初始视图为宁夏
      const that = this;
      this.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          //宁夏银川
          //   106.169866,
          //   38.46637,
          //   height || 10000

          //北京
          116.391586,
          39.898832,
          height || 500
          // 106.2,
          // 38.467,
          // 15000.0

          // 113.3191,
          // 23.109,
          // 1000

          //上海
          // 121.47,
          // 31.23,
          // 1000
        ),

        // orientation: {
        //   heading: 0, //北京天安门角度 0 上海角度 1
        //   pitch: -0.2,
        //   roll: 0,
        // },
        duration: 3,
        // orientation: {
        //   heading: Cesium.Math.toRadians(0),
        //   pitch: Cesium.Math.toRadians(-90),
        //   roll: 0.0,
        // },
        // duration: 1.0,
        complete() {
          // 为什么要加这个？因为破库地球没完全加载完成时如果执行了监听鼠标滑动事件会光速报错滑跪
          if (!that.loadDone) {
            that.initEventInputAction();
            that.loadDone = true;
          }
          callback && callback();
        },
      });
    },
    resetViewport1(height = 0) {
      // 设置初始视图为宁夏
      const that = this;
      this.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          106.169866,
          38.46637,
          height
        ),
        // orientation: {
        //   heading: 1,
        //   pitch: -0.2,
        //   roll: 0,
        // },
        // duration: 3,
        orientation: {
          heading: Cesium.Math.toRadians(0),
          pitch: Cesium.Math.toRadians(-90),
          roll: 0.0,
        },
        duration: 1.0,
        complete() {
          // 为什么要加这个？因为破库地球没完全加载完成时如果执行了监听鼠标滑动事件会光速报错滑跪
          if (!that.loadDone) {
            that.initEventInputAction();
            that.loadDone = true;
          }
        },
      });
    },
    resetCloudTempRain(height = 0) {
      // 设置初始视图为宁夏
      this.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          106.169866,
          38.46637,
          10000000
        ),
        orientation: {
          heading: Cesium.Math.toRadians(0),
          pitch: Cesium.Math.toRadians(-90),
          roll: 0.0,
        },
        duration: 3.0,
      });
    },
    // 添加风场图
    async showWindLayer() {
      if (!this.windLayer) {
        // this.resetViewport(6000000);
        // 色值面板
        const CONTROL_COLOR = {
          uv: [
            { color: "#f4f4f4", min: 0, max: 5, label: "0m/s ~ 5m/s" },
            { color: "#fff465", min: 5, max: 10, label: "5m/s ~ 10m/s" },
            { color: "#c5171e", min: 10, max: 15, label: "10m/s ~ 15m/s" },
            { color: "#930f00", min: 15, max: 20, label: "15m/s ~ 20m/s" },
          ],
          shr: [
            { color: "#00BFFF", min: 0, max: 0.034, label: "0 ~ 0.034-轻度" },
            {
              color: "#1E90FF",
              min: 0.034,
              max: 0.068,
              label: "0.034 ~ 0.068-中度",
            },
          ],
          edr: [
            { color: "#87CEFA", min: 0, max: 0.22, label: "0 ~ 0.22-轻度" },
            {
              color: "#4169E1",
              min: 0.22,
              max: 0.35,
              label: "0.22 ~ 0.35-中度",
            },
            {
              color: "#0000CD",
              min: 0.35,
              max: 0.5,
              label: "0.35 ~ 0.5-重度",
            },
          ],
        };

        this.windLayer = await createWind(
          this.viewer,
          this.trJsonData(windGridData),
          CONTROL_COLOR
        );
        // this.windLayer = new WindLayer(windGridData, {
        //   particleSize: 2.0,
        //   particleOpacity: 0.6,
        //   particleSpeed: 0.01,
        //   maxVelocity: 25,// 风速最大值（用于颜色映射和速度缩放）
        //   minVelocity: 0, // 风速最小值阈值（低于此值不显示粒子）
        //   colorScale: [
        //     "rgb(36,104, 180)",
        //     "rgb(60,157, 194)",
        //     "rgb(128,205,193)",
        //     "rgb(151,218,168)",
        //     "rgb(198,231,181)",
        //     "rgb(238,247,217)",
        //     "rgb(255,238,159)",
        //     "rgb(252,217,125)",
        //     "rgb(255,182,100)",
        //     "rgb(252,150,75)",
        //     "rgb(250,112,52)",
        //     "rgb(245,64,32)",
        //     "rgb(237,45,28)",
        //     "rgb(220,24,32)",
        //     "rgb(180,0,35)",
        //   ],// 颜色强度缩放
        //   frameRate: 15,
        //   fadeOpacity: 0.995,
        //   particleAge: 150,
        //   maxAge: 60,
        //   globalAlpha: 0.8,
        //   velocityScale: 1 / 30,// 粒子移动速度缩放因子（控制动画快慢）
        //   paths: 250,
        //   lineWidth: 2,
        // });
        // this.windLayer.addTo(this.viewer);
      }
    },

    trJsonData(jsonData) {
      function arrayMin(arr) {
        let min = Infinity;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] < min) min = arr[i];
        }
        return min;
      }

      function arrayMax(arr) {
        let max = -Infinity;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] > max) max = arr[i];
        }
        return max;
      }
      const uData = jsonData.find((ele) => {
        return ele.header.parameterNumberName === "U-component_of_wind";
      });
      const uMin = arrayMin(uData.data);
      const uMax = arrayMax(uData.data);

      const vData = jsonData.find((ele) => {
        return ele.header.parameterNumberName === "V-component_of_wind";
      });
      const vMin = arrayMin(vData.data);
      const vMax = arrayMax(vData.data);

      const bounds = {
        west: uData.header.lo1,
        south: uData.header.la2,
        east: uData.header.lo2,
        north: uData.header.la1,
      };

      return {
        u: {
          array: uData.data,
          min: uMin,
          max: uMax,
        },
        v: {
          array: vData.data,
          min: vMin,
          max: vMax,
        },
        width: uData.header.nx,
        height: uData.header.ny,
        bounds,
      };
    },

    // 将风向角度数据转换为矢量坐标
    windToVector(speed, direction) {
      // 转换为弧度（气象角度：0°=北风，90°=东风）
      const rad = Cesium.Math.toRadians(direction);
      // 计算UV分量（U: 东西方向，V: 南北方向）
      return {
        u: -speed * Math.sin(rad), // 东正西负
        v: -speed * Math.cos(rad), // 北正南负
      };
    },

    // 获取当前地图瓦片级别(暂时没用到怀疑有BUG)
    getTileLevel() {
      let tiles = new Set();
      let tilesToRender = this.viewer.scene.globe._surface._tilesToRender;
      if (Cesium.defined(tilesToRender)) {
        for (let i = 0; i < tilesToRender.length; i++) {
          tiles.add(tilesToRender[i].level);
        }
        return [...tiles].sort((a, b) => {
          return b - a;
        })[0];
      }
    },
    async showeveryTypeImagesLayer(imageUrls, intervalId, ImagesLayers) {
      // 存储所有图片图层的数组
      let imageLayers = [];
      // 当前显示的图片索引
      let currentImageIndex = -1; // 初始为-1，表示没有图片显示

      // 创建所有图片图层并添加到Viewer，初始时全部隐藏
      await imageUrls.forEach((url) => {
        const provider = new Cesium.SingleTileImageryProvider({
          url: url,
          // url: URL.createObjectURL(url),
          rectangle: Cesium.Rectangle.fromDegrees(-180.0, -90.0, 180.0, 90.0), // 全球覆盖
          tileWidth: 1440, // 根据你的图片实际宽度修改
          tileHeight: 721,
          // 如果你的图片只覆盖特定区域，请修改rectangle参数
        });
        const Layer = this.viewer.imageryLayers.addImageryProvider(provider);
        Layer.alpha = 0.8; // 透明度
        Layer.brightness = 1; // 亮度
        Layer.contrast = 1; // 对比度
        Layer.show = false; // 初始隐藏
        imageLayers.push(Layer);
        ImagesLayers.push(Layer);
      });
      function showNextImage() {
        // 隐藏当前图片
        if (currentImageIndex >= 0 && currentImageIndex < imageLayers.length) {
          imageLayers[currentImageIndex].show = false;
        }

        // 计算下一张图片的索引
        currentImageIndex = (currentImageIndex + 1) % imageLayers.length;

        // 显示下一张图片
        imageLayers[currentImageIndex].show = true;
        // imageLayers[currentImageIndex + 1].show = true;
        console.log("当前显示图片: " + imageUrls[currentImageIndex]);
      }

      // 设置切换间隔（毫秒），例如每5秒切换一次
      const intervalMs = 5000;
      intervalId = setInterval(showNextImage, intervalMs);

      // 初始显示第一张图片
      showNextImage();
    },

    // 显示云图
    showCloudLayer() {
      const imageUrls = [];
      cloudJson.forEach((it) => {
        imageUrls.push("/public/static" + it.path);
      });
      this.showeveryTypeImagesLayer(
        imageUrls,
        this.cloudintervalId,
        this.cloudImagesLayer
      );
      this.resetCloudTempRain();
    },
    //显示降雨图
    showRainLayer() {
      const imageUrls = [];
      rainJson.forEach((it) => {
        imageUrls.push("/public/static" + it.path);
      });
      this.showeveryTypeImagesLayer(
        imageUrls,
        this.rainintervalId,
        this.rainImagesLayer
      );
      this.csceneElliposid(this.viewer, "rain");
      this.resetCloudTempRain();
    },
    //显示温度图
    showTemperatureLayer() {
      const imageUrls = [];
      tempJson.forEach((it) => {
        imageUrls.push("/public/static" + it.path);
      });
      this.showeveryTypeImagesLayer(
        imageUrls,
        this.tempintervalId,
        this.tempImagesLayer
      );
      this.csceneElliposid(this.viewer, "temp");
      this.resetCloudTempRain();
    },
    // 提供控制函数以便在需要时停止循环
    stopCycling(intervalId) {
      if (intervalId) {
        clearInterval(intervalId);
        intervalId = null;
        console.log("循环已停止");
      }
    },

    // 移除风场图
    removeWindLayer() {
      if (this.windLayer) {
        this.windLayer.destroy();
        this.windLayer = null;
      }
    },

    // 移除卫星云图
    removeCloudLayer() {
      if (this.cloudLayer) {
        this.tagMsg = null;
        this.viewer.imageryLayers.remove(this.cloudLayer);
        this.cloudLayer = null;
      }
      if (this.cloudImagesLayer.length > 0) {
        this.cloudImagesLayer.forEach((it) => {
          this.viewer.imageryLayers.remove(it);
        });
        this.cloudImagesLayer = [];
      }

      if (this.imageryProviderV) {
        this.viewer.imageryLayers.remove(this.imageryProviderV);
        this.imageryProviderV = null;
      }
    },
    // 移除降雨图
    removeRainLayer() {
      if (this.rainLayer) {
        this.tagMsg = null;
        this.viewer.imageryLayers.remove(this.rainLayer);
        this.rainLayer = null;
        this.setMapImageryProvider();
        this.handlerAction.removeInputAction(
          Cesium.ScreenSpaceEventType.LEFT_CLICK
        );
      }
      if (this.rainImagesLayer.length > 0) {
        this.rainImagesLayer.forEach((it) => {
          this.viewer.imageryLayers.remove(it);
        });
        this.rainImagesLayer = [];
      }

      if (this.imageryProviderV) {
        this.viewer.imageryLayers.remove(this.imageryProviderV);
        this.imageryProviderV = null;
      }
    },
    // 移除温度图
    removeTemperatureLayer() {
      if (this.temperatureLayer) {
        this.tagMsg = null;
        this.viewer.imageryLayers.remove(this.temperatureLayer);
        this.temperatureLayer = null;
        this.setMapImageryProvider();
        this.handlerAction.removeInputAction(
          Cesium.ScreenSpaceEventType.LEFT_CLICK
        );
      }
      if (this.tempImagesLayer.length > 0) {
        this.tempImagesLayer.forEach((it) => {
          this.viewer.imageryLayers.remove(it);
        });
        this.tempImagesLayer = [];
      }
      if (this.imageryProviderV) {
        this.viewer.imageryLayers.remove(this.imageryProviderV);
        this.imageryProviderV = null;
      }
    },

    //取消所有图层加载
    cancleAllLayer() {
      if (this.windLayer) {
        this.removeWindLayer();
      }
      if (this.rainLayer || this.rainImagesLayer.length > 0) {
        this.removeRainLayer();
        this.stopCycling(this.rainintervalId);
      }
      if (this.cloudLayer || this.cloudImagesLayer.length > 0) {
        this.removeCloudLayer();
        this.stopCycling(this.cloudintervalId);
      }
      if (this.temperatureLayer || this.tempImagesLayer.length > 0) {
        this.removeTemperatureLayer();
        this.stopCycling(this.tempintervalId);
      }
    },

    // 切换风场图显隐
    switchWindLayer() {
      this.showtempImg = false;
      this.viewer.scene.screenSpaceCameraController.enableZoom = true;
      if (this.rainLayer || this.rainImagesLayer.length > 0) {
        this.removeRainLayer();
        this.stopCycling(this.rainintervalId);
      }
      if (this.cloudLayer || this.cloudImagesLayer.length > 0) {
        this.removeCloudLayer();
        this.stopCycling(this.cloudintervalId);
      }
      if (this.temperatureLayer || this.tempImagesLayer.length > 0) {
        this.removeTemperatureLayer();
        this.stopCycling(this.tempintervalId);
      }
      if (this.windLayer) {
        this.removeWindLayer();
      } else {
        this.showWindLayer();
      }
    },

    // 切换卫星云图显隐
    switchCloudLayer(val) {
      this.showtempImg = false;
      if (this.windLayer) {
        this.removeWindLayer();
      }
      if (this.rainLayer || this.rainImagesLayer.length > 0) {
        this.removeRainLayer();
        this.stopCycling(this.rainintervalId);
      }
      if (this.temperatureLayer || this.tempImagesLayer.length > 0) {
        this.removeTemperatureLayer();
        this.stopCycling(this.tempintervalId);
      }
      if (!val || this.cloudLayer || this.cloudImagesLayer.length > 0) {
        this.removeCloudLayer();
        this.stopCycling(this.cloudintervalId);
      } else {
        this.showCloudLayer();
      }
    },
    // 切换降雨图显隐
    switchRainLayer() {
      this.showtempImg = false;
      this.viewer.scene.screenSpaceCameraController.enableZoom = true;
      if (this.windLayer) {
        this.removeWindLayer();
      }
      if (this.cloudLayer || this.cloudImagesLayer.length > 0) {
        this.removeCloudLayer();
        this.stopCycling(this.cloudintervalId);
      }
      if (this.temperatureLayer || this.tempImagesLayer.length > 0) {
        this.removeTemperatureLayer();
        this.stopCycling(this.tempintervalId);
      }
      if (this.rainLayer || this.rainImagesLayer.length > 0) {
        this.removeRainLayer();
        this.stopCycling(this.rainintervalId);
      } else {
        this.showRainLayer();
      }
    },

    switchTemperatureLayerr(val) {
      this.showtempImg = val;
      this.viewer.scene.screenSpaceCameraController.enableZoom = true;
      if (this.windLayer) {
        this.removeWindLayer();
      }
      if (this.cloudLayer || this.cloudImagesLayer.length > 0) {
        this.removeCloudLayer();
        this.stopCycling(this.cloudintervalId);
      }
      if (this.rainLayer || this.rainImagesLayer.length > 0) {
        this.removeRainLayer();
        this.stopCycling(this.rainintervalId);
      }
      if (this.temperatureLayer || this.tempImagesLayer.length > 0) {
        this.removeTemperatureLayer();
        this.stopCycling(this.tempintervalId);
      } else {
        this.showTemperatureLayer();
      }
    },
    switchCity() {
      this.$router.push({
        path: "/satellitecloudchart",
      });
    },
    switchTopographicMap() {
      this.viewer.scene.screenSpaceCameraController.enableZoom = true;
      if (this.windLayer) {
        this.removeWindLayer();
      }
      if (this.cloudLayer || this.cloudImagesLayer.length > 0) {
        this.removeCloudLayer();
        this.stopCycling(this.cloudintervalId);
      }
      if (this.rainLayer || this.rainImagesLayer.length > 0) {
        this.removeRainLayer();
        this.stopCycling(this.rainintervalId);
      }
      if (this.temperatureLayer || this.tempImagesLayer.length > 0) {
        this.removeTemperatureLayer();
        this.stopCycling(this.tempintervalId);
      }
      this.$router.push({
        path: "/topographicMap",
      });
    },
    csceneElliposid(viewer, type) {
      let that = this;
      // 获取 scene 和 ellipsoid
      var scene = viewer.scene;
      var labels = viewer.scene.primitives.add(new Cesium.LabelCollection());

      // 创建 ScreenSpaceEventHandler
      var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);

      // 监听左键点击事件
      handler.setInputAction(async (click) => {
        // 获取点击位置的笛卡尔坐标
        var position = click.position;
        if (!position) return;

        // 使用 globe.pick 获取包含地形高度的坐标
        var ray = viewer.camera.getPickRay(position);
        var cartesian = viewer.scene.globe.pick(ray, viewer.scene);

        if (cartesian) {
          // 转换为地理坐标
          var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
          var longitude = Cesium.Math.toDegrees(cartographic.longitude);
          var latitude = Cesium.Math.toDegrees(cartographic.latitude);
          var height = cartographic.height;

          // 显示 loading
          that.showLoading();

          let params = {
            lat: latitude,
            lon: longitude,
            appid: "3b66d35579770393051599f8d518df4a",
          };
          let res = await getTempData(params);

          // 取消显示 loading
          that.hideLoading();

          // 格式化坐标
          var text = `经度: ${longitude.toFixed(6)}°\n纬度: ${latitude.toFixed(
            6
          )}°\n城市: ${res.name}\n降雨量: ${
            res.rain ? res.rain["1h"] + "mm/h" : "无降雨"
          }`;
          var text2 = `经度: ${longitude.toFixed(6)}°\n纬度: ${latitude.toFixed(
            6
          )}°\n城市: ${res.name}\n温度: ${Math.ceil(res.main.temp - 273.15)}℃`;
          // 创建一个标签
          var label = labels.add({
            position: cartesian,
            text: type === "rain" ? text : text2,
            font: "14px monospace",
            fillColor: Cesium.Color.fromCssColorString("#1d70df"),
            // style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            // outlineColor: Cesium.Color.BLACK,
            outlineWidth: 2,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // 标签在点的上方
            pixelOffset: new Cesium.Cartesian2(0, -20), // 向上偏移一点
            disableDepthTest: true, // 让标签始终可见（即使在地球背面）
            scale: 0.8,
          });

          // 5秒后移除标签
          setTimeout(function () {
            labels.remove(label);
          }, 5000);

          console.log(
            `点击坐标: ${longitude.toFixed(6)}, ${latitude.toFixed(
              6
            )}, ${height.toFixed(2)}m`
          );
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      this.handlerAction = handler;
    },
    showLoading() {
      var loadingEl = document.getElementById("loading");
      loadingEl.style.display = "block";
    },

    hideLoading() {
      var loadingEl = document.getElementById("loading");
      loadingEl.style.display = "none";
    },

    // 展示所有风场
    showAllStation(viewer, station) {
        station.forEach((e, index) => {
            if (e.energytype === "Wind") {
            this.showStationFn(viewer, e, index, fc);
            } else if (e.energytype === "Fire") {
            this.showStationFn(viewer, e, index, hd);
            } else if (e.energytype === "Storage") {
            this.showStationFn(viewer, e, index, chu);
            } else {
            this.showStationFn(viewer, e, index, gf);
            }
        });
        this.resetViewport(6000000);
    },
    // 根据状态展示不同颜色风机贴图
    async showStationFn(viewer, e, index, images) {
      // // 获取GIF数据
      // const response = await fetch(images);
      // const buffer = await response.arrayBuffer();
      // // 解析GIF
      // const gif = parseGIF(buffer);
      // const frames = decompressFrames(gif, true);

      // // 创建一个离屏Canvas来绘制每一帧
      // const canvas = document.createElement('canvas');
      // const ctx = canvas.getContext('2d');
      // canvas.width = gif.lsd.width;
      // canvas.height = gif.lsd.height;

      const position = Cesium.Cartesian3.fromDegrees(e.longitude, e.latitude);
      const entity = viewer.entities.add({
        id: index,
        position, // 模型位置
        billboard: {
          image: images, // 也可以是 SVG 路径，如 'icon.svg'
          // image: new Cesium.ConstantProperty(images),
          // image: canvas.toDataURL('image/png'),
          scale: 0.08,
          // width: 256,
          // height: 256,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          // 模型贴地
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        },
        // name: 'video_entity',
        label: {
          text: e.plantname,
          font: "14px sans-serif",
          fillColor: Cesium.Color.fromBytes(255, 255, 255),
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        },
      });

      // let currentFrameIndex = 0;

      // // 定义动画函数
      // const animate = () => {
      //     const frame = frames[currentFrameIndex];
      //     // 清空Canvas
      //     ctx.clearRect(0, 0, canvas.width, canvas.height);

      //     // 绘制当前帧
      //     const imageData = new ImageData(frame.patch, frame.dims.width, frame.dims.height);
      //     ctx.putImageData(imageData, frame.dims.left, frame.dims.top);

      //     // 更新Billboard的图像
      //     entity.billboard.image = canvas.toDataURL('image/png');

      //     // 计算下一帧的时间（使用GIF本身的延迟时间）
      //     currentFrameIndex = (currentFrameIndex + 1) % frames.length;
      //     const delay = 200; // 默认100ms
      //     setTimeout(animate, delay);
      // };

      // // 开始动画
      // animate();

      let that = this;
      const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      handler.setInputAction(function (movement) {
        var position = movement.position;
        var pickedObject = viewer.scene.pick(position);
        if (pickedObject && pickedObject.id.id === index) {
          console.log("你点击了标签或模型！", entity);
          console.log("选中风场或新能源场", e.plantname);

          that.showRightClickPopup(position, e, "station", viewer);
        }
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      that.allStationentitys.push({ entity, handler });
    },
    // 展示所选风场的风机
    showWindFromStation(viewer) {
      fjLonLatJson.data.forEach((e, index) => {
        if (e.status) {
          if (e.status === 1) {
            this.showStatuswind(viewer, e, dj);
          }
        } else {
          this.showAnimatewind(viewer, e);
        }
      });
      this.resetWindViewport();
    },
    // 根据状态展示不同颜色风机贴图
    showStatuswind(viewer, e, type, index) {
      this.addSvg(
        viewer,
        type,
        e.longitude,
        e.latitude,
        e,
        Math.random().toFixed(4) * 10000
      );
    },
    // 风机柱与扇叶分开展示转动效果贴图
    showAnimatewind(viewer, e, index) {
      this.addSvgs(
        viewer,
        bwshan,
        e.longitude,
        e.latitude,
        e,
        Math.random().toFixed(3) * 1000
      );
      this.addSvg(
        viewer,
        bwzhu,
        e.longitude,
        e.latitude,
        e,
        Math.random().toFixed(3) * 2000
      );
    },
    //添加svg或png贴图
    addSvg(viewer, uri, lon, lat, val, index) {
      let that = this;
      let ids = that.generateUniqueId(val.id);
      const position = Cesium.Cartesian3.fromDegrees(lon, lat);
      const entity = viewer.entities.add({
        id: ids,
        position, // 模型位置
        billboard: {
          image: uri, // 也可以是 SVG 路径，如 'icon.svg'
          scale: 0.5,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          // 模型贴地
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        },
        label: {
          text: val.name ? val.name : val.plantname,
          font: "14px sans-serif",
          fillColor: Cesium.Color.fromBytes(255, 255, 255),
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        },
      });
      // 创建事件处理器
      const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      handler.setInputAction(function (movement) {
        var position = movement.position;
        var pickedObject = viewer.scene.pick(position);
        if (pickedObject && pickedObject.id.id === ids) {
          console.log("你点击了标签或模型！", entity);
          console.log("标签或模型数据！", val);
          that.modelVal = val;
          // 找到实体，显示包含实体信息的弹框
          that.showRightClickPopup(position, val, "wind");
          return;
        }
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      this.allWindEntitys.push({ entity, handler });
    },
    //添加svg或png贴图
    addSvgs(viewer, uri, lon, lat, val, index) {
      let that = this;
      let ids = that.generateUniqueId(val.id);
      const position = Cesium.Cartesian3.fromDegrees(lon, lat);
      const entity = viewer.entities.add({
        id: ids,
        position, // 模型位置
        billboard: {
          image: uri, // 也可以是 SVG 路径，如 'icon.svg'
          scale: 0.5,
          pixelOffset: new Cesium.Cartesian2(0, -15),
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          // 模型贴地
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          // 核心：使用 CallbackProperty 实现旋转动画
          rotation: new Cesium.CallbackProperty(function (time) {
            // 每 3 秒转一圈（可调速度）
            const seconds = time.secondsOfDay;
            const angle = Cesium.Math.toRadians(((seconds % 3) * 360) / 3); // 每3秒一圈
            return angle;
          }, false),
          // 确保绕中心旋转
          rotationAlignment: Cesium.HeightReference.CENTER,
          alignedAxis: Cesium.Cartesian3.UNIT_Z,
        },
      });
      // 创建事件处理器
      const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      handler.setInputAction(function (movement) {
        var position = movement.position;
        var pickedObject = viewer.scene.pick(position);
        if (pickedObject && pickedObject.id.id === ids) {
          console.log("你点击了标签或模型！", entity);
          console.log("标签或模型数据！", val);
          that.modelVal = val;
          // 找到实体，显示包含实体信息的弹框
          that.showRightClickPopup(position, val, "wind");
          return;
        }
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      this.allWindEntitys.push({ entity, handler });
    },
    generateUniqueId(prefix = "id") {
      let idCounter = 0;
      return `${prefix}-${Date.now()}-${Math.random()
        .toString(36)
        .substr(2, 9)}-${idCounter++}`;
    },
    // 右键展示元素
    showRightClickPopup(screenPosition, val, type, viewer) {
      // 创建或获取弹框元素
      var popup = document.getElementById("rightClickPopup");
      if (!popup) {
        popup = document.createElement("div");
        popup.id = "rightClickPopup";
        popup.style.position = "absolute";
        // popup.style.backgroundColor = 'white';
        popup.style.border = "1px solid rgba(255, 255, 255, 0.2)";
        popup.style.borderRadius = "4px";
        popup.style.padding = "10px";
        popup.style.boxShadow = "0 2px 10px rgba(0,0,0,0.2)";
        popup.style.backdropFilter = `blur(10px)`;
        popup.style.zIndex = "1000";
        popup.style.pointerEvents = "auto"; // 确保弹框可交互
        // 添加一个最小宽度，避免内容过短
        popup.style.minWidth = "100px";
        // 可选：添加箭头指向点击点
        // 这需要更复杂的 CSS 或额外的 DOM 元素
        document.body.appendChild(popup);
      }
      // <span class="popup-menu-item" data-message-type="model" style="cursor:pointer">模型解构</span>
      let content = "";
      if (type === "station") {
        content = `
                <div style="display: flex;gap: 10px;flex-direction: column;text-align: center;color: #fff">
                    <span class="popup-menu-item" data-message-type="windbasic2d" style="cursor:pointer">风机详情(2D)</span>
                </div>
            `;
      } else {
        content = `
                <div style="display: flex;gap: 10px;flex-direction: column;text-align: center;color: #fff">
                    <span class="popup-menu-item" data-message-type="basic" style="cursor:pointer">基本信息</span>
                    <span class="popup-menu-item" data-message-type="video" style="cursor:pointer">视频监控</span>
                    <span class="popup-menu-item" data-message-type="problem" style="cursor:pointer">故障详情</span>
                </div>
            `;
      }

      // 设置弹框内容
      popup.innerHTML = content;

      // --- 关键修正：准确计算弹框位置 ---

      // 1. 获取 Cesium 画布 (Canvas) 相对于视口 (viewport) 的位置
      var canvas = this.viewer.scene.canvas;
      var canvasRect = canvas.getBoundingClientRect();
      // console.log('Canvas Rect:', canvasRect); // 调试用

      // 2. 计算弹框左上角在页面中的绝对 X 坐标
      //    screenPosition.x 是相对于画布左上角的 X 偏移
      //    canvasRect.left 是画布左上角相对于浏览器视口左上角的 X 偏移
      //    window.pageXOffset 是页面水平滚动的距离
      var popupLeft = canvasRect.left + screenPosition.x + window.pageXOffset;

      // 3. 计算弹框左上角在页面中的绝对 Y 坐标
      var popupTop = canvasRect.top + screenPosition.y + window.pageYOffset;

      // --- 可选：添加偏移量，避免完全覆盖鼠标指针 ---
      // 例如，向下和向右偏移 10px
      var offsetX = 10;
      var offsetY = 10;
      popupLeft += offsetX;
      popupTop += offsetY;

      // --- 可选：边界检查，防止弹框超出屏幕 ---
      var popupWidth = popup.offsetWidth || 150; // 确保有宽度
      var popupHeight = popup.offsetHeight || 50; // 确保有高度
      var windowWidth = window.innerWidth;
      var windowHeight = window.innerHeight;

      // 如果弹框右边会超出窗口，则左移
      if (popupLeft + popupWidth > windowWidth) {
        popupLeft = windowWidth - popupWidth - 10; // 靠右留 10px 边距
      }
      // 如果弹框底边会超出窗口，则上移
      if (popupTop + popupHeight > windowHeight) {
        popupTop = windowHeight - popupHeight - 10; // 靠下留 10px 边距
      }
      // 如果左边超出 (不太可能，但安全起见)
      if (popupLeft < 0) popupLeft = 10;
      // 如果顶边超出
      if (popupTop < 0) popupTop = 10;

      // --- 设置最终位置 ---
      popup.style.left = popupLeft + "px";
      popup.style.top = popupTop + "px";

      // console.log('Popup Position:', { left: popupLeft, top: popupTop }); // 调试用

      // 显示弹框
      popup.style.display = "block";

      // --- 隐藏弹框的逻辑 (保持不变) ---
      function hidePopup(event) {
        // 检查点击是否发生在弹框内部，如果是，则不隐藏
        if (event && popup.contains(event.target)) {
          return;
        }
        popup.style.display = "none";
        document.removeEventListener("click", hidePopup);
        document.removeEventListener("keydown", keyDownHandler);
      }

      function keyDownHandler(event) {
        if (event.key === "Escape") {
          hidePopup();
        }
      }

      let that = this;
      //   if (type === "station") {

      //   } else {
      that.showBasicMsg = false;
      that.showVideoMsg = false;
      that.showProblemMsg = false;
      that.showModelMsg = false;
      //   }

      function popupMenuItemClick(event) {
        // 检查点击的是否是菜单项
        if (event.target.classList.contains("popup-menu-item")) {
          event.stopPropagation(); // 阻止冒泡，防止弹框立即关闭

          var messageType = event.target.dataset.messageType; // 获取 data-message-type
          console.log("点击了菜单项:", messageType);

          // 调用您的 showMessage 函数

          that.showMessage(messageType, val, viewer);
          hidePopup();

          // 可选：执行后关闭弹框
          // hideRightClickPopup();
        }
      }

      // 移除旧的监听器（避免重复绑定）
      document.removeEventListener("click", hidePopup);
      document.removeEventListener("click", popupMenuItemClick);
      document.removeEventListener("keydown", keyDownHandler);

      // 添加新的监听器
      document.addEventListener("click", hidePopup);
      document.addEventListener("click", popupMenuItemClick);
      document.addEventListener("keydown", keyDownHandler);
    },
    showMessage(type, val, viewer) {
      console.log("type===>>>", type);
      if (type !== "windbasic2d") {
        this.windDrawer = true;
        this.windDrawerHeader = val.name + "数据详情";
        
        if (type === "basic") {
          this.windDrawerTitle = "基础信息";
          this.showBasicMsg = true;
        } else if (type === "video") {
          this.windDrawerTitle = "视频监控";
          this.showVideoMsg = true;
        } else if (type === "problem") {
          this.windDrawerTitle = "故障查看";
          this.showProblemMsg = true;
        }
      } else {
        // this.showWindDetail = true;
        this.allStationentitys.forEach(({ entity, handler }) => {
          viewer.entities.remove(entity); // 移除实体
          if (!handler.isDestroyed()) {
            handler.destroy(); // 销毁事件处理器（关键！）
          }
        });
        this.allStationentitys = [];
        // this.showWindFromStation(viewer);
        this.showTypeViewer = false;
        this.cancleAllLayer();
        this.getCameraPosition(viewer)
      }
      //  else {
      //     this.windDrawerTitle = '模型解构'
      //     this.showModelMsg = true
      // }
    },
    // 获取当前经纬度和高度并跳转风机详情
    getCameraPosition(viewer) {
        const camera = viewer.camera;
        const ellipsoid = viewer.scene.globe.ellipsoid;

        // 获取相机的笛卡尔坐标
        const cartesianPosition = camera.position;

        // 转换为地理坐标（弧度）
        const cartographicPosition = ellipsoid.cartesianToCartographic(cartesianPosition);

        if (cartographicPosition) {
            const longitude = Cesium.Math.toDegrees(cartographicPosition.longitude); // 经度（度）
            const latitude = Cesium.Math.toDegrees(cartographicPosition.latitude);   // 纬度（度）
            const height = cartographicPosition.height;                             // 高度（米）

            // return { longitude, latitude, height };

            this.$router.push({
                path: "/windMap",
                query: {
                    longitude: longitude,
                    latitude: latitude,
                    height: Math.ceil(height)
                }
            });
        } else {
            return undefined; // 相机可能在地球之外或无效位置
        }
    },
    // 重置风场中所有风机视角
    resetWindViewport() {
      this.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          114.502778,
          35.326667,
          20000
        ),
        orientation: {
          heading: Cesium.Math.toRadians(0),
          pitch: Cesium.Math.toRadians(-90),
          roll: 0.0,
        },
        duration: 3.0,
      });
    },
    backStations() {
      this.showWindDetail = false;
      this.showTypeViewer = true;
      //   this.switchWindLayer();
      this.allWindEntitys.forEach(({ entity, handler }) => {
        this.viewer.entities.remove(entity); // 移除实体
        if (!handler.isDestroyed()) {
          handler.destroy(); // 销毁事件处理器（关键！）
        }
      });
      this.allWindEntitys = [];
      this.changeType(this.stationValue);
    },
    menuComTSty(val) {
      this.menuComTStyB = val;
    },
  },
};
</script>

<style lang="less" scoped>
.mapBox {
  width: 100%;
  height: 100%;
  position: relative;
  box-sizing: content-box;
  position: relative;
  .menuComC {
    position: fixed;
    bottom: 20px;
    left: 20px;
  }

  .menuBox {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    background: #fff;
    opacity: 0.8;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 10px;

    .el-button {
      margin: 0;
    }

    .item {
      font-size: 12px;
      margin-left: 10px;
    }

    &.switch {
      opacity: 0;
      transition: 0.2s;

      &:hover {
        opacity: 1;
        transition: 0.2s;
      }
    }
  }

  .tag {
    position: absolute;
    left: 0;
    top: 0;
    background: #fff;
    font-size: 12px;
    color: #000;
    padding: 4px 8px;
    border-radius: 28px;
    transform: translate(-50%, -50%);
    transition: 0.1s;
    pointer-events: none;
  }

  .devInfoBox {
    width: 130px;
    position: absolute;
    right: 0;
    bottom: 0;
    padding: 4px;
    font-size: 12px;
    color: #fff;
    background: rgba(0, 0, 0, 0.25);
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    z-index: 500;
    user-select: none;

    .item {
      width: 100%;
      margin-top: 4px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .dataLoading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 15px 20px;
    border-radius: 6px;
    font-size: 14px;
    pointer-events: none;
    display: none;
    z-index: 999;
  }
  .tempImg {
    // width: 40px;
    height: 500px;
    position: absolute;
    right: 0;
    bottom: 0px;
    img {
      height: 300px;
    }
  }
}
</style>
<style lang="less">
.modelDialog {
  .el-dialog__body {
    height: 750px;

    .el-tabs {
      height: 100%;

      .el-tab-pane {
        width: 100%;
        height: 100%;
      }

      .el-tabs__content {
        height: 100%;
      }
    }
  }
}
</style>
<style lang="less">
.el-overlay {
  background-color: transparent !important;
  .windModelDrawer {
    width: 80% !important;
    backdrop-filter: blur(15px) !important;
    background: rgba(255, 255, 255, 0.8) !important;
    border-radius: 10px 0 0 10px !important;
    .el-drawer__body {
      overflow: hidden;
      padding-top: 0;
    }
  }
}
.windDrawerCla {
  .line {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    margin-bottom: 10px;

    .leftContent {
      width: 242px;
      height: 41px;
      display: flex;
      align-items: center;
      background: url("@/assets/cesiumImg/title_left_bg.png") no-repeat;

      span {
        font-size: 16px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #ffffff;
        margin-left: 25px;
      }
    }
  }
  .jcxx,
  .gzck {
    height: 100%;
  }
  .spjk,
  .third {
    height: 80vh;
  }
}
</style>