<template>
  <div class="mainMapContainer">
    <div id="cesiumContainer" class="cesium_container"></div>
    <Maptool-Bar :class="footer_height === '0%' ? '' : 'maptools'" :isInit="isInit"></Maptool-Bar>
    <Coordinate :isInit="isInit"></Coordinate>
    <Top-SectionUI :isInit="isInit"></Top-SectionUI>
    <LayerUpOrDown :isInit="isInit"></LayerUpOrDown>
    <BaseImageOpacity :isInit="isInit"></BaseImageOpacity>
    <PipeSpeedInfoCheck :isInit="isInit"></PipeSpeedInfoCheck>
    <InfoSearch :isInit="isInit"></InfoSearch>
    <MapLegend></MapLegend>
    <OverViewOlMap :isInit="isInit"></OverViewOlMap>
  </div>
</template>

<script>
import MaptoolBar from '@/views/widgets/MapToolBar/index.vue'
import Coordinate from '@/views/widgets/Coordinate/index.vue'
import TopSectionUI from '@/views/widgets/TopSectionUI/index.vue'
import LayerUpOrDown from '@/views/widgets/LayerUpOrDown/index.vue'
import BaseImageOpacity from '@/views/widgets/BaseImageOpacity/index.vue'
import PipeSpeedInfoCheck from '@/views/widgets/PipeSpeedInfoCheck/index.vue'
import InfoSearch from '@/views/widgets/InfoSearch/index.vue'
import MapLegend from '@/views/widgets/MapToolBar/Legend.vue'
import OverViewOlMap from '@/views/widgets/OverViewOlMap/index.vue'
import BaseConfig from '@/config/basemapConfig'
export default {
  name: 'cesiumMap',
  components: {
    MaptoolBar,
    Coordinate,
    TopSectionUI,
    LayerUpOrDown,
    BaseImageOpacity,
    PipeSpeedInfoCheck,
    InfoSearch,
    MapLegend,
    OverViewOlMap
  },
  data() {
    return {
      footer_height: '0%',
      mapService: ['img', 'theme'],
      baseScene: 'scenes',
      baseTerrain: 'terrain',
      terrain: 'dixing',
      isInit: false, //当前的地图容器对象
      baselayer: []
    }
  },
  computed: {
    AppX: function () {
      return this.$store.getters.AppX
    }
  },
  methods: {
    initData() {
      return this.$store.dispatch('cesiumMap/initGISResource')
    },
    /**
     * 加载地图
     */
    addToMap() {
      var configItem = this.AppX.appConfig.gisResource[this.baseTerrain]
      var url = configItem.config[this.terrain].url
      var layerTitle = configItem.config[this.terrain].name
      // var url =
      //   "https://yeepms.yeec.com.cn/iserver/services/3D-sxgk_dem/rest/realspace/datas/TF_PAPN_DEM@sxgk_base";
      // var layerTitle = "dixing";
      var viewer = new Cesium.Viewer('cesiumContainer', {
        terrainProvider: new Cesium.CesiumTerrainProvider({
          url: url,
          requestWaterMask: true,
          requestVertexNormals: true,
          credit: layerTitle,
          isSct: true
        }),
        navigation: true,
        contextOptions: {
          webgl: {
            alpha: false,
            depth: true,
            stencil: true,
            antialias: true,
            premultipliedAlpha: true,
            preserveDrawingBuffer: true, //通过canvas.toDataURL()实现截图需要将该项设置为true
            failIfMajorPerformanceCaveat: false
          },
          allowTextureFilterAnisotropic: true
        },
        timeline: false,
        animation: false,
        infoBox: false,
        selectionIndicator: false //设置绿色框框不可见
      })
      this.$store.state.cesiumMap.mapContainerId = 'cesiumContainer'
      this.viewer = viewer
      viewer._cesiumWidget._creditContainer.style.display = 'none' //去掉logo
      window.viewer = viewer
      //   this.viewer = window.viewer;
      this.isInit = true
      //this.panels.viewer = this.viewer = viewer;
      //this.$store.commit('viewer',viewer)
      // const viewerInit = new ViewerInitEvent(viewer);
      // viewerInit.init();
      this.initCesiumStatus()
      //viewer.scene.logarithmicDepthBuffer = false;
      //高动态范围渲染
      //viewer.scene.highDynamicRange = false;

      this.initBaseMap()
      this.initTianditu()
      const initPosition = this.AppX.appConfig.initPosition
      const carto = Cesium.Cartographic.fromDegrees(
        parseFloat(initPosition.lon),
        parseFloat(initPosition.lat),
        parseFloat(initPosition.height)
      )
      const cartes3 = Cesium.Cartographic.toCartesian(carto)

      // const cartes3 = new Cesium.Cartesian3(
      //   -2204482.2366905585,
      //   5150077.372278957,
      //   3152769.164041396
      // );
      const camera = cartes3
      viewer.camera.setView({
        destination: new Cesium.Cartesian3(camera.x, camera.y, camera.z),
        orientation: {
          heading: 0,
          pitch: Cesium.Math.toRadians(-90),
          roll: 0
        }
      })
      console.log('加载地图')
      this.$emit('afterMapLoad')
      setTimeout(
        function () {
          this.addInitScene()
        }.bind(this),
        5000
      )
    },
    /**初始化基础底图*/
    initBaseMap() {
      this.baseMapConfig()
      let layerInfo = this.baselayer
      layerInfo.forEach((item) => {
        if (item.show) {
          const gisItem = this.AppX.appConfig.gisResource[item.type].config[item.name]
          if (!gisItem) {
            return true
          }
          const url = gisItem.url
          if (this.mapService.indexOf(item.type) > -1) {
            this.viewer.imageryLayers.addImageryProvider(
              new Cesium.SuperMapImageryProvider({
                url: url,
                credit: item.name
              })
            )
          } else if ((item.type = 'mvt')) {
            this.viewer.scene.addVectorTilesMap({
              url: url,
              name: item.name
            })
          }
        }
      })

      // this.viewer.imageryLayers.addImageryProvider(
      //   new Cesium.SuperMapImageryProvider({
      //     url: "https://yeepms.yeec.com.cn/iserver/services/map-sxgk/rest/maps/hnyy_type",
      //     credit: "typetheme",
      //   })
      // );
    },
    /**
     * 地图服务配置
     */
    baseMapConfig() {
      const source = this.AppX.appConfig.gisResource
      const mapList = this.mapService
      const baseLayer = []
      for (let name in source) {
        if (mapList.indexOf(name) > -1) {
          const config = source[name].config
          for (let key in config) {
            const item = config[key]
            baseLayer.push({
              name: key,
              type: name,
              show: item.isDisplay === '0' ? false : true
            })
          }
          // for (let i = 0; i < config.length; i++) {
          //   const item = config[i];
          //   baseLayer.push({
          //     name: item.key,
          //     type: name,
          //     show: item.isDisplay === "0" ? false : true,
          //   });
          // }
        }
      }
      this.baselayer = baseLayer
    },
    /**
     * 加载初始化场景
     */
    addInitScene() {
      var scenes = this.AppX.appConfig.gisResource[this.baseScene]
      if (scenes && scenes.config) {
        this.scenesIndex = 0
        Object.keys(scenes.config).forEach(
          function (keyName, index) {
            const item = scenes.config[keyName]
            var promise = this.viewer.scene.open(item.url, undefined, {
              autoSetView: false
            })
            Cesium.when(
              promise,
              function (layers) {
                this.scenesIndex += 1
                for (var i = 0; i < layers.length; i++) {
                  var ly = layers[i]
                  ly.selectEnabled = false
                  ly.clearMemoryImmediately = false
                  ly.cullEnabled = false
                  //ly.lodRangeScale=0.01
                  var model = BaseConfig.layers[ly.name]
                  if (BaseConfig.sjpipeLayers.indexOf(ly.name) > -1) {
                    let style3d = new Cesium.Style3D()
                    style3d.altitudeMode = 0
                    style3d.bottomAltitude = 0 - AppX.appConfig.downDepth
                    ly.style3D = style3d
                    //ly.visibleDistanceMax=800;
                    ly.maxVisibleAltitude = BaseConfig.pipeMaxVisibel
                  }
                  //普查管线初始隐藏
                  if (BaseConfig.pcpipeLayers.indexOf(ly.name) > -1) {
                    let style3d = new Cesium.Style3D()
                    style3d.altitudeMode = 0
                    style3d.bottomAltitude = 0 - AppX.appConfig.downDepth
                    ly.style3D = style3d
                    ly.visible = false
                    ly.maxVisibleAltitude = BaseConfig.pipeMaxVisibel
                  }
                  if (BaseConfig.pipeSelectLayers.indexOf(ly.name) > -1) {
                    ly.selectedColor = Cesium.Color.DARKRED
                    ly.selectColorType = 1
                  }
                  if (BaseConfig.pipeLineLayer.indexOf(ly.name) > -1) {
                    ly.lodRangeScale = 20
                  }
                  if (model) {
                    let style3d = new Cesium.Style3D()
                    style3d.altitudeMode = 0
                    style3d.bottomAltitude = model.bottomAltitude
                    ly.visible = model.visible
                    ly.style3D = style3d
                    //ly.brightness = model.brightness;
                    //ly.contrast = model.contrast;
                    //ly.hue = model.hue;
                    //ly.saturation = model.saturation;
                    //ly.gamma = model.gamma;
                    //if (Cesium.defined(model.maxVisibleAltitude)) ly.maxVisibleAltitude = model.maxVisibleAltitude;
                    //if(Cesium.defined(model.maxVisibleDistance)) ly.visibleDistanceMax=model.maxVisibleDistance;
                  }
                  ly.refresh()
                }
                if (!this.AppX.runtimeConfig.activeView.scene.pickPositionSupported) {
                  console.error('不支持深度纹理,无法拾取位置！')
                }
              }.bind(this),
              function (e) {
                console.error('加载SCP失败，请检查网络连接状态或者url地址是否正确？')
              }
            )
          }.bind(this)
        )
      }
    },
    /**
     * 该方法用于初始化cesium属性
     */
    initCesiumStatus() {
      //开启地形深度测试
      this.viewer.scene.globe.depthTestAgainstTerrain = true
      //关闭灯光
      this.viewer.scene.globe.enableLighting = false
      //globeAlpha导致月球始终可见
      this.viewer.scene.moon.show = false
      //地球表面双面显示
      this.viewer.scene.globe.backFaceCulling = false
      //开启地下模式
      this.viewer.scene.undergroundMode = true
      this.viewer.scene.screenSpaceCameraController.minimumZoomDistance = -1000
      this.viewer.terrainProvider.isCreateSkirt = false //关闭地形裙边
      //设置地球表面颜色
      this.viewer.scene.globe.baseColor = new Cesium.Color(0, 0, 0, 1)
      //帧率工具
      this.viewer.scene.debugShowFramesPerSecond = false
      const nowDate = new Date(Date.now())
      nowDate.setHours(16) //设置系统时间为12点,时差12小时
      nowDate.setMinutes(0)
      this.viewer.clock.currentTime = Cesium.JulianDate.fromDate(nowDate)
      this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
    },
    /**
     * 系统初始化加载天地图
     */
    initTianditu() {
      const layerType = 'vec_w'
      const poiType = 'cva_w'
      const layerName = layerType.split('_')[0]
      const poiName = poiType.split('_')[0]
      const token = this.$store.state.cesiumMap.tdttoken
      const url =
        'https://t{s}.tianditu.gov.cn/' +
        layerType +
        '/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=' +
        layerName +
        '&TILEMATRIXSET=w&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&STYLE=default&FORMAT=tiles&tk=' +
        token
      const poiurl =
        'https://t{s}.tianditu.gov.cn/' +
        poiType +
        '/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=' +
        poiName +
        '&TILEMATRIXSET=w&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}&STYLE=default&FORMAT=tiles&tk=' +
        token
      const imagelayers = this.viewer.imageryLayers
      const layerlen = imagelayers.length
      const subdomains = ['0', '1', '2', '3', '4', '5', '6', '7']
      //中台
      const imglayer = new Cesium.WebMapTileServiceImageryProvider({
        //影像底图
        url: new Cesium.Resource({
          url: url,
          headers: {
            Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
          }
        }),
        subdomains,
        subdomains,
        credit: 'tianditu_base',
        layer: 'tdtVecLayer',
        style: 'default',
        maximumLevel: 17,
        format: 'image/jpeg',
        tileMatrixSetID: 'GoogleMapsCompatible', //使用谷歌的瓦片切片方式
        show: true
      })

      const poilayer = new Cesium.WebMapTileServiceImageryProvider({
        //影像底图
        url: new Cesium.Resource({
          url: poiurl,
          headers: {
            Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
          }
        }),
        subdomains: subdomains,
        credit: 'tianditu_poi',
        layer: 'tdtCvaLayer',
        style: 'default',
        format: 'image/jpeg',
        maximumLevel: 17,
        tileMatrixSetID: 'GoogleMapsCompatible', //使用谷歌的瓦片切片方式
        show: true
      })
      imagelayers.addImageryProvider(imglayer, 1)

      imagelayers.addImageryProvider(poilayer, 2)
    },
    handelClose() {}
  },
  mounted() {
    this.initData().then((result) => {
      this.addToMap()
    })
  }
}
</script>

<style lang="scss">
.maptools {
  display: none;
}
.mainMapContainer {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}
.cesium_container {
  width: 100%;
  height: 100%;
  canvas {
    width: 100% !important;
    height: 100% !important;
    touch-action: none;
  }
  .cesium-viewer-bottom,
  .cesium-viewer-selectionIndicatorContainer,
  .cesium-viewer-infoBoxContainer,
  .cesium-viewer-toolbar,
  .cesium-viewer-zoomIndicatorContainer {
    display: none !important;
  }
  .cesium-viewer-navigationContainer {
    left: 0 !important;
  }
}
</style>
