<template>
  <div id="layer-container" class="cpt-cesium_layer"></div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import _3dList from "./lib/3d";
import _2dList from "./lib/2d";

export default {
  name: "CesiumLayer",
  data() {
    return {
      viewer: null,
      init_lng: 112.576667,
      init_lat: 23.175833,
      init_alt: 5000,
      imageryLayers: {
        night: null, // 夜景图
        satellite: null, // 卫星图
        text: null, // 地名标记
      },
    };
  },
  computed: {
    ...mapState("MMCFlightControlCenter", [
      "cesiumImagesLayers",
      "cesium3DModels",
    ]),
    ...mapState(["mapMode"]),
  },
  watch: {},
  mounted() {
    if (!window.$mmc) {
      window.$mmc = {};
    }
    window.$mmc.viewer = {};
    this.init_viewer();
  },
  methods: {
    ...mapActions([]),
    selectMpa(item) {
      console.log(item, "item");
    },
    bus_getPositions() {
      this.$bus.$on("handlePositions", (e) => {
        this.init_lng = e[0];
        this.init_lat = e[1];
        this.init_alt = 300000;
        this.viewer.scene.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(
            this.init_lng,
            this.init_lat,
            this.init_alt
          ),
        });
      });
    },
    async init_viewer() {
      // 超图服务加密访问
      // Ap6qLhnKi1YT4ds90jxn6mftBG4tmLFbTH2Y79XRGMG4fophoB8axKlCj6IuQMW8dAXsyHAnmzrU-zF1tMuMpg..
      // Cesium.Credential.CREDENTIAL = new Cesium.Credential('r0G6d8tdvfgN_Aad1j28SGqj6ILgt1DNHpP9dK-FNVOVBPgcyaHiEs2z2qyv455bTHU8QaFTbt_Y_AdeAsPp-Q..');
      // 解决航线被三维模型遮盖
      const oldPolylineUpdate = Cesium.PolylineCollection.prototype.update;
      Cesium.PolylineCollection.prototype.update = function (frameState) {
        const oldMorphTime = frameState.morphTime;
        frameState.morphTime = 0.0;
        oldPolylineUpdate.call(this, frameState);
        frameState.morphTime = oldMorphTime;
      };
      const viewerOptions = {
        animation: false,
        shouldAnimate: true,
        homeButton: false,
        fullscreenButton: false,
        vrButton: false,
        baseLayerPicker: false,
        geocoder: false,
        timeline: false,
        sceneModePicker: false,
        navigationHelpButton: false,
        navigationInstructionsInitiallyVisible: false,
        infoBox: false,
        requestRenderMode: true,
        scene3DOnly: false,
        sceneMode: 3,
        fullscreenElement: document.body,
        selectionIndicator: false,
      };

      window.$mmc.viewer = this.viewer = new Cesium.Viewer(
        `layer-container`,
        viewerOptions
      );
      this.$store.commit("MMCFlightControlCenter/setState", {
        key: "cesiumViewer",
        value: this.viewer,
      });

      // 卫星图
      this.imageryLayers.satellite =
        this.viewer.imageryLayers.addImageryProvider(
          new Cesium.UrlTemplateImageryProvider({
            url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
            maximumLevel: 17,
          })
        );
      // 星图地球卫星影像 https://datacloud.geovisearth.com/
      // 会员源地址 url: "https://tiles{s}.geovisearth.com/plus/v1/img/{z}/{x}/{y}?format=webp&tmsIds=w&token=",
      this.imageryLayers.star_satellite =
        this.viewer.imageryLayers.addImageryProvider(
          new Cesium.UrlTemplateImageryProvider({
            url: "https://tiles{s}.geovisearth.com/base/v1/img/{z}/{x}/{y}?format=webp&token=4c504c0d9bdd48c3ba76731ffd14a536f6277d0c334d8f8a07652e26763a928d",
            subdomains: "123",
            maximumLevel: 18,
          })
        );
      // 街道图
      this.imageryLayers.street = this.viewer.imageryLayers.addImageryProvider(
        new Cesium.UrlTemplateImageryProvider({
          url: "https://webrd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8",
        })
      );
      // 夜视图
      this.imageryLayers.night = this.viewer.imageryLayers.addImageryProvider(
        new Cesium.UrlTemplateImageryProvider({
          url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
          maximumLevel: 16,
        })
      );
      // 地图标注
      this.imageryLayers.text = this.viewer.imageryLayers.addImageryProvider(
        new Cesium.WebMapTileServiceImageryProvider({
          url: "https://{s}.tianditu.gov.cn/cia_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE={style}&TILEMATRIXSET={TileMatrixSet}&FORMAT=tiles&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&tk=a5e0a8dcf07f40afe19b76bf8a32eef0",
          layer: "cia",
          style: "default",
          format: "tiles",
          tileMatrixSetID: "c",
          credit: new Cesium.Credit("天地图全球影像服务"),
          tilingScheme: new Cesium.GeographicTilingScheme(), //采用经纬度投影
          subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
          tileMatrixLabels: [
            "1",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9",
            "10",
            "11",
            "12",
            "13",
            "14",
            "15",
            "16",
            "17",
            "18",
          ],
          maximumLevel: 18,
        })
      );
      this.imageryLayers.night.show = false;
      this.imageryLayers.street.show = false;
      this.imageryLayers.star_satellite.show = false;

      this.viewer.scene.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          this.init_lng,
          this.init_lat,
          this.init_alt
        ),
      });

      this.$store.commit("MMCFlightControlCenter/setState", {
        key: "cesiumImagesLayers",
        value: this.imageryLayers,
      });

      // 加载三维倾斜
      window.$mmc._3d = [];
      /* const token =
        'r0G6d8tdvfgN_Aad1j28SGqj6ILgt1DNHpP9dK-FNVOVBPgcyaHiEs2z2qyv455bTHU8QaFTbt_Y_AdeAsPp-Q..'; */
      _3dList.forEach(async (item) => {
        const obj = await this.viewer.scene.addS3MTilesLayerByScp(
          `https://ct.mmcuav.cn:8443/iserver/services/${item}/rest/realspace/datas/Config/config`,
          {
            name: item,
            // cullEnabled: false
          }
        );
        window.$mmc._3d.push(obj);
        if (item === "3D-ZQ-JLH") {
          // 肇庆九龙湖的模型需要修改海拔, 使其贴地
          obj.style3D.bottomAltitude = -20;
        }
      });
      this.$store.commit("MMCFlightControlCenter/setState", {
        key: "cesium3DModels",
        value: window.$mmc._3d,
      });

      // 二维影像缓存加载方式
      window.$mmc._2d = [];
      ["3D-ZQ-DH", "3D-local3DCache-s3mb"].forEach((item) => {
        this.viewer.scene
          .open(
            `https://ct.mmcuav.cn:8443/iserver/services/${item}/rest/realspace`,
            undefined,
            {
              subdomains: [""], // 子域
              autoSetView: false, // 不自动定位
            }
          )
          .then((obj) => {
            window.$mmc._2d.push(obj);
          });
      });

      // 关闭地图深度检测
      this.viewer.scene.globe.depthTestAgainstTerrain = false;
      // 飞向指定的经纬度
      window.$mmc.flyTo = function (lng, lat) {
        this.viewer.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(lng, lat, 1000),
        });
      };
    },
  },
};
</script>

<style lang="scss" scoped>

.cpt-cesium_layer::v-deep {
  width: 100%;
  height: 100%;

  #layer-container {
  }

  .cesium-viewer-bottom {
    display: none;
  }

  .cesium-viewer-zoomIndicatorContainer {
    display: none;
  }

  .cesium-viewer-navigationContainer {
    display: none;
  }

  .cesium-credit-logoContainer {
    display: none;
  }
}

.videoWallMapStyle {
  position: fixed !important;
  left: 12px !important;
  top: 63px !important;
  bottom: 0 !important;
  width: 415px !important;
  height: 234px !important;
  box-sizing: border-box !important;
  z-index: 1;
}

.right_33 {
  right: 33%;
}
</style>
