<template>
  <div class="marker-wrap">
    <div id="cesiumContainer"></div>
  </div>
</template>

<script>
import * as Cesium from 'cesium'
import {loadWindfield, removeWindfield, loadWindfieldWithDataNew} from './WindMap/WindField'
import {loadHeatmap, loadHeatmapByData} from './HeatMap/examples/heatmap'
import Wind from './wind.json'
import Atmospheric from './atmospheric.json'

export default {
  data() {
    return {
      viewer: null,
      windData: null,
      pressureData: null,
      temperatureData: null,
      atmosphericData: null,
    }
  },
  watch: {
    '$route.query.type': {
      handler(val) {
        removeWindfield()
        let lay = this.findLayerByName('heatmap')
        this.viewer.imageryLayers.remove(lay);

        this.setFunByParam(val)
      }
    }
  },
  created() {},
  mounted() {
    this.initCesium()
    this.getAtmosphericStability()
  },
  methods: {
    // 获取大气稳定度数据
    async getAtmosphericStability() {
      // 2024-05-18到2024-05-24是有数据的
      let params = {
        date: '2024-05-20',
        lon_center: 116,
        lat_center: 39,
        grid_halfwidth_deg: 1
      }
      this.loading = true
      const res = await this.$axios.post(window.CONFIG.baseUrl + '/nuclide-sim/calculate_atmospheric_stability', params, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      })
      this.loading = false

      this.atmosphericData = res.stability_result.stability_result
    },
    // 获取风场、温度场、气压场数据
    async getWindTemperaturePressure() {
      let params = {
        date: '2024-05-20',
        lon_center: 116,
        lat_center: 39,
        grid_halfwidth_deg: 1
      }
      try {
        this.loading = true
        const res = await this.$axios.post(window.CONFIG.baseUrl + '/nuclide-sim/get_wind_temperature_pressure_data', params, {
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
        this.loading = false
        // const res = Wind

        this.windData = res.wind_result
        this.pressureData = res.pressure_result.pressure_result
        this.temperatureData = res.temp_result.temp_result

        let param = this.$route.query ? this.$route.query.type : ''
        this.setFunByParam(param)
        // removeWindfield()
        // loadWindfield(this.viewer)
        // loadWindfieldWithDataNew(this.viewer, res.wind_result)

        // loadHeatmap(this.viewer)
      } catch (error) {
        console.log(error)
      }
    },
    setFunByParam(val) {
      switch (val) {
        case 'Wind':
          // loadWindfield(this.viewer)
          loadWindfieldWithDataNew(this.viewer, this.windData)
          break
        case 'AtmosphericStability':
          debugger
          loadHeatmapByData(this.viewer, this.atmosphericData)
          break
        case 'AirPressure':
          loadHeatmapByData(this.viewer, this.pressureData)
          break
        case 'Temperature':
          loadHeatmapByData(this.viewer, this.temperatureData)
          break
        default:
          loadWindfieldWithDataNew(this.viewer, this.windData)
      }
    },
    findLayerByName(layerName) {
      for (let i = 0; i < this.viewer.imageryLayers.length; i++) {
        const layer = this.viewer.imageryLayers.get(i);
        if (layer.name === layerName) {
          return layer;
        }
      }
      return null;
    },
    initCesium() {
      // 设置Cesium Ion访问令牌（需在官网申请）
      Cesium.Ion.defaultAccessToken =
        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI0N2FjZGMzOC1kOGRlLTQ2MjgtOTQ3Yy0wZjNhNjU2MWE2YzMiLCJpZCI6MTU2MjMzLCJpYXQiOjE2OTAyNjQ2Mjl9.ek7v5pm-V7zWe5rxLGYIWuavneNk4p-VO40KictHc_Y'

      // 初始化Cesium Viewer
      this.viewer = new Cesium.Viewer('cesiumContainer', {
        homeButton: false, // 不显示Home按钮
        sceneModePicker: false, // 不显示场景模式选择器
        baseLayerPicker: false, // 不显示底图选择器
        animation: false, // 不显示动画控件
        timeline: false, // 不显示时间线控件
        fullscreenButton: false, // 不显示全屏按钮
        geocoder: false, // 不显示地名查找控件
        infoBox: false, // 显示信息框
        selectionIndicator: false, // 不显示选择指示器
      })

      // 移除默认的版权信息
      this.viewer._cesiumWidget._creditContainer.style.display = 'none'

      // 初始化完成后加载模型
      this.flyToBeijing()

      // 开启风场
      // loadWindfield(this.viewer)
      // this.getAtmosphericStability()
      this.getWindTemperaturePressure()
      // this.getWindData()
      // 开启热力图
      // loadHeatmap(this.viewer)
    },

    flyToBeijing() {
      // 北京坐标（经度, 纬度, 高度）
      const beijingPosition = Cesium.Cartesian3.fromDegrees(116.3903, 39.9001, 600000)

      this.viewer.camera.flyTo({
        destination: beijingPosition, // 目标位置
        orientation: {
          heading: Cesium.Math.toRadians(0), // 航向角（0度为正北）
          pitch: Cesium.Math.toRadians(-90), // 俯仰角（-45度为45度俯视）
          roll: 0.0, // 滚转角（保持水平）
        },
        duration: 3.0, // 飞行时间（秒）
      })

      // 飞行完成后添加模型
      this.viewer.camera.moveEnd.addEventListener(() => {
        console.log('飞行完成')
      })
    },

    // async getWindData() {
    //   let now = new Date().toLocaleDateString('zh-CN', {
    //     year: 'numeric',
    //     month: '2-digit',
    //     day: '2-digit'
    //   }).replace(/\//g, '-');
    //   debugger
    //   try {
    //     const res = await this.$axios.get(window.CONFIG.baseUrl + '/nuclide-sim/get_wind_temperature_data', { params: { date: now }})
    //     console.log("111111111111111", res)
    //     debugger
    //     removeWindfield()
    //     loadWindfieldWithData(this.viewer, res.data.result)
    //   } catch (error) {
    //     console.log(error)
    //   }
    // },
  },
  beforeDestroy() {
    // 组件销毁时清理Cesium实例
    if (this.viewer && !this.viewer.isDestroyed()) {
      this.viewer.destroy()
    }
  },
}
</script>

<style scoped lang="scss">
.marker-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  #cesiumContainer {
    width: 100%;
    height: 100%;
    ::v-deep .cesium-viewer-toolbar {
      .cesium-navigationHelpButton-wrapper {
        display: none;
      }
    }
  }
}
</style>
