<template>
  <div class="cesium_div" id="cesium_id"></div>
  <el-radio-group class="choose" v-model="radio" @change="changeRadio">
    <el-radio
      v-for="(item, index) in effect"
      :key="index"
      :label="item.label"
      >{{ item.name }}</el-radio
    >
  </el-radio-group>
  <el-switch
    v-model="value1"
    @change="changeSwitch"
    class="switch"
    active-text="上海中心大厦"
    inactive-text="室内模型"
  />
</template>

<script>
export default {
  name: "SHLJZ",
  props: {
    msg: String,
  },
  data() {
    return {
      topK: systemConfig.flyLine,
      radio: 0,
      value1: true,
      radius: 1800,
      effect: [
        {
          name: "无",
          label: 0,
        },
        {
          name: "雨",
          label: 1,
        },
        {
          name: "雪",
          label: 2,
        },
        {
          name: "雾",
          label: 3,
        },
      ],
    };
  },
  methods: {},
  mounted() {
    let that = this;
    let viewer = new Cesium.Viewer("cesium_id", {
      shouldAnimate: true,
      animation: false, //动画控制不显示
      timeline: false, //时间线不显示
      fullscreenButton: false, //全屏按钮不显示
      infoBox: false,
      baseLayerPicker: false, //地图切换不显示
      imageryProvider: new Cesium.SingleTileImageryProvider({
        url: (function createColorCanvas(color) {
          let width = 1,
            height = 1;
          let canvas = document.createElement("canvas");
          canvas.width = width;
          canvas.height = height;
          let 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),
      }),
      geocoder: false,
      homeButton: false,
      selectionIndicator: false, // 去除绿色选择框
      sceneModePicker: false,
      navigationHelpButton: false,
      scene3DOnly: true, // 仅以3D渲染以节省GPU内存
      useBrowserRecommendedResolution: true, // 以浏览器建议的分辨率渲染
    });

    globalVariable.viewer = viewer;

    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(
        121.49254337380488,
        31.219286378124917,
        631.5765993791605
      ),
      orientation: {
        heading: Cesium.Math.toRadians(30.69861679518457),
        pitch: Cesium.Math.toRadians(-12.45131041368068),
        roll: 0.0,
      },
    });

    //去除版权标记
    viewer._cesiumWidget._creditContainer.style.display = "none";

    // 关闭太原光
    // viewer.scene.sun.show = true;
    // 开启阴影
    // viewer.shadows = true;
    // 阴影强度
    // viewer.shadowMap.darkness = 0.65;

    this.initMap(viewer);

    this.addEffect(viewer);

    // 白膜
    let shBmTileset = this.add3DTiles(
      viewer,
      systemConfig.server.lujiazui,
      false
    );
    shBmTileset.readyPromise.then(function (tileset) {
      tileset.style = new Cesium.Cesium3DTileStyle({
        color: {
          conditions: [
            ["true", "color('rgb(33,76,142)',0.7)"], //135,206,250    51, 153, 255
          ],
        },
      });
      that.panyi(tileset);
    });
    shBmTileset.customShader = new Cesium.CustomShader({
      lightingModel: Cesium.LightingModel.UNLIT,
      fragmentShaderText: `
      void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
            float _baseHeight = 0.0; // 物体的基础高度，需要修改成一个合适的建筑基础高度
            float _heightRange = 50.0; // 高亮的范围(_baseHeight ~ _baseHeight + _      heightRange) 默认是 0-60米
            float _glowRange = 300.0; // 光环的移动范围(高度)
    
            vec3 position = fsInput.attributes.positionMC;
    
            float vtxf_height = position.y-_baseHeight;
            float vtxf_a11 = fract(czm_frameNumber / 120.0) * 3.14159265 * 2.0;
            float vtxf_a12 = vtxf_height / _heightRange + vtxf_a11 * 0.1;
            material.diffuse*= vec3(vtxf_a12, vtxf_a12, vtxf_a12);
    
            float time = fract(czm_frameNumber / 1000.0);
            time = abs(time - 0.5) * 1.2;
            float diff = step(0.005, abs(clamp(position.y / _glowRange, 0.0, 1.0) - time));
            material.diffuse += material.diffuse * (1.0 - diff);
          }
      `,
    });

    // 张金雨建模  外
    let shzxZJYTileset_N = this.add3DTiles(
      viewer,
      systemConfig.server.shzxZJY_wai,
      false
    );
    this.shzxZJYTileset_N = shzxZJYTileset_N;
    shzxZJYTileset_N.readyPromise.then(function (tileset) {
      tileset.style = new Cesium.Cesium3DTileStyle({
        color: {
          conditions: [
            // ["true", "color('rgb(0,255,255)',0.6)"]//135,206,250    51, 153, 255
            ["true", "color('rgb(0,252,255)',0.8)"], //135,206,250    51, 153, 255
          ],
        },
      });
      that.panyi(tileset);
    });
    shzxZJYTileset_N.customShader = new Cesium.CustomShader({
      lightingModel: Cesium.LightingModel.UNLIT,
      varyings: {
        v_normalMC: Cesium.VaryingType.VEC3,
      },
      vertexShaderText: `
    void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
      v_normalMC = vsInput.attributes.normalMC;
    }
    `,
      fragmentShaderText: `
  void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
        float _baseHeight = 0.0; // 物体的基础高度，需要修改成一个合适的建筑基础高度
        float _heightRange = 200.0; // 高亮的范围(_baseHeight ~ _baseHeight + _      heightRange) 默认是 0-60米
        float _glowRange = 600.0; // 光环的移动范围(高度)

        vec3 position = fsInput.attributes.positionMC;

        float vtxf_height = position.y-_baseHeight;
        float vtxf_a11 = fract(czm_frameNumber / 300.0) * 3.14159265 * 0.8;
        // float vtxf_a12 = vtxf_height / _heightRange + sin(vtxf_a11) * 0.5;
        float vtxf_a12 = vtxf_height / _heightRange + vtxf_a11 * 0.8;
        material.diffuse*= vec3(vtxf_a12, vtxf_a12, vtxf_a12);


        float time = fract(czm_frameNumber / 2000.0);
        time = abs(time - 0.5) * 2.0;
        float diff = step(0.03, abs(clamp(position.y / _glowRange, 0.0, 1.0) - time ));
        float diff2 = step(0.03, abs(clamp(position.y / _glowRange, 0.0, 1.0) - fract(time + 0.25 )));
        float diff3 = step(0.03, abs(clamp(position.y / _glowRange, 0.0, 1.0) - fract(time + 0.5 )) );
        float diff4 = step(0.03, abs(clamp(position.y / _glowRange, 0.0, 1.0) - fract(time + 0.75)));
        material.diffuse += material.diffuse * (1.0 - (diff * diff2 * diff3 * diff4)) * (1.0 - v_normalMC.y) * 10.0;

      }
  `,
    });
    // 张金雨建模  内
    let shzxZJYTileset_W = this.add3DTiles(
      viewer,
      systemConfig.server.shzxZJY_nei,
      false
    );
    this.shzxZJYTileset_W = shzxZJYTileset_W;
    shzxZJYTileset_W.readyPromise.then(function (tileset) {
      that.panyi(tileset);
    });

    // // 重要建筑
    // let mainBuildTileset = this.add3DTiles(
    //   viewer,
    //   systemConfig.server.mainBuild,
    //   false
    // );
    // this.mainBuildTileset = mainBuildTileset;
    // mainBuildTileset.readyPromise.then(function (tileset) {
    //   // tileset.modelMatrix = that.createMatrix4({
    //   //   longitude: 121.4983784,
    //   //   latitude: 31.2392238,
    //   //   height: 0,
    //   //   rx: 0,
    //   //   ry: 0,
    //   //   rz: 0,
    //   // });

    //   // // 偏移
    //   // //笛卡尔转换为弧度
    //   // var cartographic = Cesium.Cartographic.fromCartesian(
    //   //   tileset.boundingSphere.center
    //   // );
    //   // var lng = Cesium.Math.toDegrees(cartographic.longitude); //使用经纬度和弧度的转换，将WGS84弧度坐标系转换到目标值，弧度转度
    //   // var lat = Cesium.Math.toDegrees(cartographic.latitude);
    //   // var height = cartographic.height;
    //   // //计算中心点位置的地表坐标
    //   // var surface = Cesium.Cartesian3.fromDegrees(lng, lat, height);
    //   // const m = Cesium.Transforms.eastNorthUpToFixedFrame(surface);
    //   // const tempTranslation = new Cesium.Cartesian3(2000, 2000, 0);
    //   // const offset = Cesium.Matrix4.multiplyByPoint(
    //   //   m,
    //   //   tempTranslation,
    //   //   new Cesium.Cartesian3(0, 0, 0)
    //   // );
    //   // const translation = Cesium.Cartesian3.subtract(
    //   //   offset,
    //   //   surface,
    //   //   new Cesium.Cartesian3()
    //   // );
    //   // tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);

    //   // //偏移后的坐标
    //   // // var offset = Cesium.Cartesian3.fromDegrees(lng + 0.0045, lat - 0.002, 0);
    //   // // var offset = Cesium.Cartesian3.fromDegrees(
    //   // //   121.4983784, // + 0.0045,
    //   // //   31.2392238, // - 0.002,
    //   // //   0
    //   // // );
    //   // // var translation = Cesium.Cartesian3.subtract(
    //   // //   offset,
    //   // //   surface,
    //   // //   new Cesium.Cartesian3()
    //   // // );
    //   // // tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
    //   // return;

    //   var transformPosition = Cesium.Cartesian3.fromDegrees(
    //     121.4983784 + 0.0045,
    //     31.2392238 - 0.002,
    //     0
    //   );
    //   var matrix = Cesium.Transforms.eastNorthUpToFixedFrame(transformPosition);
    //   var scale = Cesium.Matrix4.fromUniformScale(1);
    //   Cesium.Matrix4.multiply(matrix, scale, matrix);

    //   var rotationX = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(0));
    //   var rotationY = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(0));
    //   var rotationZ = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(8));
    //   var rotationTranslationX =
    //     Cesium.Matrix4.fromRotationTranslation(rotationX);
    //   var rotationTranslationY =
    //     Cesium.Matrix4.fromRotationTranslation(rotationY);
    //   var rotationTranslationZ =
    //     Cesium.Matrix4.fromRotationTranslation(rotationZ);
    //   Cesium.Matrix4.multiply(matrix, rotationTranslationX, matrix);
    //   Cesium.Matrix4.multiply(matrix, rotationTranslationY, matrix);
    //   Cesium.Matrix4.multiply(matrix, rotationTranslationZ, matrix);

    //   tileset._root.transform = matrix;

    //   // viewer.zoomTo(mainBuildTileset);
    // });

    // BIM 建模
    let bimTileset = this.add3DTiles(viewer, systemConfig.server.bim, false);
    this.bimTileset = bimTileset;
    bimTileset.readyPromise.then(function (tileset) {
      bimTileset.show = false;

      // 偏移
      //笛卡尔转换为弧度
      var cartographic = Cesium.Cartographic.fromCartesian(
        tileset.boundingSphere.center
      );
      var lng = Cesium.Math.toDegrees(cartographic.longitude); //使用经纬度和弧度的转换，将WGS84弧度坐标系转换到目标值，弧度转度
      var lat = Cesium.Math.toDegrees(cartographic.latitude);
      var height = cartographic.height;
      //计算中心点位置的地表坐标
      var surface = Cesium.Cartesian3.fromDegrees(lng, lat, height);
      //偏移后的坐标
      var offset = Cesium.Cartesian3.fromDegrees(
        lng + 0.0039,
        lat - 0.0021,
        height
      );
      // m = Cesium.Transforms.eastNorthUpToFixedFrame(offset);
      var translation = Cesium.Cartesian3.subtract(
        offset,
        surface,
        new Cesium.Cartesian3()
      );

      let m = Cesium.Matrix4.fromTranslation(translation);
      tileset.modelMatrix = m;
      // viewer.zoomTo(bimTileset);
    });

    // // 上海中心大厦
    // this.shZxTileset = this.add3DTiles(viewer, systemConfig.server.shzx, false);
    // shZxTileset.readyPromise.then(function (tileset) {
    //   that.panyi(tileset);
    // });

    // // 自定义光源
    // let customShaderAAA = new Cesium.CustomShader({
    //   lightingModel: Cesium.LightingModel.UNLIT,
    //   uniforms: {
    //     u_cameraDirectionWC: {
    //       type: Cesium.UniformType.VEC3,
    //       value: viewer.scene.camera.positionWC,
    //     },
    //     u_lightColor1: {
    //       type: Cesium.UniformType.VEC4,
    //       value: new Cesium.Cartesian4(248/255, 0/255, 0/255, 0),
    //     },
    //     u_lightPos1: {
    //       type: Cesium.UniformType.VEC3,
    //       // 大门头顶
    //       value: Cesium.Cartesian3.fromRadians(
    //               2.120596229847432,
    //               0.5451633778904422,
    //               500,
    //       ),
    //       // 一楼门厅
    //       // value: Cesium.Cartesian3.fromRadians(
    //       //         2.113987467160011,
    //       //         0.5437379383404595,
    //       //         2,
    //       // ),
    //       // 门口室外
    //       // value: Cesium.Cartesian3.fromDegrees(
    //       // 121.122485613095,
    //       // 31.1542436101541,
    //       // 10.649243861995
    //       // ),
    //     },
    //     // u_lightColor2: {
    //     //   type: Cesium.UniformType.VEC4,
    //     //   value: new Cesium.Cartesian4(0.2, 0.8, 0.2, 0.2),
    //     // },
    //     // u_lightPos2: {
    //     //   type: Cesium.UniformType.VEC3,
    //     //   value: Cesium.Cartesian3.fromRadians(
    //     //           3.1001573234522195,
    //     //           0.5437380338095784,
    //     //           2.1
    //     //   ),
    //     // },
    //     // u_lightColor3: {
    //     //   type: Cesium.UniformType.VEC4,
    //     //   value: lightPoint3.color,
    //     // },
    //     // u_lightPos3: {
    //     //   type: Cesium.UniformType.VEC3,
    //     //   value: lightPoint3.postion,
    //     // },
    //   },
    //   fragmentShaderText: `
    //     vec4 makeLight(vec4 lightColorHdr,vec3 lightPos,
    //       vec3 positionWC,vec3 positionEC,vec3 normalEC,czm_pbrParameters pbrParameters)
    //     {
    //       vec3 color = vec3(0.0);
    //       float mx1 = 1.0;
    //       vec3 light1Dir = positionWC - lightPos;
    //       float distance1 = length(light1Dir);
    //       if(distance1 < 300.0){
    //         vec4 l1 = czm_view * vec4(lightPos, 1.0);
    //         vec3 lightDirectionEC = l1.xyz - positionEC;
    //         mx1 = 1.0 - distance1 / 300.0;
    //         color = czm_pbrLighting(
    //           positionEC,
    //           normalEC,
    //           lightDirectionEC,
    //           lightColorHdr.xyz,
    //           pbrParameters
    //         ).xyz;
    //       }
    //       mx1 = max(color.r,max(color.g,color.b)) * pow(mx1,1.0) * 10.0;
    //       return vec4(color,mx1);
    //     }
    //     void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material)
    //     {
    //       // material.diffuse = vec3(1.0);
    //       vec3 positionWC = fsInput.attributes.positionWC;
    //       vec3 normalEC = fsInput.attributes.normalEC;
    //       vec3 positionEC = fsInput.attributes.positionEC;
    //       vec3 lightColorHdr = czm_lightColorHdr;
    //       vec3 lightDirectionEC = czm_lightDirectionEC;
    //       lightDirectionEC = (czm_view * vec4(u_cameraDirectionWC,1.0)).xyz - positionEC;

    //       czm_pbrParameters pbrParameters;
    //       pbrParameters.diffuseColor = material.diffuse;
    //       pbrParameters.f0 = vec3(0.5);
    //       pbrParameters.roughness = 1.0;

    //       vec3 ligth1Color0 = czm_pbrLighting(
    //         positionEC,
    //         normalEC,
    //         lightDirectionEC,
    //         lightColorHdr,
    //         pbrParameters
    //       );

    //       vec4 ligth1ColorR = makeLight(u_lightColor1,u_lightPos1,positionWC,positionEC,normalEC,pbrParameters);
    //       // vec4 ligth1ColorG = makeLight(u_lightColor2,u_lightPos2,positionWC,positionEC,normalEC,pbrParameters);

    //       vec3 finalColor = mix(material.diffuse.rgb, ligth1ColorR.rgb, ligth1ColorR.a);
    //       // finalColor = mix(finalColor, ligth1ColorG.rgb, ligth1ColorG.a);

    //       material.diffuse = finalColor;
    //       // material.ambient = finalColor;
    //     }
    //     `,
    // });
    // shZxTileset.customShader = customShaderAAA;

    this.singleClick();
    // this.addFlyLine();
    // // 正多边形扩散
    // WallRegularDiffuse(viewer, systemConfig.WallRegularDiffuseObj);
    // 随机竖直飞线
    lineFlowInit(viewer, systemConfig.lineFlowObj);
    // 中心扩散
    this.addCircle(viewer);
  },
  methods: {
    changeRadio(label) {
      switch (label) {
        case 0:
          this.rain.show(false);
          this.snow.show(false);
          this.fog.show(false);
          break;
        case 1:
          this.rain.show(true);
          this.snow.show(false);
          this.fog.show(false);
          break;
        case 2:
          this.rain.show(false);
          this.snow.show(true);
          this.fog.show(false);
          break;
        case 3:
          this.rain.show(false);
          this.snow.show(false);
          this.fog.show(true);
          break;

        default:
          break;
      }
    },

    changeSwitch(val) {
      // this.mainBuildTileset.show = val;
      this.shzxZJYTileset_N.show = val
      this.shzxZJYTileset_W.show = val

      this.bimTileset.show = !val;
    },

    initMap(viewer) {
      // // 加载天地图影像
      // viewer.imageryLayers.addImageryProvider(
      //         new Cesium.WebMapTileServiceImageryProvider({
      //           url: "http://t{s}.tianditu.gov.cn/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&tk=" +
      //                   systemConfig.tdt_tk,
      //           layer: "img",
      //           style: "default",
      //           tileMatrixSetID: "w",
      //           format: "image/jpeg",
      //           subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
      //           tileMatrixSetID: "GoogleMapsCompatible",
      //           show: true,
      //           minimumLevel: 1,
      //           maximumLevel: 18,
      //         })
      // );
      // //加载影像注记
      // viewer.imageryLayers.addImageryProvider(
      //         new Cesium.WebMapTileServiceImageryProvider({
      //           url: "http://t{s}.tianditu.gov.cn/cia_w/wmts?tk=" + systemConfig.tdt_tk,
      //           layer: "cia",
      //           style: "default",
      //           tileMatrixSetID: "w",
      //           format: "tiles",
      //           subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
      //           maximumLevel: 20,
      //         })
      // );
      // 加载黑夜底图
      viewer.imageryLayers.addImageryProvider(
        new Cesium.ArcGisMapServerImageryProvider({
          // url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer",
          url: "http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer",
        })
      );

      // viewer.imageryLayers.addImageryProvider(
      //   new Cesium.ArcGisMapServerImageryProvider({
      //     // url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer",
      //     url: "http://121.43.55.7:10011/proxy/?servertype=World_Imagery&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlSWQiOiIyLDIwLDEyLDQsMCIsImV4cCI6MTY2NjMzMzcwNywidXNlcklkIjoyMiwidXNlcm5hbWUiOiJ1c2VyX3Rlc3QxIn0.-wYyW-HiEfZGqrVn8X4LC7rH8DFLSVjhcIIKWX-Kriw",
      //   })
      // );
    },

    addEffect(viewer) {
      this.rain = new Cesium.RainEffect(viewer, {
        speed: 5,
        size: 40,
        direction: 0,
        enabled: false,
      });
      this.snow = new Cesium.SnowEffect(viewer, {
        speed: 15,
        size: 1000,
        direction: 0,
        enabled: false,
      });
      this.fog = new Cesium.FogEffect(viewer, {
        fogByDistance: new Cesium.Cartesian4(10, 0.0, 1000, 0.5),
        maxHeight: 9000,
        color: Cesium.Color.WHITE,
        enabled: false,
      });
    },

    add3DTiles(viewer, url, flyto) {
      let tileset = new Cesium.Cesium3DTileset({
        url: url + "/tileset.json",
        skipLevelOfDetail: true, //开启跳级加载
        maximumScreenSpaceError: 16,
        maximumNumberOfLoadedTiles: 2000,
        maximumMemoryUsage: 512, //tileset可以使用的最大内存
        show: true,
        immediatelyLoadDesiredLevelOfDetail: true,
        // showOutLine : true, // 是否使用 CESIUM_primitive_outline 扩展显示模型的轮廓。为 true 时，将显示轮廓。如果为 false，则不显示轮廓。
        // debugColorizeTiles : true, // 仅用于调试。如果为 true，则为每个图块分配随机颜色。
        // debugShowBoundingVolume : true, // 仅用于调试。如果为 true，则为每个图块渲染边界体积。
        // debugShowContentBoundingVolume : true, // 仅用于调试。如果为 true，则为每个图块的内容渲染边界体积。
        // lightColor : new Cesium.Cartesian3(100.0,100.0, 100.0),  // 调整模型亮度
      });
      viewer.scene.primitives.add(tileset);

      // tileset.readyPromise.then(function () {
      //   if (flyto) viewer.zoomTo(tileset);
      // });

      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;
    },

    panyi(tileset) {
      // 偏移
      //笛卡尔转换为弧度
      var cartographic = Cesium.Cartographic.fromCartesian(
        tileset.boundingSphere.center
      );
      var lng = Cesium.Math.toDegrees(cartographic.longitude); //使用经纬度和弧度的转换，将WGS84弧度坐标系转换到目标值，弧度转度
      var lat = Cesium.Math.toDegrees(cartographic.latitude);
      //计算中心点位置的地表坐标
      var surface = Cesium.Cartesian3.fromDegrees(lng, lat, 0.0);
      //偏移后的坐标
      var offset = Cesium.Cartesian3.fromDegrees(lng + 0.0045, lat - 0.002, 0);
      var translation = Cesium.Cartesian3.subtract(
        offset,
        surface,
        new Cesium.Cartesian3()
      );
      tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
    },

    addCircle(viewer) {
      let that = this;
      let multiS = 1;
      let circleFirst3 = viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(
          121.50564342780112,
          31.23360579506302,
          0
        ),
        // height: 0.0,
        ellipse: {
          show: true,
          semiMinorAxis: new Cesium.CallbackProperty(function () {
            if (!Cesium.defined(circleFirst3.ellipse._semiMinorAxis2)) {
              circleFirst3.ellipse._semiMinorAxis2 = 0;
            }
            // if (that.moveMode) {
            //往返
            if (circleFirst3.ellipse._semiMinorAxis2 > that.radius) {
              multiS = -1;
            } else if (circleFirst3.ellipse._semiMinorAxis2 < 0) {
              //单一
              multiS = 1;
            }
            // } else {
            //   //单一
            //   if (circleFirst3.ellipse._semiMinorAxis2 > that.radius) {
            //     // circleFirst3.ellipse._semiMinorAxis2 = 0;
            //     multiS = 1;
            //     circleFirst3.ellipse._semiMinorAxis2 = 0;
            //   } else if (circleFirst3.ellipse._semiMinorAxis2 < 0) {
            //     multiS = 1;
            //   }
            // }
            circleFirst3.ellipse._semiMinorAxis2 += multiS * 15;
            return circleFirst3.ellipse._semiMinorAxis2;
          }, false),

          semiMajorAxis: new Cesium.CallbackProperty(function () {
            if (!Cesium.defined(circleFirst3.ellipse._semiMajorAxis2)) {
              circleFirst3.ellipse._semiMajorAxis2 = 0;
            }
            // if (that.moveMode) {
            //往返
            if (circleFirst3.ellipse._semiMajorAxis2 > that.radius) {
              multiS = -1;
            } else if (circleFirst3.ellipse._semiMajorAxis2 < 0) {
              //单一
              multiS = 1;
            }
            // } else {
            //   //单一
            //   if (circleFirst3.ellipse._semiMajorAxis2 > that.radius) {
            //     multiS = 1;
            //     circleFirst3.ellipse._semiMajorAxis2 = 0;
            //   } else if (circleFirst3.ellipse._semiMajorAxis2 < 0) {
            //     multiS = 1;
            //   }
            // }
            circleFirst3.ellipse._semiMajorAxis2 += multiS * 15;
            return circleFirst3.ellipse._semiMajorAxis2;
          }, false),

          // stRotation: new Cesium.CallbackProperty(function () {
          //   if (!Cesium.defined(circleFirst3.ellipse._semiMajorAxis2)) {
          //     circleFirst3.ellipse._semiMajorAxis2 = 0;
          //   }
          //   circleFirst3.ellipse._semiMajorAxis2 += multiS * 15;
          //   return circleFirst3.ellipse._semiMajorAxis2;
          // }, false),
          material: new Cesium.ImageMaterialProperty({
            image: "./static/images/circle.png",
            transparent: true,
          }),
          classificationType: Cesium.ClassificationType.TERRAIN,
          outline: false,
        },
      });

      window.circleFirst3 = circleFirst3;
    },

    // 加载飞线
    addFlyLine() {
      let that = this;
      this.topK.map(function (item) {
        let startPoint = item;
        let endPoint = Object.assign({}, startPoint);
        endPoint.h = item.h;
        let positions = [
          startPoint.lon,
          startPoint.lat,
          0,
          endPoint.lon,
          endPoint.lat,
          endPoint.h,
        ];
        addLine(positions);
      });

      // for (var j = 0; j < 50; ++j) {
      //   let startPoint = randomPoint();
      //   let endPoint = Object.assign({}, startPoint);
      //   endPoint.h = getRandom(199, 200);

      //   // this.addFlyingLineByEntity(
      //   //   Cesium.Cartesian3.fromDegreesArrayHeights([
      //   //     startPoint.lon,
      //   //     startPoint.lat,
      //   //     startPoint.h,
      //   //     endPoint.lon,
      //   //     endPoint.lat,
      //   //     endPoint.h,
      //   //   ])
      //   // );
      //   // continue;
      // }

      function addLine(positions) {
        // 创建长方体对象
        const PolylineGeometry = new Cesium.PolylineGeometry({
          positions: Cesium.Cartesian3.fromDegreesArrayHeights(positions),
          width: 2,
        });
        const instance = new Cesium.GeometryInstance({
          geometry: PolylineGeometry,
        });
        // this.flylineObj.push(
        globalVariable.viewer.scene.primitives.add(
          new Cesium.Primitive({
            geometryInstances: [instance],
            appearance: that.getFlylineMaterial(1),
            depthFailAppearance: that.getFlylineMaterial(1),
            releaseGeometryInstances: false,
            compressVertices: false,
          })
        );
        // );
      }

      function randomPoint() {
        var jingd = 1000000;
        var jd =
          getRandom(
            systemConfig.mapDefault.bbox.west * jingd,
            systemConfig.mapDefault.bbox.east * jingd
          ) / jingd;
        var wd =
          getRandom(
            systemConfig.mapDefault.bbox.south * jingd,
            systemConfig.mapDefault.bbox.north * jingd
          ) / jingd;
        return {
          lon: jd,
          lat: wd,
          h: 0,
        };
      }
      function getRandom(t, e) {
        return Math.floor(Math.random() * (e - t + 1) + t);
      }
    },
    // 创建飞线材质 1
    getFlylineMaterial(index) {
      // 创建材质，在MaterialAppearance中若不添加基础材质，模型将会透明
      let material = new Cesium.Material.fromType("Color");
      material.uniforms.color = Cesium.Color.ORANGE;
      let fragmentShaderSource;
      if (index === 1) {
        // 飞线效果-飞线间隔，宽度2
        fragmentShaderSource = `         
                  varying vec2 v_st;    
                  varying float v_width;    
                  varying float v_polylineAngle;
                  varying vec4 v_positionEC;
                  varying vec3 v_normalEC;
                  void main()
                  {
                      vec2 st = v_st;
                      float xx = fract(st.s*2.0 - czm_frameNumber/60.0);
                      float r = xx;
                      float g = 200.0;
                      float b = 200.0;
                      float a = xx;
                      gl_FragColor = vec4(r,g,b,a);
                  }
          `;
      } else if (index === 2) {
        fragmentShaderSource = `
  varying vec2 v_st;
  varying float v_width;
  varying float v_polylineAngle;
  varying vec4 v_positionEC;
  varying vec3 v_normalEC;
  void main()
  {
      vec2 st = v_st;
      float xx = fract(st.s*2.0 - czm_frameNumber/60.0);
      float r = xx;
      float g = sin(czm_frameNumber/30.0);
      float b = cos(czm_frameNumber/30.0);
      float a = xx;
      gl_FragColor = vec4(r,g,b,a);
  }
          `;
      } else if (index === 3) {
        fragmentShaderSource = `
  varying vec2 v_st;
  varying float v_width;
  varying float v_polylineAngle;
  varying vec4 v_positionEC;
  varying vec3 v_normalEC;
  void main()
  {
      vec2 st = v_st;
      float xx = sin(st.s*6.0 -czm_frameNumber/5.0) - cos(st.t*6.0);
      float r = 0.0;
      float g = xx;
      float b = xx;
      float a = xx;
      gl_FragColor = vec4(r,g,b,a);
  }
          `;
      } else if (index === 4) {
        fragmentShaderSource = `
  varying vec2 v_st;
  varying float v_width;
  varying float v_polylineAngle;
  varying vec4 v_positionEC;
  varying vec3 v_normalEC;
  void main()
  {
      vec2 st = v_st;
      float xx = fract(st.s*10.0 + st.t  - czm_frameNumber/60.0);
      if (st.t<0.5) {
          xx = fract(st.s*10.0 - st.t - czm_frameNumber/60.0);
      }
      float r = 0.0;
      float g = xx;
      float b = xx;
      float a = xx;
      if (st.t>0.8||st.t<0.2) {
          g = 1.0;
          b = 1.0;
          a = 0.4;
      }
      gl_FragColor = vec4(r,g,b,a);
  }
          `;
      }
      // 自定义材质
      const aper = new Cesium.PolylineMaterialAppearance({
        material: material,
        translucent: true,
        vertexShaderSource: `
                  #define CLIP_POLYLINE 
                  void clipLineSegmentToNearPlane(
                      vec3 p0,
                      vec3 p1,
                      out vec4 positionWC,
                      out bool clipped,
                      out bool culledByNearPlane,
                      out vec4 clippedPositionEC)
                  {
                      culledByNearPlane = false;
                      clipped = false;
                      vec3 p0ToP1 = p1 - p0;
                      float magnitude = length(p0ToP1);
                      vec3 direction = normalize(p0ToP1);
                      float endPoint0Distance =  czm_currentFrustum.x + p0.z;
                      float denominator = -direction.z;
                      if (endPoint0Distance > 0.0 && abs(denominator) < czm_epsilon7)
                      {
                          culledByNearPlane = true;
                      }
                      else if (endPoint0Distance > 0.0)
                      {
                          float t = endPoint0Distance / denominator;
                          if (t < 0.0 || t > magnitude)
                          {
                              culledByNearPlane = true;
                          }
                          else
                          {
                              p0 = p0 + t * direction;
                              p0.z = min(p0.z, -czm_currentFrustum.x);
                              clipped = true;
                          }
                      }
                      clippedPositionEC = vec4(p0, 1.0);
                      positionWC = czm_eyeToWindowCoordinates(clippedPositionEC);
                  }
                  vec4 getPolylineWindowCoordinatesEC(vec4 positionEC, vec4 prevEC, vec4 nextEC, float expandDirection, float width, bool usePrevious, out float angle)
                  {
                      #ifdef POLYLINE_DASH
                      vec4 positionWindow = czm_eyeToWindowCoordinates(positionEC);
                      vec4 previousWindow = czm_eyeToWindowCoordinates(prevEC);
                      vec4 nextWindow = czm_eyeToWindowCoordinates(nextEC);
                      vec2 lineDir;
                      if (usePrevious) {
                          lineDir = normalize(positionWindow.xy - previousWindow.xy);
                      }
                      else {
                          lineDir = normalize(nextWindow.xy - positionWindow.xy);
                      }
                      angle = atan(lineDir.x, lineDir.y) - 1.570796327;
                      angle = floor(angle / czm_piOverFour + 0.5) * czm_piOverFour;
                      #endif
                      vec4 clippedPrevWC, clippedPrevEC;
                      bool prevSegmentClipped, prevSegmentCulled;
                      clipLineSegmentToNearPlane(prevEC.xyz, positionEC.xyz, clippedPrevWC, prevSegmentClipped, prevSegmentCulled, clippedPrevEC);
                      vec4 clippedNextWC, clippedNextEC;
                      bool nextSegmentClipped, nextSegmentCulled;
                      clipLineSegmentToNearPlane(nextEC.xyz, positionEC.xyz, clippedNextWC, nextSegmentClipped, nextSegmentCulled, clippedNextEC);
                      bool segmentClipped, segmentCulled;
                      vec4 clippedPositionWC, clippedPositionEC;
                      clipLineSegmentToNearPlane(positionEC.xyz, usePrevious ? prevEC.xyz : nextEC.xyz, clippedPositionWC, segmentClipped, segmentCulled, clippedPositionEC);
                      if (segmentCulled)
                      {
                          return vec4(0.0, 0.0, 0.0, 1.0);
                      }
                      vec2 directionToPrevWC = normalize(clippedPrevWC.xy - clippedPositionWC.xy);
                      vec2 directionToNextWC = normalize(clippedNextWC.xy - clippedPositionWC.xy);
                      if (prevSegmentCulled)
                      {
                          directionToPrevWC = -directionToNextWC;
                      }
                      else if (nextSegmentCulled)
                      {
                          directionToNextWC = -directionToPrevWC;
                      }
                      vec2 thisSegmentForwardWC, otherSegmentForwardWC;
                      if (usePrevious)
                      {
                          thisSegmentForwardWC = -directionToPrevWC;
                          otherSegmentForwardWC = directionToNextWC;
                      }
                      else
                      {
                          thisSegmentForwardWC = directionToNextWC;
                          otherSegmentForwardWC =  -directionToPrevWC;
                      }
                      vec2 thisSegmentLeftWC = vec2(-thisSegmentForwardWC.y, thisSegmentForwardWC.x);
                      vec2 leftWC = thisSegmentLeftWC;
                      float expandWidth = width * 0.5;
                      if (!czm_equalsEpsilon(prevEC.xyz - positionEC.xyz, vec3(0.0), czm_epsilon1) && !czm_equalsEpsilon(nextEC.xyz - positionEC.xyz, vec3(0.0), czm_epsilon1))
                      {
                          vec2 otherSegmentLeftWC = vec2(-otherSegmentForwardWC.y, otherSegmentForwardWC.x);
                          vec2 leftSumWC = thisSegmentLeftWC + otherSegmentLeftWC;
                          float leftSumLength = length(leftSumWC);
                          leftWC = leftSumLength < czm_epsilon6 ? thisSegmentLeftWC : (leftSumWC / leftSumLength);
                          vec2 u = -thisSegmentForwardWC;
                          vec2 v = leftWC;
                          float sinAngle = abs(u.x * v.y - u.y * v.x);
                          expandWidth = clamp(expandWidth / sinAngle, 0.0, width * 2.0);
                      }
                      vec2 offset = leftWC * expandDirection * expandWidth * czm_pixelRatio;
                      return vec4(clippedPositionWC.xy + offset, -clippedPositionWC.z, 1.0) * (czm_projection * clippedPositionEC).w;
                  }
                  vec4 getPolylineWindowCoordinates(vec4 position, vec4 previous, vec4 next, float expandDirection, float width, bool usePrevious, out float angle)
                  {
                      vec4 positionEC = czm_modelViewRelativeToEye * position;
                      vec4 prevEC = czm_modelViewRelativeToEye * previous;
                      vec4 nextEC = czm_modelViewRelativeToEye * next;
                      return getPolylineWindowCoordinatesEC(positionEC, prevEC, nextEC, expandDirection, width, usePrevious, angle);
                  }
                  attribute vec3 position3DHigh;
                  attribute vec3 position3DLow;
                  attribute vec3 prevPosition3DHigh;
                  attribute vec3 prevPosition3DLow;
                  attribute vec3 nextPosition3DHigh;
                  attribute vec3 nextPosition3DLow;
                  attribute vec2 expandAndWidth;
                  attribute vec2 st;
                  attribute float batchId;
                  varying float v_width;
                  varying vec2 v_st;
                  varying float v_polylineAngle;
                  
                  varying vec4 v_positionEC;
                  varying vec3 v_normalEC;
                  void main()
                  {
                  float expandDir = expandAndWidth.x;
                  float width = abs(expandAndWidth.y) + 0.5;
                  bool usePrev = expandAndWidth.y < 0.0;
                  vec4 p = czm_computePosition();
                  vec4 prev = czm_computePrevPosition();
                  vec4 next = czm_computeNextPosition();
                  
                  float angle;
                  vec4 positionWC = getPolylineWindowCoordinates(p, prev, next, expandDir, width, usePrev, angle);
                  gl_Position = czm_viewportOrthographic * positionWC;
                  
                  v_width = width;
                  v_st.s = st.s;
                  v_st.t = st.t;
                  // v_st.t = czm_writeNonPerspective(st.t, gl_Position.w);
                  v_polylineAngle = angle;
                  
                  vec4 eyePosition = czm_modelViewRelativeToEye * p;
                  v_positionEC =  czm_inverseModelView * eyePosition;      // position in eye coordinates
                  //v_normalEC = czm_normal * normal;                         // normal in eye coordinates
                  }
              `,
        fragmentShaderSource: fragmentShaderSource,
      });
      return aper;
    },

    // 地图（地球表面，无地形）左击事件
    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);
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#cesium_id {
  width: 100%;
  height: 100%;
}
.choose {
  position: absolute;
  z-index: 1;
  top: 20px;
  left: 20px;
  background: #ffffff;
  padding: 0px 20px;
  border-radius: 5px;
}
.switch {
  position: absolute;
  z-index: 1;
  top: 20px;
  right: 20px;
  background: #ffffff;
  padding: 0px 20px;
  border-radius: 5px;
}
</style>
