<template>
  <div class="track3D-container" :id="cId"></div>
</template>

<script>
let viewer = null;
export default {
  name: "cesiumMap",
  props: ["cId", "loadTileset"],
  components: {},
  watch: {},
  data() {
    return {};
  },
  computed: {},
  methods: {
    loadMap() {
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI1OWE5YzQ2ZS05NDYzLTQ3NTEtYTZhOC0yNDhmMmIyY2I5ZTAiLCJpZCI6MTA0MTAyLCJpYXQiOjE2ODU2MTMxOTB9.JxmgXnf8_-V1eM9we2W8VfiP37vyGMJJDSWF4Br6hKU";
      viewer = new Cesium.Viewer(this.cId, {
        contextOptions:{
          requestWebgl2: true
        },
        msaaSamples:2,
        // targetFrameRate: 30, // 目标帧率
        animation: false, // 隐藏动画控件
        baseLayerPicker: false, // 隐藏图层选择控件
        fullscreenButton: false, // 隐藏全屏按钮
        vrButton: false, // 隐藏VR按钮，默认false
        geocoder: false, // 隐藏地名查找控件
        homeButton: false, // 隐藏Home按钮
        // infoBox: true, // 隐藏点击要素之后显示的信息窗口
        infoBox: false, // 隐藏点击要素之后显示的信息窗口
        sceneModePicker: false, // 隐藏场景模式选择控件
        selectionIndicator: false, // 显示实体对象选择框，默认true
        timeline: true, // 时间线控件
        navigationHelpButton: false, // 隐藏帮助按钮
        scene3DOnly: true, // 每个几何实例将只在3D中呈现，以节省GPU内存
        shouldAnimate: true, // 开启动画自动播放
        sceneMode: 3, // 初始场景模式 1：2D 2：2D循环 3：3D，默认3
        requestRenderMode: true, // 减少Cesium渲染新帧总时间并减少Cesium在应用程序中总体CPU使用率
        imageryProvider: false,
        // 如场景中的元素没有随仿真时间变化，请考虑将设置maximumRenderTimeChange为较高的值，例如Infinity
        // maximumRenderTimeChange: Infinity,
        // shadows: true, // 阴影
        // imageryProvider: new Cesium.UrlTemplateImageryProvider({
        //   url: cesium_config.baseMap,
        //   fileExtension: "png"
        // }),
        // imageryProvider:new Cesium.ArcGisMapServerImageryProvider({
        //   url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Terrain_Base/MapServer'
        // }),
      });
      viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString("#112e4a"); //改变空球的颜色
      // 添加光源
      viewer.scene.light = new Cesium.DirectionalLight({
        direction: new Cesium.Cartesian3(0.354925, -0.890918, -0.283358),
        intensity: cesium_config.tilesetIntensity || 0.5,
      });

      if (this.loadTileset) {
        const tileset = new Cesium.Cesium3DTileset({
          url: cesium_config.tile3dURL,
          skipLevelOfDetail: true,
          baseScreenSpaceError: 1024,
          skipScreenSpaceErrorFactor: 16,
          skipLevels: 1,
          immediatelyLoadDesiredLevelOfDetail: false,
          loadSiblings: false,
          cullWithChildrenBounds: true,
          dynamicScreenSpaceError: true,
          dynamicScreenSpaceErrorDensity: 0.00278,
          dynamicScreenSpaceErrorFactor: 4.0,
          dynamicScreenSpaceErrorHeightFalloff: 0.25,
        }); 

        tileset.readyPromise.then(() => {
          window.tileset = tileset;
          this.$emit("tilesetReady");
          //计算tileset的绑定范围
          let boundingSphere = tileset.boundingSphere;
          //计算中心点位置
          let cartographic = Cesium.Cartographic.fromCartesian(
            boundingSphere.center
          );
          //计算中心点位置的地表坐标
          let surface = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            0.0
          );
          console.log("tileset自身center : ", [
            Cesium.Math.toDegrees(cartographic.longitude),
            Cesium.Math.toDegrees(cartographic.latitude),
          ]);
          // 偏移tileset到指定位置
          let heightOffset = cesium_config.tilesetHeightOffset;
          let x = Cesium.Math.toDegrees(cartographic.longitude);
          let y = Cesium.Math.toDegrees(cartographic.latitude);
          let offset = Cesium.Cartesian3.fromRadians(
            cesium_config.tilesetOffsetX
              ? Cesium.Math.toRadians(x + cesium_config.tilesetOffsetX)
              : cartographic.longitude,
            cesium_config.tilesetOffsetY
              ? Cesium.Math.toRadians(y + cesium_config.tilesetOffsetY)
              : cartographic.latitude,
            heightOffset
          );
          let translation = Cesium.Cartesian3.subtract(
            offset,
            surface,
            new Cesium.Cartesian3()
          );
          //tileset.modelMatrix转换
          tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
        });
        viewer.scene.primitives.add(tileset);
      }

      viewer.cesiumWidget.creditContainer.style.display = "none";
      // 以下设置为了使cesium地图鼠标控制符合mapbox习惯
      // 关闭双击事件
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
      );
      // 鼠标右键旋转
      viewer.scene.screenSpaceCameraController.tiltEventTypes = [
        Cesium.CameraEventType.RIGHT_DRAG,
      ];
      // 中键滚动缩放
      viewer.scene.screenSpaceCameraController.zoomEventTypes = [
        Cesium.CameraEventType.WHEEL,
      ];
      // 鼠标左键平移
      viewer.scene.screenSpaceCameraController.rotateEventTypes = [
        Cesium.CameraEventType.LEFT_DRAG,
      ];
      viewer.scene.globe.enableLighting = true;
 
    // 开启抗锯齿
    viewer.scene.postProcessStages.fxaa.enabled = true
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          ...cesium_config.center,
          cesium_config.zoomHeight
        ),
        orientation: {
          heading: Cesium.Math.toRadians(0), // 旋转角度
          pitch: Cesium.Math.toRadians(-90.0), // 相机方向
        },
        duration: 0.5,
      });
      return viewer;
    },
  },
  mounted() {},
  created() {},
  beforeDestroy() {
    viewer?.destroy();
  },
};
</script>
<style>
.cesium-viewer-timelineContainer {
  z-index: 15;
  left: 625px !important;
  width: 1025px !important;
  bottom: 35px !important;
  height: 40px !important;
}

.cesium-timeline-bar {
  height: 30px;
}

.cesium-timeline-main {
  height: inherit;
}

.cesium-timeline-trackContainer {
  height: unset !important;
}

/* pop框css*/
.cesium-popup-panel {
  opacity: 0.8;
  position: absolute;
  z-index: 0;
}

.cesium-popup-close-btn > svg:hover {
  color: #00fcf9 !important;
}

.cesium-popup-close-btn > svg {
  display: none;
  user-select: auto;
  color: #4674d6;
  cursor: pointer;
  width: 15px;
}

.cesium-viewer {
  position: unset;
}
</style>
