<template>
  <div id="skysceneryContainer"></div>
</template>

<script>
export default {
  name: "Map",
  mounted() {
    window.SkySceneryConfig = {};
    this.getToken();
  },
  methods: {
    getToken() {
      let that = this;
      let loginInfo = new FormData();
      for (const key in userLoginConfig) {
        if (Object.prototype.hasOwnProperty.call(userLoginConfig, key)) {
          loginInfo.append(key, userLoginConfig[key]);
        }
      }
      fetch(oauthUrl + "/oauth/api/user/login", {
        method: "POST",
        body: loginInfo
      })
        .then(resp => resp.json())
        .then(data => {
          SkySceneryConfig = {
            authUrl: oauthUrl,
            token: data.message
          };
          that.pushAllScripts();
        });
    },

    pushAllScripts() {
      let that = this;
      that.addScripts(scriptObj.main).then(function() {
        let arr = scriptObj.plugins.map(function(src) {
          return that.addScripts(src);
        });
        Promise.all(arr).then(function() {
          setTimeout(() => {
            if (SkyScenery) {
              that.creatMap();
            } else {
              that.pushAllScripts();
            }
          });
        });
      });
    },

    addScripts(src) {
      return new Promise((resolve, reject) => {
        // 创建一个新的script标签
        var script = document.createElement("script");
        // 设置script标签的src属性为要引入的JavaScript文件的URL
        script.src = src;
        // 将script标签添加到页面的head部分或者其他合适的位置
        document.head.appendChild(script);
        if (script.readyState) {
          // IE
          script.onreadystatechange = function() {
            if (
              script.readyState === "loaded" ||
              script.readyState === "complete"
            ) {
              script.onreadystatechange = null;
              resolve();
            }
          };
        } else {
          // 其他浏览器
          script.onload = function() {
            resolve();
          };
        }
      });
    },
    creatMap() {
      try {
        let that = this;
        window.viewer = new SkyScenery.Viewer("skysceneryContainer", {
          animation: false, //是否创建动画小器件，左下角仪表
          baseLayerPicker: false, //是否显示图层选择器
          imageryProvider: new SkyScenery.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: SkyScenery.Rectangle.fromDegrees(
              -180.0,
              -90.0,
              180.0,
              90.0
            )
          }),
          fullscreenButton: false, //是否显示全屏按钮
          geocoder: false, //是否显示geocoder小器件，右上角查询按钮
          homeButton: false, //是否显示Home按钮
          infoBox: false, //是否显示信息框
          sceneModePicker: false, //是否显示3D/2D选择器
          selectionIndicator: false, //是否显示选取指示器组件
          timeline: false, //是否显示时间轴
          navigationHelpButton: false, //是否显示右上角的帮助按钮
          scene3DOnly: true, //如果设置为true，则所有几何图形以3D模式绘制以节约GPU资源
          infoBox: false, //是否显示点击要素之后显示的信息
          shouldAnimate: false //是否自动播放
        });
        setTimeout(() => {
          // 根据配置文件中的配置信息加载底图
          systemConfig.imageryProviders.forEach(url => {
            that.loadTheWorldMapImage(url);
          });
          viewer.camera.setView({
            destination: SkyScenery.Cartesian3.fromDegrees(121, 31, 30000.0), // 设置位置
            orientation: {
              heading: SkyScenery.Math.toRadians(0.0), // 方向
              pitch: SkyScenery.Math.toRadians(-90.0), // 倾斜角度
              roll: 0
            }
          });
          this.$store.commit("createdMap", true);
          // // 盘龙天地
          // let tileName = "盘龙天地";
          // for (let key in systemConfig.data3DTiles[tileName]) {
          //   let v = systemConfig.data3DTiles[tileName][key];
          //   this.add3DTiles(v, true);
          // }
          // // 西虹桥
          // this.add3DTiles(systemConfig.data3DTiles["西虹桥"]["全部"], true);
          return;
        }, 0);
        // viewer.entities.add({
        //   name: "点",
        //   position: SkyScenery.Cartesian3.fromDegrees(121.1, 31), //经纬度转世界坐标
        //   point: {
        //     show: true,
        //     color: SkyScenery.Color.GREEN,
        //     pixelSize: 20,
        //     outlineColor: SkyScenery.Color.YELLOW,
        //     outlineWidth: 3,
        //   },
        //   label: {
        //     text: "这里是标签", //设置文字内容
        //     font: "normal 18px 楷体", //设置文字大小和字体
        //     fillColor: SkyScenery.Color.fromCssColorString("#00ff00"), //设置文字填充的颜色
        //     horizontalOrigin: SkyScenery.HorizontalOrigin.CENTER,
        //     verticalOrigin: SkyScenery.VerticalOrigin.BOTTOM,
        //     pixelOffset: new SkyScenery.Cartesian2(0, -20),
        //   },
        // });
        // viewer.entities.add({
        //   position: SkyScenery.Cartesian3.fromDegrees(121.2, 31),
        //   billboard: {
        //     image: "/static/image/point.png",
        //     width: 48, // default: undefined
        //     height: 48, // default: undefined
        //     scale: 1.0, // default: 1.0
        //     show: true, // default
        //     horizontalOrigin: SkyScenery.HorizontalOrigin.CENTER, // default
        //     verticalOrigin: SkyScenery.VerticalOrigin.BOTTOM, // default: CENTER
        //   },
        //   label: {
        //     text: "这是自定义图片", // 设置文字内容
        //     font: "normal 18px 楷体", // 设置文字大小和字体
        //     fillColor: SkyScenery.Color.fromCssColorString("#00ff00"), //设置文字填充的颜色
        //     horizontalOrigin: SkyScenery.HorizontalOrigin.CENTER,
        //     verticalOrigin: SkyScenery.VerticalOrigin.BOTTOM,
        //     pixelOffset: new SkyScenery.Cartesian2(0, -50),
        //   },
        // });
        // let positions = [
        //   [121.04829640102727, 31.12735759260756],
        //   [121.05219953077487, 31.126058264888133],
        //   [121.0556573133586, 31.125143117515066],
        //   [121.0585577885634, 31.12489903339664],
        //   [121.05855842602281, 31.117437091290032],
        //   [121.05755469646111, 31.116865171387122],
        //   [121.05855867110577, 31.114567660254956],
        //   [121.05716503781966, 31.111412856109656],
        //   [121.05169919616742, 31.109414349328368],
        //   [121.04846566530048, 31.10731617798831],
        //   [121.04523257218045, 31.105074455848328],
        //   [121.04372646220537, 31.108713847196935],
        //   [121.04238895034425, 31.11239990163383],
        //   [121.04216536839769, 31.11503097997496],
        //   [121.03965751482633, 31.117141773623022],
        //   [121.0392664980893, 31.119247569299414],
        //   [121.0401584271992, 31.124267692010815],
        //   [121.04534263782213, 31.124207732078528],
        //   [121.04813004860797, 31.124919266167907],
        //   [121.04829640102727, 31.12735759260756],
        // ];
        // viewer.entities.add({
        //   name: "立体墙效果",
        //   wall: {
        //     positions: positions.map(function (item) {
        //       return SkyScenery.Cartesian3.fromDegrees(item[0], item[1]);
        //     }),
        //     // 设置高度
        //     maximumHeights: new Array(positions.length).fill(100),
        //     minimumHeights: new Array(positions.length).fill(0),
        //     material: new SkyScenery.DynamicWallMaterialProperty({
        //       color: SkyScenery.Color.fromCssColorString("#00c4ff80"),
        //       trailImage: "/static/image/color.png",
        //       duration: 3000,
        //     }),
        //   },
        // });
        // viewer.entities.add({
        //   name: " 面",
        //   polygon: {
        //     hierarchy: {
        //       positions: SkyScenery.Cartesian3.fromDegreesArray(
        //         positions
        //           .join(",")
        //           .split(",")
        //           .map(function (num) {
        //             return Number(num);
        //           })
        //       ),
        //     },
        //     material: new SkyScenery.ImageMaterialProperty({
        //       image: "/static/image/b2.png", // 图片路径
        //       transparent: true, // 是否透明
        //     }),
        //   },
        // });
      } catch (error) {
        console.log("createMap error:", error);
        window.location.reload();
      }
    },

    /**
     * 加载天地图底图
     * @author LiuMengxiang
     * 加载影像底图和影像注记
     */
    loadTheWorldMapImage(url) {
      // if (url.indexOf("//t0.") != -1) {
      //   url = url.replace("//t0.", "//t{s}.");
      // }
      // viewer.imageryLayers.addImageryProvider(
      //   new SkyScenery.WebMapTileServiceImageryProvider({
      //     url:
      //       url +
      //       "?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"],
      //     show: true,
      //     minimumLevel: 1,
      //     maximumLevel: 18
      //   })
      // );
      viewer.imageryLayers.addImageryProvider(
        new SkyScenery.ArcGisMapServerImageryProvider({
          url:
            "https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer"
        })
      );
      viewer.camera.setView({
        destination: SkyScenery.Cartesian3.fromDegrees(121, 31, 30000.0), // 设置位置
        orientation: {
          heading: SkyScenery.Math.toRadians(0.0), // 方向
          pitch: SkyScenery.Math.toRadians(-90.0), // 倾斜角度
          roll: 0
        }
      });
    },

    // 加载geojson数据
    addGeoJson(url, options) {
      // options = {
      //   point: {
      //     imgUrl: ""
      //   },
      //   polyline: {
      //     color: "#ffffff",
      //     width: 3,
      //     alpha: 0.7
      //   },
      //   polygon: {
      //     outerColor: "#ffffff",
      //     outerWidth: 3,
      //     innerColor: "#ffffff",
      //     alpha: 0.7
      //   }
      // };

      SkyScenery.GeoJsonDataSource.load(url).then(function(dataSource) {
        viewer.dataSources.add(dataSource);
        var entities = dataSource.entities.values;
        for (var i = 0; i < entities.length; i++) {
          var entity = entities[i];
          if (entity.billboard) {
            entity.billboard = undefined;
            entity.billboard = new SkyScenery.BillboardGraphics({
              image: options.point.imgUrl,
              width: 50,
              height: 50,
              pixelOffset: new SkyScenery.Cartesian2(0, -25),
              heightReference: SkyScenery.HeightReference.CLAMP_TO_GROUND
            });
          }
          if (entity.polyline) {
            entity.polyline.width = options.polyline.width;
            entity.polyline.material = SkyScenery.Color.fromCssColorString(
              options.polyline.color
            ).withAlpha(options.polyline.alpha); // 颜色
          }
          if (entity.polygon) {
            entity.polygon.height = 0.2;
            entity.polygon.outline = true; // 边框是否显示
            entity.polygon.outlineColor = SkyScenery.Color.fromCssColorString(
              options.polygon.outerColor
            ); // 边框颜色
            entity.polygon.outlineWidth = options.polygon.outerWidth; // 边框宽度
            entity.polygon.material = SkyScenery.Color.fromCssColorString(
              options.polygon.innerColor
            ).withAlpha(options.polygon.alpha); // 填充色
          }
        }
      });
    },

    // 加载动态围墙
    addDynamicWall(positions, options) {
      /**
       * options = {
       *    maxH: 100,
       *    color: "#00c4ff80",
       *    duration: 3000,
       * }
       */
      return viewer.entities.add({
        name: "立体墙效果",
        wall: {
          positions: positions.map(function(item) {
            return SkyScenery.Cartesian3.fromDegrees(item[0], item[1]);
          }),
          // 设置高度
          maximumHeights: new Array(positions.length).fill(options.maxH || 100),
          minimumHeights: new Array(positions.length).fill(0),
          material: new SkyScenery.DynamicWallMaterialProperty({
            color: SkyScenery.Color.fromCssColorString(options.color), // "#"
            trailImage: "/static/image/color.png",
            duration: options.duration || 3000 // 3000
          })
        }
      });
    },

    /**
     * 加载3Dtiles
     * @author LiuMengxiang
     * @param {*} url 3Dtiles的url地址
     * @param {*} flyto 是否自动飞行到3Dtiles
     */
    add3DTiles(url, flyto) {
      // let that = this;
      let option = {
        url: url + "/tileset.json",
        skipLevelOfDetail: true, //开启跳级加载
        maximumMemoryUsage: 1024, //最大内存占用  推荐显存的一般
        preferLeaves: true,
        maximumScreenSpaceError: 16,
        maximumNumberOfLoadedTiles: 2000
      };
      // option = Object.assign(option, options);
      var tile = new SkyScenery.Cesium3DTileset(option);
      viewer.scene.primitives.add(tile);

      if (flyto) {
        tile.readyPromise.then(function(tileset) {
          viewer.zoomTo(tile);
          // if (url.indexOf("jz") != -1) {
          //   setTimeout(() => {
          //     that.remove3Dtiles(tile);
          //   }, 5000);
          // }
        });
      }
      return tile;

      // let tile = SkyScenery.add3DTilesData(url + "/tileset.json", viewer);

      // viewer.scene.primitives.add(tile);
      // if (flyto) {
      //   tile.readyPromise.then(function(tileset) {
      //     viewer.zoomTo(tile);
      //     if (url.indexOf("jz") != -1) {
      //       setTimeout(() => {
      //         that.remove3Dtiles(tile);
      //       }, 5000);
      //     }
      //   });
      // }
      // return tile;
    },
    /**
     * 删除3DTiles(测试)
     * @author LiuMengxiang
     * @param tiles 3DTiles实例
     */
    remove3Dtiles(tiles) {
      viewer.scene.primitives.remove(tiles);
    }
  }
};
</script>

<style lang="less" scoped>
#skysceneryContainer {
  width: 100%;
  height: 100%;
}
</style>
