<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="mapOperation">-->
      <!--  <el-button>点标记</el-button>-->
      <!--  <el-button>线标记</el-button>-->
      <!--  <el-button>面标记</el-button>-->
      <!--</div>-->
      <div id="mapContainer">

      </div>
    </div>

    <template #footer>
      <el-button type="primary">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>
import 'cesium/Widgets/widgets.css'
import CesiumMarker from "@/static/js/CesiumMarker";

export default {
  data() {
    return {
      viewer: '',
      drawData: {
        points: [],
        lines: [],
        polygons: []
      },
      cesiumConfig: {
        animation: false, //动画控制不显示
        timeline: false, //时间线不显示
        fullscreenButton: 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),
        }),
        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,
    item: Object,
    isGeoJson: Boolean,
    close: Function
  },
  watch: {
    "isShow": function (val) {
      this.initMap();
    }
  },
  mounted() {
    this.$util.loading.handleLoading(true)
    this.initMap();
  },
  methods: {
    initMap() {
      let app = this;
      this.$nextTick(()=>{
        app.viewer = new Cesium.Viewer('mapContainer', app.cesiumConfig);
        app.viewer.scene.preRender.addEventListener(function () {
          app.loading = true;
        })
        app.viewer.scene.postRender.addEventListener(function () {
          app.loading = false;
        })
        // 加载底图
        app.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,
            })
        );
        // 加载注记
        app.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,
            })
        );
        // 加载GeoJson
        if (app.isGeoJson) {
          let geojson = {"type": "Feature", "geometry": JSON.parse(app.item.geometryStr), "properties": {}}
          let res = Cesium.GeoJsonDataSource.load(geojson,{
            stroke: Cesium.Color.fromCssColorString('#ff0000'),
            fill: Cesium.Color.RED.withAlpha(0.3),
            strokeWidth: 5,
            clampToGround:true,
          })
          app.viewer.dataSources.add(res);
          res.then(()=>{
            app.$util.loading.handleLoading(false)
            app.viewer.zoomTo(res, {heading: 2.718565, pitch: -0.415366, roll: 0.0,});
          }).catch(()=>{
            app.$message({message:'加载失败', type: 'error'})
            app.$util.loading.handleLoading(false)
          })
        } else {
          // 加载模型
          if (app.item.modelUrl && app.item.modelUrl!=='') {
            app.add3DTiles(app.viewer, app.item.modelUrl)
          } else {
            app.$util.loading.handleLoading(false)
          }
        }
      });
    },
    // 添加模型
    add3DTiles(viewer, url){
      let app = this;
      let tileset = new Cesium.Cesium3DTileset({
        url: url,
        skipLevelOfDetail: true, //开启跳级加载
        maximumScreenSpaceError: 16,
        maximumNumberOfLoadedTiles: 2000,
        maximumMemoryUsage: 512,//tileset可以使用的最大内存
        show: true,
        immediatelyLoadDesiredLevelOfDetail: true,
      });
      tileset.allTilesLoaded.addEventListener(function() {
        app.$util.loading.handleLoading(false)
      });
      tileset.tileFailed.addEventListener(function (err) {
        app.$util.loading.handleLoading(false);
        app.$message({message: '模型加载失败', type: 'error'});
        app.handleClose()
      })
      viewer.scene.primitives.add(tileset);
      tileset.show=true;
      tileset.readyPromise.then(function () {
        viewer.zoomTo(tileset, {
          heading: 2.718565,
          pitch: -0.415366,
          roll: 0.0,
        });
      }).catch(err=>{
        app.$util.loading.handleLoading(false);
        app.$message({dangerouslyUseHTMLString: true, message: '模型加载失败，'+err.statusCode+'：'+err.response, type: 'error'});
        app.handleClose()
      });
      return tileset;
    },
    handleClose() {
      this.close(false)
    }
  }
}
</script>

<style scoped>
#mapBox {
  width: 100%;
  height: 100%;
}
#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>