<template>
  <div class="viewer_container">
    <div id="cesiumContainer">
      <!-- <div class="get_now_camera_view">
      <van-button @click="consoleCameraPosition"> 当前视角 </van-button>
      <van-button @click="setViewDefaultlocation"> 复位 </van-button>
    </div>
    <van-popup
      v-model:show="dialogVisible"
      :style="{ height: '50%', width: '80%' }"
      :closed="hideInfoDailog"
    >
      <div>
        <div style="font-size: 16px">{{ dialogInfoStr }}</div>
        <van-button @click="hideInfoDailog">关 闭</van-button>
        <van-button :class="'copy_info_dialog'" type="primary">
          复 制
        </van-button>
      </div>
    </van-popup> -->
    </div>
    <canvas id="canvas-b" class="canvas" width="500" height="180"></canvas>
    <Tool></Tool>
  </div>
</template>

<script>
// import Clipboard from "clipboard";
import { defineAsyncComponent } from "vue";
import Water from "@/utils/Water";
import api from "@/api/content";

export default {
  data() {
    return {
      JHEntityObj: {},
      dialogVisible: false,
      dialogInfoStr: "",
      clipboard: null,
      correctCamera: false,
      waterObj: null, // 水面实例
      flylineObj: [], // 飞线数组
      topK: [
        {
          lon: 121.12265818599361,
          lat: 31.153907327111906,
          h: 12.178229477117695,
        },
        {
          lon: 121.12264787421734,
          lat: 31.15395149031556,
          h: 12.178192986180326,
        },
        {
          lon: 121.12278546708409,
          lat: 31.153975342725264,
          h: 12.178415363887282,
        },
        {
          lon: 121.12281310059657,
          lat: 31.15385762853425,
          h: 12.178399877503464,
        },
        {
          lon: 121.1228576094918,
          lat: 31.15386519051712,
          h: 12.178394232107442,
        },
        {
          lon: 121.1228909000206,
          lat: 31.153723309251856,
          h: 12.17857353611858,
        },
        {
          lon: 121.12294578609598,
          lat: 31.153732796983615,
          h: 12.178675754028028,
        },
        {
          lon: 121.12298033312791,
          lat: 31.153585333373417,
          h: 12.17876227737616,
        },
        {
          lon: 121.1228480316718,
          lat: 31.15356239349922,
          h: 12.178326652099466,
        },
        {
          lon: 121.12283863696666,
          lat: 31.153602052352188,
          h: 12.178301731797035,
        },
        {
          lon: 121.12279132401528,
          lat: 31.153593731079162,
          h: 12.17821160134978,
        },
        {
          lon: 121.12280904366847,
          lat: 31.153517944755357,
          h: 12.178387628978598,
        },
        {
          lon: 121.12256003807408,
          lat: 31.15347475524662,
          h: 12.178108003497535,
        },
        {
          lon: 121.12255140331416,
          lat: 31.153510889388823,
          h: 12.178086221333002,
        },
        {
          lon: 121.12251427275822,
          lat: 31.153504509859477,
          h: 12.17756730102783,
        },
        { lon: 121.1224291079002, lat: 31.15386748647, h: 12.177529555001517 },
      ],
    };
  },
  components: {
    Tool: defineAsyncComponent(() => import("@/components2/Tool.vue")),
  },
  created() {},
  mounted() {
    let that = this;
    // this.clipboard = new Clipboard(".copy_info_dialog", {
    //   // 点击copy按钮，直接通过text直接返回复印的内容
    //   text: function () {
    //     return that.dialogInfoStr;
    //   },
    // });
    this.waterObj = new Water();
    window.controlCZ = this.controlCZ;
    this.$root.$.appContext.config.globalProperties.$flyTo = this.flyTo;
    this.initViewer().then(() => {
      this.mapConfig();
      // 默认视角
      this.setViewDefaultlocation().then(() => {
        that.mainFunc();
      });
    });
    window.getNowCameraPosition1 = this.getNowCameraPosition;
    window.getNowCameraPosition = function () {
      this.getNowCameraPosition().then((result) => {
        this.showInfoDailog(result.info);
      });
    };

    // window.addImage = this.addImage;
    // window.changeImage = this.changeImage;
    // addImage(globalVariable.viewer, {
    //   arr: [
    //     121.12273519090121, 31.153827313511016, 3.280499471365055,
    //     121.12273815983032, 31.153814774429165, 3.281036567079009,
    //   ],
    //   minH: [2.807028457880749, 2.807028457880749],
    // });
    // window.tp =
    // this.addImage(globalVariable.viewer, {
    //   arr: [
    //     121.12273519090121, 31.153826679130416, 3.280499471365055,
    //     121.12273833983032, 31.153813096263634, 3.281036567079009,
    //   ],
    //   minH: [2.807028457880749, 2.807028457880749]
    // }, '../static/images/ceshi.png');
    // changeImage(tp,'../static/images/jinru.png')

    // this.addImage(globalVariable.viewer, {
    //   arr: [
    //     121.12273884192843, 31.153811497621240, 3.2435919391164383,
    //     121.12274206014264, 31.153797613000965, 3.2321212783392600,
    //   ],
    //   minH: [2.8569308025328994, 2.8529680784118310]
    // }, '../static/images/ceshi.png');
    this.initJH();
    return;
  },

  methods: {
    consoleCameraPosition() {
      this.getNowCameraPosition().then((result) => {
        this.showInfoDailog(
          JSON.stringify(result.result).replaceAll("{", "").replaceAll("}", "")
        );
      });
    },

    initViewer() {
      return new Promise((resolve, reject) => {
        globalVariable.viewer = new Cesium.Viewer("cesiumContainer", {
          animation: false, // 是否创建动画小器件，左下角仪表
          baseLayerPicker: false, // 是否显示图层选择器
          fullscreenButton: false, // 是否显示全屏按钮
          vrButton: false, // 是否创建VRButton小工具
          geocoder: false, // 是否显示geocoder小器件，右上角查询按钮
          homeButton: false, // 是否显示Home按钮
          infoBox: false, // 是否显示信息框
          sceneModePicker: false, // 是否显示3D/2D选择器
          selectionIndicator: false, // 是否显示选取指示器组件
          timeline: false, // 是否显示时间轴
          navigationHelpButton: false, // 是否显示右上角的帮助按钮
          navigationInstructionsInitiallyVisible: false, // 如果导航指示最初应可见，则为True；如果用户明确单击按钮后才显示，则为false。
          scene3DOnly: true, // 如果设置为true，则所有几何图形以3D模式绘制以节约GPU资源
          shouldAnimate: false, // 默认情况下，如果时钟应尝试提前模拟时间，则为true，否则为false。此选项优先于设置
          clock: new Cesium.Clock(), // 用于控制当前时间的时钟对象
          clockViewModel: new Cesium.ClockViewModel(
            new Cesium.Clock({
              startTime: Cesium.JulianDate.fromIso8601("2023-03-14T22:30:14Z"),
              currentTime: Cesium.JulianDate.fromIso8601(
                "2023-03-14T22:31:14Z"
              ),
              stopTime: Cesium.JulianDate.fromIso8601("2023-03-15T10:19:14Z"),
              clockRange: Cesium.ClockRange.LOOP_STOP,
              clockStep: Cesium.ClockStep.SYSTEM_CLOCK_MULTIPLIER,
            })
          ), // 用于控制当前时间的时钟对象
          selectedImageryProviderViewModel: undefined, // 当前图像图层的显示模型，仅baseLayerPicker设为true有意义
          imageryProviderViewModels:
            Cesium.createDefaultImageryProviderViewModels(), // 可供BaseLayerPicker选择的图像图层ProviderViewModel数组
          selectedTerrainProviderViewModel: undefined, // 当前地形图层的显示模型，仅baseLayerPicker设为true有意义
          terrainProviderViewModels:
            Cesium.createDefaultTerrainProviderViewModels(), // 可供BaseLayerPicker选择的地形图层ProviderViewModel数组
          imageryProvider: new Cesium.SingleTileImageryProvider({
            url: (function createColorCanvas(color) {
              // 返回空白
              var width = 1,
                height = 1;
              var canvas = document.createElement("canvas");
              canvas.width = width;
              canvas.height = height;
              var ctx = canvas.getContext("2d");
              ctx.fillStyle = color;
              ctx.fillRect(0, 0, width, height);
              return canvas.toDataURL();
            })("#ffffff00"),
            rectangle: Cesium.Rectangle.fromDegrees(-180.0, -90.0, 180.0, 90.0),
          }), // 图像图层提供者，仅baseLayerPicker设为false有意义
          fullscreenElement: document.body, // 全屏时渲染的HTML元素,
          useDefaultRenderLoop: true, // 如果需要控制渲染循环，则设为true
          targetFrameRate: undefined, // 使用默认render loop时的帧率
          showRenderLoopErrors: false, // 如果设为true，将在一个HTML面板中显示错误信息
          automaticallyTrackDataSourceClocks: true, // 自动追踪最近添加的数据源的时钟设置
          sceneMode: Cesium.SceneMode.SCENE3D, // 初始场景模式
          mapProjection: new Cesium.WebMercatorProjection(), // 地图投影体系
          dataSources: new Cesium.DataSourceCollection(), // 需要进行可视化的数据源的集合
        });

        if (systemConfig.msaaSamples != 0) {
          globalVariable.viewer.scene.msaaSamples = systemConfig.msaaSamples;
        }
        //去除版权标记
        globalVariable.viewer._cesiumWidget._creditContainer.style.display =
          "none";
        resolve();
      });
    },

    mainFunc() {
      let that = this;
      // camera范围限制
      this.bindLimitCameraFunc();

      // 取消滑动事件
      this.controlCZ(systemConfig.mapControl);

      // 自定义滑动事件
      this.wetherScroll(this.changeCamera);

      window.bindLimitCameraFunc = this.bindLimitCameraFunc;
      window.unbindLimitCameraFunc = this.unbindLimitCameraFunc;

      // entity点击事件
      this.entityClickEvent();
      // // 键盘/地图点击事件
      // this.singleClick(viewer); // 地图点击
      this.singleClick2(); // 模型点击
      keyboardMapRoamingInit(globalVariable.viewer);

      let keyArr = Object.keys(systemConfig.tilesConfig);
      this.yanchiAdd3DTiles(0, keyArr);

      // for (let i = 0; i < keyArr.length; i++) {
      //   const str = keyArr[i];
      //   globalVariable.tilesArr[str] = this.add3DTilesData(
      //     systemConfig.dataUrl + str + "/tileset.json", //
      //     {
      //       light: systemConfig.tilesConfig[str].light,
      //     }
      //   );
      // }
      // window.changeImage = this.changeImage;

      // 水面加载
      setTimeout(() => {
        that.addWaterPanel();
      }, 10000);
    },

    yanchiAdd3DTiles(index, keyArr) {
      let that = this;
      if (index >= keyArr.length) return;
      const str = keyArr[index];
      globalVariable.tilesArr[str] = this.add3DTilesData(
        systemConfig.tilesConfig[str].dataUrl + str + "/tileset.json" //
        // {
        //   light: systemConfig.tilesConfig[str].light,
        // }
      );
      setTimeout(() => {
        that.yanchiAdd3DTiles(++index, keyArr);
      }, systemConfig.tilesConfig[str].yanchi);
    },

    // entity Click
    entityClickEvent() {
      let viewClickHandle = new Cesium.ScreenSpaceEventHandler(
        globalVariable.viewer.scene.canvas
      );
      viewClickHandle.setInputAction(function (evt) {
        var pickedObject = globalVariable.viewer.scene.pick(evt.position);
        if (pickedObject && pickedObject.id) {
          var clickMarkerId = pickedObject.id._id;
          if (globalVariable.point_positions[clickMarkerId]) {
            var data = globalVariable.point_positions[clickMarkerId];
            if (data.callback) {
              data.callback(data.infos);
            }
          }
        } else {
          return false;
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },

    changeCamera(direction) {
      switch (direction) {
        case "left":
          globalVariable.viewer.camera.lookLeft((Math.PI / 180) * 2);
          break;

        case "right":
          globalVariable.viewer.camera.lookRight((Math.PI / 180) * 2);
          break;

        default:
          break;
      }
    },

    wetherScroll(func) {
      let startX = 0;
      let endX = 0;
      let distanceX = 0;
      let container = document.getElementById("cesiumContainer");
      var clientWidth = document.documentElement.clientWidth;
      container.addEventListener("pointerdown", mousedown, false);
      container.addEventListener("pointerup", mouseup, false);
      function mousedown(event) {
        var touch = event;
        //滑动起点的坐标
        startX = touch.pageX;
        container.addEventListener("pointermove", mousemove);
      }
      function mousemove(event) {
        var touch = event;
        //手势滑动时，手势坐标不断变化，取最后一点的坐标为最终的终点坐标
        endX = touch.pageX;
        distanceX = endX - startX;
        if (startX != Math.abs(distanceX)) {
          //在滑动的距离超过屏幕高度的20%时，做某种操作
          if (Math.abs(distanceX) > clientWidth * 0.005) {
            //向下滑实行函数someAction1，向上滑实行函数someAction2
            //向左滑实行函数someAction1，向右滑实行函数someAction2
            distanceX > 0 ? func("left") : func("right");
            startX = endX;
          }
        }
      }
      function mouseup(event) {
        startX = 0;
        endX = 0;
        distanceX = 0;
        container.removeEventListener("pointermove", mousemove);
      }
    },

    // 禁用/开启 操作
    controlCZ(bool) {
      let screenSpaceCameraController =
        globalVariable.viewer.scene.screenSpaceCameraController;
      screenSpaceCameraController.enableLook = bool;
      screenSpaceCameraController.enableRotate = bool; // 禁止旋转
      screenSpaceCameraController.enableTilt = bool; // 禁止倾斜相机
      screenSpaceCameraController.enableTranslate = bool; // 禁止移动
      screenSpaceCameraController.enableZoom = bool; // 禁止缩放
    },

    // 默认定位
    setViewDefaultlocation() {
      return new Promise((resolve, reject) => {
        this.$flyTo({
          lon: systemConfig.mapDefault.center.lon,
          lat: systemConfig.mapDefault.center.lat,
          h: systemConfig.mapDefault.height,
          heading: systemConfig.mapDefault.heading,
          pitch: systemConfig.mapDefault.pitch,
          roll: systemConfig.mapDefault.roll,
          time: 1,
          pitchAdjustHeight: 1000,
          callback: null,
        }).then(() => {
          resolve();
        });
      });
    },

    flyTo(item) {
      return new Promise((resolve, reject) => {
        globalVariable.viewer.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(
            item.lon,
            item.lat,
            item.h
          ),
          orientation: {
            heading: Cesium.Math.toRadians(item.heading), // 方向
            pitch: Cesium.Math.toRadians(item.pitch), // 倾斜角度
            roll: Cesium.Math.toRadians(item.roll),
          },
          duration: isNaN(item.time) ? 2 : item.time,
          pitchAdjustHeight: item.pitchAdjustHeight || 1000,
          complete: function () {
            if (item) {
              if (item.callback) item.callback(item);
            }
            resolve();
          },
        });
      });
    },

    // cesium 球体配置
    mapConfig() {
      // 大气效果（发光）
      globalVariable.viewer.scene.globe.showGroundAtmosphere = false;
      // 是否将地球渲染为半透明的球体
      globalVariable.viewer.scene.globe.translucency.enabled = true;
      // 基础球体颜色
      globalVariable.viewer.scene.globe.baseColor = Cesium.Color.TRANSPARENT;
      // 地底颜色
      globalVariable.viewer.scene.globe.undergroundColor = undefined;

      // 开启场景光照
      globalVariable.viewer.scene.globe.enableLighting = true;
      // 控制太阳光
      globalVariable.viewer.scene.sun.show = false; // systemConfig.sunShow;
      // 控制阴影
      globalVariable.viewer.shadows = false; // systemConfig.shadows;
      // 阴影强度
      globalVariable.viewer.shadowMap.darkness = systemConfig.shadowMapDarkness;

      // globalVariable.viewer.terrainShadows = Cesium.ShadowMode.RECEIVE_ONLY;
      // // globalVariable.viewer.shadowMap.softShadows  = truee
      // globalVariable.viewer.shadowMap.darkness = 0.7; //阴影透明度--越大越透明
      if (systemConfig.DirectionalLightShow) {
        globalVariable.viewer.scene.light = new Cesium.DirectionalLight({
          color: new Cesium.Color(
            systemConfig.DirectionalLightColor.r,
            systemConfig.DirectionalLightColor.g,
            systemConfig.DirectionalLightColor.b,
            systemConfig.DirectionalLightColor.a
          ),
          // //去除时间原因影响模型颜色
          // direction: Cesium.Cartesian3.fromDegrees(
          //   121.1217914833498,
          //   31.154385387088624,
          //   2000
          // ),
          direction: new Cesium.Cartesian3(
            systemConfig.DirectionalLightDirection.x,
            systemConfig.DirectionalLightDirection.y,
            systemConfig.DirectionalLightDirection.z
          ),
          intensity: systemConfig.DirectionalLightIntensity,
        });
      }

      // globalVariable.viewer._cesiumWidget._supportsImageRenderingPixelated =
      //   Cesium.FeatureDetection.supportsImageRenderingPixelated();
      // globalVariable.viewer._cesiumWidget._forceResize = true;

      // 解决抗锯齿问题
      // // 方法一
      // if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
      //   //判断是否支持图像渲染像素化处理
      //   var vtxf_dpr = window.devicePixelRatio;
      //   // 适度降低分辨率
      //   while (vtxf_dpr >= 2.0) {
      //     vtxf_dpr /= 2.0;
      //   }
      //   //alert(dpr);
      //   globalVariable.viewer.resolutionScale = vtxf_dpr;
      // }
      // 方法二
      if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
        //判断是否支持图像渲染像素化处理
        var vtxf_dpr = window.devicePixelRatio;
        globalVariable.viewer.resolutionScale = vtxf_dpr;
      }

      // //是否开启抗锯齿
      globalVariable.viewer.scene.fxaa = systemConfig.fxaa;
      globalVariable.viewer.scene.postProcessStages.fxaa.enabled =
        systemConfig.fxaaEnabled;

      // // 天空盒隐藏
      // globalVariable.viewer.scene.skyBox.show = false;
      // 配置天空盒子
      this.deploySkyBox();
    },

    // 限制camera的移动范围
    bindLimitCameraFunc() {
      globalVariable.viewer.camera.changed.addEventListener(
        this.limitCameraFunc
      );
    },
    unbindLimitCameraFunc() {
      globalVariable.viewer.camera.changed.removeEventListener(
        this.limitCameraFunc
      );
    },
    limitCameraFunc() {
      let that = this;
      if (!this.correctCamera) {
        this.getNowCameraPosition()
          .then((result) => {
            let cameraLon = result.result.lon;
            let cameraLat = result.result.lat;
            let cameraHeight = result.result.h;
            if (
              cameraLon > systemConfig.mapDefault.bbox.east ||
              cameraLon < systemConfig.mapDefault.bbox.west ||
              cameraLat > systemConfig.mapDefault.bbox.north ||
              cameraLat < systemConfig.mapDefault.bbox.south ||
              cameraHeight > systemConfig.mapDefault.defaultH
            ) {
              that.correctCamera = true;
              that.setViewDefaultlocation().then(() => {
                huifu();
              });
            }
            cameraLon = null;
            cameraLat = null;
            cameraHeight = null;
          })
          .catch((err) => {});
      }
      function huifu() {
        that.correctCamera = false;
      }
    },

    // 配置天空盒
    deploySkyBox() {
      // 自定义的近地天空盒
      let groundSkybox = new Cesium.GroundSkyBox({
        sources: {
          negativeX: "./static/images/skybox/Left.jpg",
          negativeY: "./static/images/skybox/Front.jpg",
          negativeZ: "./static/images/skybox/Down.jpg",

          positiveX: "./static/images/skybox/Right.jpg",
          positiveY: "./static/images/skybox/Back.jpg",
          positiveZ: "./static/images/skybox/Up.jpg",
        },
      });

      // // 自带的默认天空盒
      // let defaultSkybox = viewer.scene.skyBox;

      globalVariable.viewer.scene.skyBox = groundSkybox;
      globalVariable.viewer.scene.skyAtmosphere.show = false;
    },

    // 获取当前camera的详细位置
    getNowCameraPosition() {
      return new Promise((resolve, reject) => {
        var camera = globalVariable.viewer.camera;
        var heading = Cesium.Math.toDegrees(
          globalVariable.viewer.camera.heading
        );
        var pitch = Cesium.Math.toDegrees(globalVariable.viewer.camera.pitch); //Cesium.Math.toDegrees作用是把弧度转换成度数
        var roll = Cesium.Math.toDegrees(globalVariable.viewer.camera.roll);
        var h = globalVariable.viewer.camera.positionCartographic.height;
        var camera = globalVariable.viewer.camera.position;
        var position = Cesium.Cartographic.fromCartesian(camera);
        var lon = Cesium.Math.toDegrees(position.longitude);
        var lat = Cesium.Math.toDegrees(position.latitude);
        resolve({
          str: "",
          result: {
            lon: lon,
            lat: lat,
            h: h,
            heading: heading,
            pitch: pitch,
            roll: roll,
          },
        });
      });

      // that.showInfoDailog(str);
    },

    // 地图（地球表面，无地形）左击事件
    singleClick() {
      var handler = new Cesium.ScreenSpaceEventHandler(
        globalVariable.viewer.scene.canvas
      );
      handler.setInputAction(function (event) {
        var earthPosition = globalVariable.viewer.camera.pickEllipsoid(
          event.position,
          globalVariable.viewer.scene.globe.ellipsoid
        );
        var cartographic = Cesium.Cartographic.fromCartesian(
          earthPosition,
          globalVariable.viewer.scene.globe.ellipsoid,
          new Cesium.Cartographic()
        );
        var lat = Cesium.Math.toDegrees(cartographic.latitude);
        var lng = Cesium.Math.toDegrees(cartographic.longitude);
        var height = cartographic.height;
        console.log(lng + "," + lat);
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },

    // 地图（模型上）左击事件
    singleClick2() {
      let that = this;
      var handler = new Cesium.ScreenSpaceEventHandler(
        globalVariable.viewer.scene.canvas
      );
      handler.setInputAction(function (event) {
        var pick = globalVariable.viewer.scene.pickPosition(event.position);
        var pickModel = globalVariable.viewer.scene.pick(event.position);
        if (pickModel && pick && !pickModel.id) {
          var height = Cesium.Cartographic.fromCartesian(pick).height;
          var lat = Cesium.Math.toDegrees(
            Cesium.Cartographic.fromCartesian(pick).latitude
          );
          var lon = Cesium.Math.toDegrees(
            Cesium.Cartographic.fromCartesian(pick).longitude
          );
          // cartesian = Cesium.Cartesian3.fromDegrees(lng, lat, height);
          // console.log("模型高度点", cartesian);
          let str = `
          lon:${lon},
          lat:${lat},
          height:${height}
          `;
          console.log(str);
          that.showInfoDailog(
            JSON.stringify({
              lon: lon,
              lat: lat,
              h: height,
            })
              .replaceAll("{", "")
              .replaceAll("}", "")
          );
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },

    initJH() {
      let that = this;
      window.getToken = function () {
        return that.$store.getters.getToken;
      };
      this.getToken().then(() => {
        serviceWindow.map(function (item, index) {
          let pointArr = item.topPoint
            .map(function (item_) {
              return [item_.lon, item_.lat, item_.height];
            })
            .join()
            .split(",")
            .map((num) => Number(num));
          that.getWindowInfo(item).then((info) => {
            let image = that.createJHImage(item, info);
            let entity = globalVariable.viewer.entities.add({
              wall: {
                positions: Cesium.Cartesian3.fromDegreesArrayHeights(pointArr),
                minimumHeights: item.endHeight,
                material: new Cesium.ImageMaterialProperty({
                  image: image,
                  transparent: true,
                }),
              },
            });
            that.JHEntityObj[item.id] = {
              item: item,
              entity: entity,
            };
          });
        });
      });

      // 开始循环访问
      setInterval(() => {
        that.loopJH();
      }, 5000); //3 * 60 * 1000
    },
    getToken() {
      let that = this;
      return new Promise((resolve, reject) => {
        api.getToken().then(function (result) {
          that.$store.commit("setToken", result.data);
          resolve();
        });
      });
    },
    getWindowInfo(params) {
      return new Promise((resolve, reject) => {
        api.getWindowInfo({ id: params.id }).then(function (result) {
          resolve(result.data);
        });
      });
    },
    createJHImage(item, info) {
      // win_code: "A02",
      // win_id: "102",
      // area_id: "310000310100310118001",
      // win_status: "STOP",
      // user_code: "742",
      // user_name: "谢晨 ",
      // ticket_uuid: "",
      // ticket_code: "",
      let width = 300,
        height = 100;
      var canvas = document.createElement("canvas");
      canvas.width = 300;
      canvas.height = 100;
      var ctx = canvas.getContext("2d");
      ctx.clearRect(0, 0, width, height);

      ctx.fillStyle = "#000000";
      ctx.fillRect(0, 0, width, height);

      ctx.fillStyle = "#FF0000";
      ctx.font = "30px Arial";
      // ctx.fillText(item.id, 15, 60);
      ctx.fillText(info.win_code, 15, 60);

      ctx.fillStyle = "#FF0000";
      ctx.beginPath();
      ctx.lineWidth = "2";
      ctx.strokeStyle = "#FF0000"; // Green path
      ctx.moveTo(83, 10);
      ctx.lineTo(83, 90);
      ctx.stroke(); // Draw it

      ctx.fillStyle = "#FF0000";
      ctx.font = "30px Arial";
      ctx.fillText(item.name, 100, 37);

      if (info.win_status == "STOP") {
        ctx.fillStyle = "#FF0000";
        ctx.font = "30px Arial";
        ctx.fillText("暂停服务", 116, 83);
      } else {
        if (info.ticket_code == "") {
          ctx.fillStyle = "#FF0000";
          ctx.font = "30px Arial";
          ctx.fillText("欢迎光临", 116, 83);
        } else {
          ctx.fillStyle = "#FF0000";
          ctx.font = "30px Arial";
          ctx.fillText("请" + info.ticket_code + "号", 116, 83);
        }
      }

      return canvas.toDataURL("image/png");
    },
    loopJH() {
      let that = this;
      this.getToken().then(() => {
        let arr = Object.getOwnPropertyNames(that.JHEntityObj);
        arr.map(function (index) {
          let obj = that.JHEntityObj[index];
          let item = obj.item;
          that.getWindowInfo(obj.item).then((info) => {
            let image = that.createJHImage(item, info);
            obj.entity.wall.material = new Cesium.ImageMaterialProperty({
              image: image,
              transparent: true,
            });
          });
        });
      });
    },

    // 地图添加图片
    addImage(viewer, pObj, imgUrl) {
      // // 顺时针
      // let pObj = {
      //   arr: [
      //     121.12273519090121, 31.153826679130416, 3.280499471365055,
      //     121.12273833983032, 31.153813096263634, 3.281036567079009,
      //   ],
      //   minH: [2.807028457880749, 2.807028457880749],
      // };
      // let imgUrl = '../static/images/ceshi.png';

      // let material = Cesium.Material.fromType("Image");
      // material.uniforms.image = imgUrl;
      return new Promise((resolve, reject) => {
        let instance = new Cesium.GeometryInstance({
          geometry: new Cesium.WallGeometry({
            positions: Cesium.Cartesian3.fromDegreesArrayHeights(pObj.arr),
            minimumHeights: pObj.minH,
          }),
        });

        new Cesium.createDynamicImage({
          imageWidth: 500,
          imageHeight: 200,
          canvasWidth: 500,
          canvasHeight: 200,
          period: 10,
          text: "税务综合受理",
          textStyle: "normal bold 40pt 宋体",
        }).then((result) => {
          // let material = Cesium.Material.fromType("Image");
          // material.uniforms.image = result;
          // 使用抽象的Primitive而不是RectanglePrimitive

          // let wallPrimitive = new Cesium.Primitive({
          //   geometryInstances: instance,
          //   appearance: new Cesium.MaterialAppearance({
          //     material: material,
          //     faceForward: true,
          //   }),
          // });
          // viewer.scene.primitives.add(wallPrimitive);

          viewer.entities.add({
            wall: {
              positions: Cesium.Cartesian3.fromDegreesArrayHeights(pObj.arr),
              minimumHeights: pObj.minH,
              material: result,
            },
          });
        });
      });

      // return item;
    },

    changeImage(primitiveObj, imgUrl) {
      let material = Cesium.Material.fromType("Image");
      material.uniforms.image = imgUrl;
      primitiveObj.appearance = new Cesium.MaterialAppearance({
        material: material,
        faceForward: true,
      });
    },

    showInfoDailog(str) {
      this.dialogVisible = true;
      this.dialogInfoStr = str;
    },
    hideInfoDailog() {
      this.dialogVisible = false;
    },

    // 添加水面
    addWaterPanel() {
      let d = [];
      for (let i = 0; i < systemConfig.water.length; i += 2) {
        let x = systemConfig.water[i];
        let y = systemConfig.water[i + 1];
        d.push(x);
        d.push(y);
        d.push(1);
      }

      let geometry = new Cesium.PolygonGeometry({
        polygonHierarchy: new Cesium.PolygonHierarchy(
          Cesium.Cartesian3.fromRadiansArrayHeights(d)
        ),
        height: -2,
      });

      let waterFace = this.waterObj.create(geometry, {
        // normalMap: "img/textures/waterNormals.jpg", // 水正常扰动的法线图
        frequency: 8000.0, // 控制波数的数字。
        animationSpeed: 0.02, // 控制水的动画速度的数字。
        amplitude: 5.0, // 控制水波振幅的数字。
        specularIntensity: 0.8, // 控制镜面反射强度的数字。
        baseWaterColor: "#006ab4", // rgba颜色对象基础颜色的水。#00ffff,#00baff,#006ab4
        blendColor: "#006ab4", // 从水中混合到非水域时使用的rgba颜色对象。
        // height: 100, //水面高度
        clampToGround: true, //是否贴地
        opacity: 0.7, //透明度
      });
      globalVariable.viewer.scene.primitives.add(waterFace);
    },

    // 加载3DTiles数据
    add3DTilesData(url, options) {
      if (!options) {
        options = {
          show: true,
          // light: 1,
          matrix: null,
        };
      } else {
        options.show = typeof options.show == "boolean" ? options.show : true;
        // options.light = isNaN(options.light) ? 1 : options.light;
      }

      let that = this;
      let tileset = new Cesium.Cesium3DTileset({
        url: url,
        show: options.show,
      });

      globalVariable.viewer.scene.primitives.add(tileset);

      tileset.readyPromise.then(function () {
        if (options.matrix)
          tileset.root.transform = that.createMatrix4(options.matrix);

        tileset.style = {
          color: {
            conditions: [["true", "rgba(0, 0, 0, 0.3)"]],
          },
        };
      });
      return tileset;
    },

    // 创建偏移矩阵
    createMatrix4(matrixParam, defaultModelMatrix) {
      let tileModelTool = matrixParam;
      var mx = Cesium.Matrix3.fromRotationX(
        Cesium.Math.toRadians(tileModelTool.rx)
      );
      var my = Cesium.Matrix3.fromRotationY(
        Cesium.Math.toRadians(tileModelTool.ry)
      );
      var mz = Cesium.Matrix3.fromRotationZ(
        Cesium.Math.toRadians(tileModelTool.rz)
      );
      var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);
      var rotationY = Cesium.Matrix4.fromRotationTranslation(my);
      var rotationZ = Cesium.Matrix4.fromRotationTranslation(mz);
      var m;
      if (defaultModelMatrix) {
        m = defaultModelMatrix;
      } else {
        //平移 修改经纬度
        var position = Cesium.Cartesian3.fromDegrees(
          tileModelTool.longitude,
          tileModelTool.latitude,
          tileModelTool.height
        );
        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(tileModelTool.scale);
      Cesium.Matrix4.multiply(m, scale, m);
      return m;
    },
  },
};
</script>

<style lang="less" scoped>
.viewer_container {
  width: 100%;
  height: 100%;
  #cesiumContainer {
    width: 100%;
    height: 100%;

    .get_now_camera_view {
      position: absolute;
      z-index: 1;
    }
  }
  #canvas-b {
    position: absolute;
    top: 0px;
    left: 0px;
    display: none;
  }
}
</style>