<template>
  <el-dialog v-if="isShow" :model-value="isShow" title="地理信息" :width="1200" :close-on-click-modal="false"
    :before-close="handleClose">
    <div id="mapBox">
      <!-- <div id="mapContainer"></div> -->
      <iframe :src="src" frameborder="0"></iframe>
    </div>

  </el-dialog>
</template>

<script>

let viewer = null;
export default {
  data() {
    return {
      src: systemConfig.single_map,
      viewer: '',
      centerPoint: {},
      cesiumConfig: {
        animation: false, //动画控制不显示
        timeline: false, //时间线不显示
        fullscreenButton: false, //全屏按钮不显示
        imageryProvider: new SkyScenery.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: SkyScenery.Rectangle.fromDegrees(-180.0, -90.0, 180.0, 90.0),
        }),
        infoBox: false,
        baseLayerPicker: false, //地图切换不显示
        geocoder: false,
        homeButton: false,
        selectionIndicator: false, // 去除绿色选择框
        sceneModePicker: false,
        navigationHelpButton: false,
        navigationInstructionsInitiallyVisible: false,
        scene3DOnly: true, // 仅以3D渲染以节省GPU内存
        useBrowserRecommendedResolution: true, // 以浏览器建议的分辨率渲染
      },
    }
  },
  props: {
    isShow: Boolean,
    type: Number, // 0-GeoJson、1-3DTiles、2-gltf、3-水面、4-地图
    item: Object,
    close: Function
  },
  watch: {
    "isShow": function (val) {
      this.initMap();
    }
  },
  mounted() {
    let app = this;
    this.$nextTick(() => {
      app.initMap();
    })
  },
  methods: {
    initMap() {
      let app = this;
      // viewer = new SkyScenery.Viewer('mapContainer', app.cesiumConfig);
      // // 加载底图
      // if (app.type !== 4) {
      //   viewer.imageryLayers.addImageryProvider(
      //     new SkyScenery.ArcGisMapServerImageryProvider({
      //       url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer',
      //     })
      //   )
      // }
      // window.viewer = viewer
      // 加载模型
      app.loadingEntities(app.type);
    },
    loadingEntities(type) {
      let app = this;
      if (!type || type === '') {
        return;
      }
      // 加载GeoJson
      if (type === 0) {
        let obj = { "type": "Feature", "geometry": JSON.parse(app.item), "properties": {} }
        this.addGeoJson(obj);
      }
      // 加载3DTiles
      else if (type === 1) {
        // let url = app.item.url + '/tileset.json'
        // app.add3DTiles(url)
        // http://localhost:8080/map-server/index.html?dataType=threeD&url=http://1.119.143.102:9002/model_data/750/qinghulu/output/tileset.json
        this.src = systemConfig.single_map + "?dataType=threeD&" + app.item.url + '/tileset.json'
      }
      // 加载gltf
      else if (type === 2) {
        app.addGltf(app.item.url)
      }
      // 加载底图
      else if (type === 4) {
        app.addMap(app.item.url, app.item.type);
      }
    },
    // 加载GeoJson
    addGeoJson(obj) {
      let app = this;
      let res = SkyScenery.GeoJsonDataSource.load(obj, {
        stroke: SkyScenery.Color.fromCssColorString('#ff0000'),
        fill: SkyScenery.Color.RED.withAlpha(0.3),
        strokeWidth: 5,
        clampToGround: true,
      })
      viewer.dataSources.add(res);
      res.then(() => {
        viewer.zoomTo(res, { heading: 2.718565, pitch: -0.415366, roll: 0.0, });
      }).catch(() => {
        app.$message({ message: '加载失败', type: 'error' })
      })
    },
    // 添加模型
    add3DTiles(url) {
      let app = this;
      let tile = undefined;
      if (!url || url == '') {
        app.$message.warning('请检查模型地址');
        app.handleClose()
        return;
      }
      tile = SkyScenery.add3DTilesData(url, viewer);
      tile.tileFailed.addEventListener(function (err) {
        app.$message({ message: '模型加载失败', type: 'error' });
        app.handleClose()
      })
      tile.readyPromise.then(function () {
        viewer.zoomTo(tile, {
          heading: 2.718565,
          pitch: -0.415366,
          roll: 0.0,
        });
      }).catch(err => {
        app.$message({
          dangerouslyUseHTMLString: true,
          message: '模型加载失败，' + err.statusCode + '：' + err.response,
          type: 'error'
        });
        app.handleClose()
      });
      return tile;
    },
    // 添加gltf
    addGltf(url) {
      let app = this;
      if (!url || url == '') {
        app.$message.warning('请检查模型地址');
        app.handleClose()
        return;
      }
      let modelObj = new SkyScenery.singleModelBindClick(viewer, {
        url: url,
        lon: systemConfig.mapCenter.lon,
        lat: systemConfig.mapCenter.lat,
        height: 10,
        heading: 0,
        pitch: -90,
        roll: 0,
        info: {}
      })
      let origin = SkyScenery.Cartesian3.fromDegrees(systemConfig.mapCenter.lon, systemConfig.mapCenter.lat, 10);
      viewer.camera.flyTo({
        destination: origin,
        orientation: {
          heading: SkyScenery.Math.toRadians(0), // 方向
          pitch: SkyScenery.Math.toRadians(-90), // 倾斜角度
          roll: SkyScenery.Math.toRadians(0),
        },
      });
    },
    addMap(url, type) {
      if (type == '') {
        this.src = systemConfig.single_map + "?dataType=twoD&mapType=twoD&mapserverType=arcgis&url=" + url
      } else if (type == 'xyz') {
        this.src = systemConfig.single_map + "?dataType=twoD&mapType=twoD&mapserverType=xyz&url=" + url
      }
      // return;
      // viewer.imageryLayers.removeAll(true);
      // if (type == '') {
      //   viewer.imageryLayers.addImageryProvider(
      //     new SkyScenery.ArcGisMapServerImageryProvider({
      //       url: url,
      //     })
      //   )
      // } else if (type == 'xyz') {
      //   viewer.imageryLayers.addImageryProvider(
      //     new SkyScenery.UrlTemplateImageryProvider({
      //       url: url + '/{z}/{x}/{y}.png',
      //       fileExtension: 'png'
      //     })
      //   )
      // }
    },
    flyToPrimitive(obj) {
      let east = obj.geometryInstances.geometry.rectangle.east;
      let north = obj.geometryInstances.geometry.rectangle.north;
      let west = obj.geometryInstances.geometry.rectangle.west;
      let south = obj.geometryInstances.geometry.rectangle.south;
      let lon = (east + west) / 2;
      let lat = (north + south) / 2;
      viewer.camera.flyTo({
        destination: SkyScenery.Cartesian3.fromDegrees(SkyScenery.Math.toDegrees(lon), SkyScenery.Math.toDegrees(lat), 338.8293456247198),
        orientation: {
          heading: SkyScenery.Math.toRadians(0),
          pitch: SkyScenery.Math.toRadians(-90),
          roll: 0,
        }
      })
    },
    handleClose() {
      this.close(false)
    }
  }
}
</script>

<style scoped>
#mapBox {
  width: 100%;
  height: 100%;
}

iframe {
  width: 100%;
  height:500px;
}

#mapContainer {
  width: 100%;
  height: 100%;
}

#mapOperation {
  margin-bottom: 10px;
}
</style>

<style>
/*隐藏 cesium logo*/
.cesium-widget-credits {
  display: none !important;
}

.el-dialog__body {
  padding-top: 10px;
}
</style>