<template>
  <div class="home">
    <div id="cesiumContainer"></div>
    <transition name="el-zoom-in-center">
      <div v-if="huanyingBox" @dblclick="huanyingBox = false" class="welcome">
        <span>{{ welcomeStr }}</span>
      </div>
    </transition>
    <svg-icon
      icon-class="huanying"
      style="color: red"
      class="iconhuanying"
      @click="huanyingBox = true"
    />
  </div>
</template>
<script>
import { welcomeQuery } from "@/api/tyler/screen";

export default {
  name: "cesium",
  data() {
    return {
      viewer: null,
      tileset: null, // 存储加载的3D Tileset
      markerList: [
        {
          longitude: 113.43095267132009,
          latitude: 32.547011665190039,
          height: 70,
          des: {
            name: "指挥中心",
            height: 300,
          },
        },
        {
          longitude: 113.42852104976393,
          latitude: 32.54756929901858,
          height: 35,
          des: {
            name: "35变电所",
            height: 550,
          },
        },
        {
          longitude: 113.42927005190415,
          latitude: 32.5467314676447,
          height: 40,
          des: {
            name: "选矿厂",
            height: 350,
          },
        },
        {
          longitude: 113.43050560273339,
          latitude: 32.544308886167876,
          height: 40,
          des: {
            name: "办公楼",
            height: 450,
          },
        },
        {
          longitude: 113.41589577353257,
          latitude: 32.55852021801037,
          height: 89,
          des: {
            name: "小高尖",
            height: 450,
          },
        },
        {
          longitude: 113.42033472323261,
          latitude: 32.55511520736364,
          height: 99,
          des: {
            name: "中央井",
            height: 1450,
          },
        },
        {
          longitude: 113.42321929988399,
          latitude: 32.55311983314357,
          height: 60,
          des: {
            name: "东风井",
            height: 1450,
          },
        },
      ],
      huanyingBox: false,
      welcomeStr: "",
    };
  },
  created() {
    welcomeQuery().then((res) => {
      this.welcomeStr = res.rows[0].title;
    });

    this.$nextTick(() => {
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2ZmY5ZWUyZS00MjQwLTQzZjUtYTBjZi02ZWZiYzJhMmY2NTYiLCJpZCI6MTMxMzY5LCJpYXQiOjE3NDE2NzY4Mzh9.QD-8cQI_VqPG2t-S8KxLyMFux0R429lfTdhQWrdeWhE";
      this.viewer = new Cesium.Viewer("cesiumContainer", {
        homeButton: false,
        sceneModePicker: false,
        baseLayerPicker: false,
        animation: false,
        infoBox: false,
        selectionIndicator: false,
        geocoder: false,
        timeline: false,
        fullscreenButton: false,
        shouldAnimate: false,
        scene3DOnly: true,
        navigationHelpButton: false,
      });
      this.viewer.cesiumWidget.creditContainer.style.display = "none";

      // 加载3D Tileset

      Cesium.Cesium3DTileset.fromUrl("/terra_b3dms_yd/tileset.json", {
        // Cesium.Cesium3DTileset.fromUrl(
        //   "http://localhost/terra_b3dms_yd/tileset.json",
        //   {
        maximumScreenSpaceError: 1,
        pickable: true,
      })
        .then((tileset) => {
          this.tileset = tileset; // 存储tileset供后续使用
          this.viewer.scene.primitives.add(tileset);

          // 调整模型高度
          var heightOffset = -250;
          var boundingSphere = tileset.boundingSphere;
          var cartographic = Cesium.Cartographic.fromCartesian(
            boundingSphere.center
          );
          var surface = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            0.0
          );
          var offset = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            cartographic.height + heightOffset
          );
          var translation = Cesium.Cartesian3.subtract(
            offset,
            surface,
            new Cesium.Cartesian3()
          );
          tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);

          // 开启地形深度检测
          this.viewer.scene.globe.depthTestAgainstTerrain = true;
          return this.viewer.zoomTo(tileset);
        })
        .then(() => {
          // 添加标记点
          this.addMarkers();
          // 设置初始视角
          this.viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(
              113.43050560273339, // 经度
              32.542908886167876, // 纬度
              200 // 高度(米)，数值越小视角越近
            ),
            orientation: {
              heading: Cesium.Math.toRadians(0), // 朝向角度
              pitch: Cesium.Math.toRadians(-45), // 俯仰角度
              roll: 0.0,
            },
          });
        })
        .catch((error) => {
          console.error("模型加载失败:", error);
        });

      // 监听鼠标点击事件
      const handler = new Cesium.ScreenSpaceEventHandler(
        this.viewer.scene.canvas
      );
      handler.setInputAction((movement) => {
        this.pickPosition(movement.position);
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    });
  },
  methods: {
    // 添加所有标记点
    addMarkers() {
      this.markerList.forEach((marker) => {
        this.addCustomPoint(marker);
      });
    },

    // 添加单个标记点
    addCustomPoint(pointInfo) {
      const position = Cesium.Cartesian3.fromDegrees(
        pointInfo.longitude * 1,
        pointInfo.latitude * 1,
        pointInfo.height * 1
      );

      // 创建描述信息HTML
      let des = '<table class="cesium-infoBox-defaultTable"><tbody>';
      Object.keys(pointInfo.des).forEach((key) => {
        des += `<tr><th>${key}</th><td>${pointInfo.des[key]}</td></tr>`;
      });
      des += "</tbody></table>";

      // 添加实体
      const entity = this.viewer.entities.add({
        position: position,
        billboard: {
          // image: Cesium.buildModuleUrl('Assets/Textures/maki/grocery.png'),
          image: "/img/location.png",
          width: 26,
          height: 26,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            1.0,
            8000.0
          ),
          disableDepthTestDistance: 15,
          // disableDepthTestDistance: Number.POSITIVE_INFINITY
        },
        label: {
          text: pointInfo.des.name || "监测点",
          font: "14px Microsoft YaHei",
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.TOP,
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            1.0,
            8000.0
          ),
          pixelOffset: new Cesium.Cartesian2(0, -60),
        },
        name: pointInfo.des.name || "建筑物信息",
        description: des,
      });

      console.log("添加标记点:", pointInfo.des.name);
    },

    // 拾取坐标点
    pickPosition(position) {
      const scene = this.viewer.scene;
      const ray = this.viewer.camera.getPickRay(position);
      const cartesian = scene.globe.pick(ray, scene);

      if (Cesium.defined(cartesian)) {
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        const longitude = Cesium.Math.toDegrees(cartographic.longitude);
        const latitude = Cesium.Math.toDegrees(cartographic.latitude);
        const height = cartographic.height;

        console.log(
          `拾取的坐标点：经度 ${longitude}, 纬度 ${latitude}, 高度 ${height}`
        );
      }
    },
  },
  beforeDestroy() {
    if (this.viewer) {
      this.viewer.destroy();
    }
    ``;
  },
};
</script>

<style scoped lang="scss">
.home {
  width: 100%;
  height: 100%;
  padding-top: 0px;
  pointer-events: auto;
  #cesiumContainer {
    width: 100%;
    height: 100%;
    pointer-events: auto;
    position: relative;
    z-index: 0 !important; // 强制设置基础层级
    transform: translateZ(0); // 创建独立层叠上下文
  }
  .welcome {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 999;
    background: url("~@/assets/images/screen/welcom.png") no-repeat;
    background-size: 100% 100%;
    color: red;
    font-family: "fangsong";
    font-size: 54px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    user-select: none;
    padding-bottom: 100px;
    span {
      font-weight: 800;
      background: linear-gradient(
        0deg,
        #38d7ff 0.634765625%,
        #f4ffff 61.279296875%
      );
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      display: inline-block;
      max-width: 1300px;
    }
  }
  .iconhuanying {
    font-size: 52px;

    position: absolute;
    right: 50px;
    bottom: 50px;
    color: #000;
    fill: rgba(25, 69, 108, 0.5); /* 修改第二个路径的颜色 */
    &:hover {
      cursor: pointer;
      fill: rgba(25, 69, 108, 1);
    }
  }
}
// 新增强制穿透样式
::v-deep .cesium-widget canvas {
  pointer-events: auto !important;
  position: relative;
  z-index: 0;
}

// 移除Cesium默认事件拦截
::v-deep .cesium-widget-credits {
  display: none !important;
}
</style>
