<template>
  <div id="cesiumContainer" ref="cesiumContainer">
    <!-- <c-pointer></c-pointer> -->
    <slot v-if="map"></slot>
    <div class="title-box" ref="title_box" :style="titlePosition">
      <div>
      联华超市（天目山路）

      </div>
      <div>
        今日人流量：11222
      </div>
      </div>
  </div>
</template>

<script>
import * as Cesium from "cesium";
import "cesium/Build/Cesium/Widgets/widgets.css";
window.Cesium = Cesium;
window.CESIUM_BASE_URL = "/static/Cesium/";
import { CesiumZh } from "utils/cesium/CesiumZh.js";
export default {
  name: "LhMap3d",
  props: {
    // 初始化缩放层级
    zoom: {
      type: Number,
      default: 10,
    },
    // 初始化中心经纬度
    center: {
      type: Array,
      default() {
        return [108.349402, 21.678761, 500];
      },
    },
    viewerOptions: {
      type: Object,
      default() {
        return {
          CreditsDisplay: false, //展示数据版权属性
          animation: false, //左下角仪表
          fullscreenButton: false, //全屏按钮
          timeline: false, //时间轴
          // sceneMode: 3,
        };
      },
    },
  },
  data() {
    return {
      map: null,
      isMap: true,
      isOlMap: false,
      titlePosition: {
        bottom: '10px',
        left: '10px',
      },
    };
  },
  provide() {
    return {
      coordType: null,
      bounds: null,
    };
  },

  beforeDestroy() {},
  methods: {
    init() {
      this.$store.commit("setIsOlMap", false);
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxZmY4NjlmZS1iM2IwLTRlNWUtOWU5Yy0yMDM2MGRlZjZkZGMiLCJpZCI6Mzc2MzEsImlhdCI6MTYwNjY1MzcyMX0.cNGtGAI3APmDMaFsudpOwkBGXZcpoXgf8mgA9Fdq4jE";
      //可能要在cesium账号中添加数据 暂时用网上的token
      // Cesium.Ion.defaultAccessToken =
      //   "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJiY2RhMDMyYi1mODVkLTRkODAtYmI4MS0zZTY0OTM3OGExZWEiLCJpZCI6MjU5LCJpYXQiOjE2MTQ1OTIwNDZ9.0jO0HJaY0N1DrvfxPuuoDPWN_ebN2o2Ku2DrRC_P8qs";
      console.log(this.viewerOptions, "参数");
      this.map = new Cesium.Viewer(this.$refs.cesiumContainer, {
        terrainProvider: Cesium.createWorldTerrain(),
        proxy: new Cesium.DefaultProxy("/proxy/"), //cesium的跨域
        // ...this.viewerOptions,
        CreditsDisplay: false, //展示数据版权属性
        animation: false, //左下角仪表
        fullscreenButton: false, //全屏按钮
        timeline: false,
        // baseLayerPicker: false,
        //  imageryProvider: imgMap,
        animation: false, //左下角仪表
        fullscreenButton: false, //全屏按钮
        geocoder: false, //右上角查询搜索
        // sceneMode: 3, //初始场景模式 1 2D模式 2 2D循环模式 3 3D模式  Cesium.SceneMode
        // infoBox: false,   //信息框
        homeButton: false, //home按钮
        sceneModePicker: false, //3d 2d选择器
        // selectionIndicator: false,  //
        timeline: false, //时间轴
        // navigationHelpButton: false,  //右上角帮助按钮
        // imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
        //       url: "t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",
        //       layer: "tdtBasicLayer",
        //       style: "default",
        //       format: "image/jpeg",
        //       tileMatrixSetID: "GoogleMapsCompatible",
        //       show: false
        //   })
        //     imageryProvider:new Cesium.UrlTemplateImageryProvider({
        //   url:
        //     "tdt/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=464554f64aa4f4e90e0321c17a57a331",
        //   layer: "tdtCiaBasicLayer",
        //   style: "default",
        //   format: "image/jpeg",
        //   tileMatrixSetID: "GoogleMapsCompatible",
        //   show: false,
        // });
      });
      var imageryLayers = this.map.imageryLayers;

      //加载天地影像影像注记
      var tdtCia_w = new Cesium.UrlTemplateImageryProvider({
        url:
          "tdt/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=464554f64aa4f4e90e0321c17a57a331",
        layer: "tdtCiaBasicLayer",
        style: "default",
        format: "image/jpeg",
        tileMatrixSetID: "GoogleMapsCompatible",
        show: false,
      });

      // this.map.zoomTo(this.map.entities);
      imageryLayers.addImageryProvider(tdtCia_w);
      //相机飞行 设置中心点
      this.setCenter(this.center);
      //测试实体
      // this.addEntity();
      this.addGeoserveLayers();
      // this.map.scene.camera.moveEnd.addEventListener((e) => {
      //   this.$emit("move-end", this.map);
      // });
      // this.map.camera.DEFAULT_VIEW_FACTOR=3
      //设置主页按钮的中心点
      this.map.homeButton &&
        this.map.homeButton.viewModel.command.beforeExecute.addEventListener(
          (e) => {
            e.cancel = true;

            //你要飞的位置
            this.setCenter([108.350298, 21.688681, 1000]);
          }
        );
    },
    /**
     * 设置中心点
     * Rectangle [113, 23, 1000] 经度 纬度 高度
     *  */
    setCenter(Rectangle) {
      this.map.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          Rectangle[0],
          Rectangle[1],
          Rectangle[2]
        ),
        //包含了方位(direction)、上方向(up)以及方位角(heading)、俯仰角(pitch)、滚动角(roll)属性的对象。
        orientation: {
          // up: Cesium.Math.toRadians(5.0),
          heading: Cesium.Math.toRadians(5.0), //方位角
          pitch: Cesium.Math.toRadians(-15.0), //、俯仰角
        },
      });
    },
    /**
     * 加载形状
     */
    addEntity() {
      this.map.entities.add({
        name: "Red box with black outline ",
        description: `添加一个模型`,
        position: Cesium.Cartesian3.fromDegrees(108.351127, 21.693294, 100),
        box: {
          dimensions: new Cesium.Cartesian3(100.0, 100.0, 1000.0),
          material: Cesium.Color.RED.withAlpha(0.5),
          outline: true,
          outlineColor: Cesium.Color.BLACK,
        },
        //  point: { pixelSize: 10, color: Cesium.Color.RED }
      });
    },
    /**
     * 加载geoserve图层
     */
    addGeoserveLayers() {
      this.map.container.appendChild(this.$refs.title_box);

      var imageryLayers = this.map.imageryLayers;
      // var shadedRelief1 = new Cesium.WebMapTileServiceImageryProvider({
      //     url : 'http://basemap.nationalmap.gov/arcgis/rest/services/USGSShadedReliefOnly/MapServer/WMTS',
      //     layer : 'USGSShadedReliefOnly',
      //     style : 'default',
      //     format : 'image/jpeg',
      //     tileMatrixSetID : 'default028mm',
      //     // tileMatrixLabels : ['default028mm:0', 'default028mm:1', 'default028mm:2' ...],
      //     maximumLevel: 19,
      //     credit : new Cesium.Credit('U. S. Geological Survey')
      // });
      var arcGISMap = new Cesium.WebMapServiceImageryProvider({
        url: "http://47.112.216.198:5080/geoserver/fcg/wms",
        layers: "fcg:fcgtest_5", //WMTS请求的层名称
        // layer: "ylwork:SXSS", //WMTS请求的层名称
        style: "default",
        // tileMatrixSetID: "default028mm",
        parameters: {
          service: "WMS",
          format: "image/png",
          transparent: true,
        },
      });

      // imageryLayers.addImageryProvider(arcGISMap);
      var tilesetModel = new Cesium.Cesium3DTileset({
        url: "cesium/3DTiles/tileset.json",
        // url: "./",
        // url: Cesium.IonResource.fromAssetId(75343),
        maximumScreenSpaceError: 2, //最大的屏幕空间误差
        maximumNumberOfLoadedTiles: 10000,//最大加载瓦片个数
      });
      // 由于生成3dtiles文件时使用的底图和地形和cesium加载的可能不同，再加上人工调整模型位置具有一定的偏差，所以3dtiles模型加载到数字地球上之后，可能需要再次调整位置，所以最好有前端调整工具去进行模型位置的调整
      let tileset = this.map.scene.primitives.add(tilesetModel);
      tileset.readyPromise
        .then((currentModel) => {
          // console.log(tileset.boundingSphere.center,"成功");
          console.log(currentModel, "成功", tilesetModel.boundingSphere.radius);
          //加载模型数据并定位到模型
          var params = {
            tx: 108.349402, //模型中心X轴坐标（经度，单位：十进制度）
            ty: 21.678761, //模型中心Y轴坐标（纬度，单位：十进制度）
            tz: 0, //模型中心Z轴坐标（高程，单位：米）
            rx: 0, //X轴（经度）方向旋转角度（单位：度）
            ry: 0, //Y轴（纬度）方向旋转角度（单位：度）
            rz: 0, //Z轴（高程）方向旋转角度（单位：度）
            scale: 1.0,
            longitude: 108.349402,
            latitude: 21.678761,
            height: 1000, //修改高度
            alpha: 1,
          };
          var boundingSphere = tileset.boundingSphere;
          // 设置相机，使当前视图包含提供的边界球。
          // this.map.camera.viewBoundingSphere(
          //   boundingSphere,
          //   new Cesium.HeadingPitchRange(0.5, -0.2, boundingSphere.radius * 1.5)//定义航向角，俯仰角和范围
          // );
          // 使用目标和变换矩阵设置相机的位置和方向
          // this.map.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
          // viewer.zoomTo(tileset);
          //修改经纬度位置
          console.log(tileset._root);
          // return
          // tileset._root.transform = this.update3dtilesMaxtrix(params);
          //贴地显示
          //       var height=-30;
          //  var cartographic = Cesium.Cartographic.fromCartesian(tileset.boundingSphere.center);
          //  var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height);
          //  var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height + height);
          //  var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
          //  tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
          return;
        })
        .otherwise((error) => {
          console.log(error, "模型加载错误");
        });
// return
//       var highlightFace = null;
//       //获取左键点击事件
//       this.map.screenSpaceEventHandler.setInputAction((movement) => {
//         console.log(movement, "movement");
//         var pickedFeature = this.map.scene.pick(movement.position);
//         if (typeof pickedFeature != "undefined")
//           //鼠标是否点到面上
//           var id = pickedFeature.id;
//         this.titlePosition = {
//           bottom: this.map.canvas.clientHeight - movement.position.y + "px",
//           left: movement.position.x + "px",
//         };
//         // nameOverlay.textContent = 1111;
//         console.log(pickedFeature, 11111);
//         console.log(pickedFeature.getProperty("BIN"))
//       }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      // tileset.style = new Cesium.Cesium3DTileStyle({
        // color: {
        //   conditions: [
        //     ["${height} >= 100", "rgba(45, 0, 75, 0.5)"],
        //     // ["${height} >= 200", "rgb(102, 71, 151)"],
        //     // ["${height} >= 100", "rgb(170, 162, 204)"],
        //     ["${height} >= 50", "rgb(224, 226, 238)"],
        //     ["${height} >= 25", "rgb(252, 230, 200)"],
        //     ["${height} >= 10", "rgb(248, 176, 87)"],
        //     ["${height} >= 5", "rgb(198, 106, 11)"],
        //     ["true", "rgb(127, 59, 8)"]
        // ],
        // },
      // });
    },
    /**
     * 调整模型参数
     */
    update3dtilesMaxtrix(params) {
      var mx = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(params.rx));
      var my = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(params.ry));
      var mz = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(params.rz));
      var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);
      var rotationY = Cesium.Matrix4.fromRotationTranslation(my);
      var rotationZ = Cesium.Matrix4.fromRotationTranslation(mz);
      //平移 修改经纬度
      var position = Cesium.Cartesian3.fromDegrees(
        params.longitude,
        params.latitude,
        params.height
      );
      var m = Cesium.Transforms.eastNorthUpToFixedFrame(position);
      //旋转、平移矩阵相乘
      Cesium.Matrix4.multiply(m, rotationX, m);
      Cesium.Matrix4.multiply(m, rotationY, m);
      Cesium.Matrix4.multiply(m, rotationZ, m);
      //缩放 修改缩放比例
      var scale = Cesium.Matrix4.fromUniformScale(params.scale);
      Cesium.Matrix4.multiply(m, scale, m);
      //赋值给tileset
      window.tileModel._root.transform = m;
      //调整地下透明度
      viewer.scene.globe.translucency.frontFaceAlphaByDistance.nearValue = Cesium.Math.clamp(
        params.alpha,
        0.0,
        1.0
      );
    },
  },
  mounted() {
    this.init();
    //汉化
    CesiumZh.load();
  },
};
</script>

<style lang='scss' scoped>
#cesiumContainer {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  position: relative;
  /deep/.cesium-viewer-bottom {
    display: none;
  }
}
.title-box {
  background-color: #cccc;
  color: #fff;
  position: absolute;
  padding: 10px;
}
</style>