<template>
  <div class="ProjectMap" id="ProjectMap" v-if="show">
    <ComInfoBox />
  </div>
</template>

<script>
import Vue from 'vue'
import ComInfoBox from '@/views/groupPage/components/ComInfoBox.vue'
import monitorTree from '@/views/groupPage/districtPageModules/customTools/monitorTree.vue'
import pbsTree from '@/views/groupPage/districtPageModules/customTools/pbsTree.vue'
import trailJson from './mapJson/TF_PC_PSYS_GHPIPE_B.json'
import { PolylineTrailLinkMaterialProperty } from '@/views/groupPage/util'
const layer_lx = [
  {
    layerName: 'NETWORK_SJ_PSWS_Node@sxgk#1',
    sceneName: 'hnyy_sj_lx',
    key: 'geometry',
    value: 'lxfxfw'
  },
  {
    layerName: 'NETWORK_SJ_PSWS@sxgk#1',
    sceneName: 'hnyy_sj_lx',
    key: 'geometry',
    value: 'lxfxfw'
  },
  {
    layerName: 'NETWORK_SJ_PSYS_Node@sxgk#1',
    sceneName: 'hnyy_sj_lx',
    key: 'geometry',
    value: 'lxfxfw'
  },
  {
    layerName: 'NETWORK_SJ_PSYS@sxgk#1',
    sceneName: 'hnyy_sj_lx',
    key: 'geometry',
    value: 'lxfxfw'
  },
  {
    layerName: 'NETWORK_SJ_PSHS_Node@sxgk#1',
    sceneName: 'hnyy_sj_lx',
    key: 'geometry',
    value: 'lxfxfw'
  },
  {
    layerName: 'NETWORK_SJ_PSHS@sxgk#1',
    sceneName: 'hnyy_sj_lx',
    key: 'geometry',
    value: 'lxfxfw'
  }
]
const gLayerList = [
  'NETWORK_SJ_PSWS@sxgk#1',
  'NETWORK_SJ_PSYS@sxgk#1',
  'NETWORK_SJ_PSWS_Node@sxgk#1',
  'NETWORK_SJ_PSYS_Node@sxgk#1',
  'TF_SJ_PSYS_JG_B_3D@sxgk#1',
  'TF_SJ_PSYS_JG_B_3D@sxgk#2',
  'TF_SJ_PSWS_JG_B_3D@sxgk#2',
  'TF_SJ_PSWS_JG_B_3D@sxgk#1'
]
export default {
  name: 'ProjectMap', //三维底图
  components: {
    ComInfoBox
  },
  props: {
    show: {}
  },
  data() {
    return {
      baselayer: [],
      baseScene: 'scenes',
      baseTerrain: 'terrain',
      terrain: 'dixing',
      mapService: ['img', 'theme'],
      //
      monitorTreeInfo: null
    }
  },
  watch: {
    show(val) {
      if (val) {
        this.$nextTick(() => {
          this.initData().then((result) => {
            this.addToMap()
          })
        })
      } else {
        this.resetData()
      }
    }
  },
  computed: {
    mapConfig() {
      return this.$store.state.bigScreen.mapConfig
    }
  },
  methods: {
    initData() {
      return this.$store.dispatch('bigScreen/initGISResource')
    },
    //加载地图
    addToMap() {
      var viewer = new Cesium.Viewer('ProjectMap', {
        navigation: false,
        contextOptions: {
          webgl: {
            alpha: false,
            depth: true,
            stencil: true,
            antialias: true,
            premultipliedAlpha: true,
            preserveDrawingBuffer: true, //通过canvas.toDataURL()实现截图需要将该项设置为true
            failIfMajorPerformanceCaveat: false
          },
          allowTextureFilterAnisotropic: true
        },
        // skyAtmosphere: false,
        timeline: false,
        animation: false,
        infoBox: false,
        selectionIndicator: false //设置绿色框框不可见
      })
      this.viewer = viewer
      window.viewer = viewer
      this.$store.state.bigScreen.isInitViewer = true
      this.$store.state.bigScreen.mapContainerId = 'ProjectMap'
      //去掉logo
      viewer._cesiumWidget._creditContainer.style.display = 'none'
      //地图配置
      this.sceneSetting(viewer)
      this.addRoad()
      this.addTrail()
      this.initBaseMap()
      //当前项目位置
      const initPosition = this.mapConfig.initPosition
      const carto = Cesium.Cartographic.fromDegrees(
        parseFloat(initPosition.lon),
        parseFloat(initPosition.lat),
        parseFloat(initPosition.height)
      )
      const cartes3 = Cesium.Cartographic.toCartesian(carto)
      const camera = cartes3
      viewer.camera.setView({
        //倾斜设置
        //new Cesium.Cartesian3(camera.x, camera.y, camera.z)
        destination: { x: -2002099.8064685483, y: 5125053.48587751, z: 3240386.7848629407 },
        orientation: {
          heading: 6.241173904929705,
          pitch: -0.3248275425737035,
          roll: 6.283185307179586
          // heading: 0,
          // pitch: Cesium.Math.toRadians(-90),
          // roll: 0
        }
      })
      this.addInitScene()
      this.addTerrain()
      this.initModulesContentShow()
    },
    addRoad() {
      let viewer = this.viewer
      let promise = Cesium.GeoJsonDataSource.load(trailJson, {
        clampToGround: true //贴地设置
      }) //geojson面数据
      promise.then(function (dataSource) {
        viewer.dataSources.add(dataSource)
        var entities = dataSource.entities.values
        for (var o = 0; o < entities.length; o++) {
          var r = entities[o]
          r.polyline.width = 10 //添加默认样式
          ;(r.polyline.material = new Cesium.PolylineGlowMaterialProperty({
            glowPower: 0.1, //一个数字属性，指定发光强度，占总线宽的百分比。
            color: Cesium.Color.DARKBLUE.withAlpha(0.5)
          })),
            10
        }
      })
    },
    //添加尾迹线
    addTrail() {
      let viewer = this.viewer
      let trailLineColor = null
      trailLineColor = new Cesium.Color(0, 2.88, 23.9, 1.0) //初始化尾迹线颜色
      Cesium.Math.setRandomNumberSeed(0) //设置随机数种子
      let promise2 = Cesium.GeoJsonDataSource.load(trailJson, {
        clampToGround: true //贴地设置
      }) //geojson面数据
      promise2.then(function (dataSource) {
        viewer.dataSources.add(dataSource)
        var entities = dataSource.entities.values
        for (var o = 0; o < entities.length; o++) {
          var r = entities[o]
          r.polyline.width = 4 //添加默认样式
          r.polyline.material = new PolylineTrailLinkMaterialProperty(
            trailLineColor,
            require('@/views/groupPage/images/trail.png'),
            2000
          )
        }
      })
    },
    //场景设置
    sceneSetting(viewer) {
      var scene = viewer.scene
      // //开启泛光
      // viewer.scene.bloomEffect.show = true
      // scene.bloomEffect.threshold = '1'
      // scene.bloomEffect.bloomIntensity = '0.3'
      // // 开启hdr
      // scene.hdrEnabled = true
      // //开启抗锯齿
      // scene.postProcessStages.fxaa.enabled = true
      // //显示天空
      // scene.skyBox.show = false
      // // scene.shadowMap.darkness = 1.275 //设置第二重烘焙纹理的效果（明暗程度）
      // scene.sun.show = true //关闭太阳
      // scene.fog.enabled = false //关闭雾气
      // //隐藏大气圈
      // scene.skyAtmosphere.show = false
      //地形深度测试
      scene.globe.depthTestAgainstTerrain = true
      // //当 Cesium 单个模型过长时，会遇到某些视角模型显示不完整的问题
      // // scene.logarithmicDepthBuffer = false;
      // //高动态范围渲染
      // scene.highDynamicRange = 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)
    },
    //地图服务配置
    baseMapConfig() {
      const source = this.mapConfig.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
            })
          }
        }
      }
      this.baselayer = baseLayer
    },
    //初始化基础底图
    initBaseMap() {
      this.baseMapConfig()
      let layerInfo = this.baselayer
      layerInfo.forEach((item) => {
        if (item.show) {
          const gisItem = this.mapConfig.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
            })
          }
        }
      })
    },
    //加载初始化场景
    addInitScene() {
      var scenes = this.mapConfig.gisResource[this.baseScene]
      if (scenes && scenes.config) {
        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) {
                for (var i = 0; i < layers.length; i++) {
                  var ly = layers[i]
                  ly.selectEnabled = true
                  ly.clearMemoryImmediately = false
                  ly.cullEnabled = false
                  //ly.lodRangeScale=0.01
                  //初始化流向显示
                  if (layer_lx.some((item) => item.layerName == ly.name)) {
                    ly.textureUVSpeed = new Cesium.Cartesian2(-1.0, 0)
                  }
                  //初始化建筑物隐藏
                  if (ly.name === 'TF_PAPN_BUILD@sxgk_base') {
                    ly.visible = false
                  }
                  ly.refresh()
                }
                // if (!this.AppX.runtimeConfig.activeView.scene.pickPositionSupported) {
                //   console.error('不支持深度纹理,无法拾取位置！')
                // }
              }.bind(this),
              function (e) {
                console.error('加载SCP失败，请检查网络连接状态或者url地址是否正确？')
              }
            )
          }.bind(this)
        )
      }
      // setTimeout(() => {
      //   this.defaultUpdepth()
      // }, 5000)
    },
    //地形加载
    addTerrain() {
      var viewer = this.viewer
      var configItem = this.mapConfig.gisResource[this.baseTerrain]
      var type = configItem.type
      var url = configItem.config[this.terrain].url
      var layerTitle = configItem.config[this.terrain].name
      switch (type) {
        case 'ext_terrain':
          viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
            url: url,
            requestWaterMask: true,
            requestVertexNormals: true,
            credit: layerTitle
          })
          viewer.terrainProvider.isCreateSkirt = false //关闭地表透明后出现的网格
          break
        case 'terrain':
          viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
            url: url,
            requestWaterMask: true,
            requestVertexNormals: true,
            credit: layerTitle,
            isSct: true
          })
          viewer.terrainProvider.isCreateSkirt = false //关闭地表透明后出现的网格
          break
      }
    },
    //默认抬升
    defaultUpdepth() {
      const layers = window.viewer.scene.layers
      //默认抬升
      const style3D = new Cesium.Style3D()
      style3D.altitudeMode = 0
      style3D.bottomAltitude = this.mapConfig.downDepth
      gLayerList.forEach((item) => {
        var layer = layers.find(item)
        if (layer) {
          layer.style3D = style3D
          layer.refresh()
        }
      })
    },
    //初始化显示模块内容
    initModulesContentShow() {
      const monitorTreeConstructor = Vue.extend(monitorTree)
      this.monitorTreeInfo = new monitorTreeConstructor({
        store: this.$store
      }).$mount()
      //
      const pbsTreeConstructor = Vue.extend(pbsTree)
      const pbsTreeInfo = new pbsTreeConstructor({
        store: this.$store
      }).$mount()
      pbsTreeInfo.externalInit()
    },
    resetData() {
      window.viewer = null
      this.$store.dispatch('bigScreen/resetState')
      this.monitorTreeInfo.clearDataSource()
    }
  }
}
</script>

<style lang='scss' scoped>
.ProjectMap {
  width: 100%;
  height: 100%;
  position: relative;
  background: #000;
}
</style>