<template>
  <div ref="miniMap_container" class="miniMap_container">
    <div class="top-bar">
      <div v-show="layerControl">图层控制</div>
      <div v-show="projectList">工程列表</div>
      <slot name="topBar" />
      <div v-show="partsCheck">部件查看</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'minMap',
  props: {
    layerControl: {
      type: Boolean,
      default: false
    },
    projectList: {
      type: Boolean,
      default: false
    },
    partsCheck: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      footer_height: '0%',
      mapService: ['img', 'theme'],
      baseScene: 'scenes',
      baseTerrain: 'terrain',
      terrain: 'dixing',
      isInit: false, //当前的地图容器对象
      baselayer: [],
      _viewer: null
    }
  },
  computed: {
    AppX: function () {
      return this.$store.getters.AppX
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initMap()
    })
  },
  methods: {
    initData() {
      return this.$store.dispatch('cesiumMap/initGISResource')
    },
    /**
     * 初始化地图
     */
    initMap() {
      return new Promise((resolve, reject) => {
        this.addToMap()
        resolve()
      })
    },
    /**
     * 加载地图
     */
    addToMap() {
      if (this._viewer) this._viewer.destroy()
      let configItem = this.AppX.appConfig.gisResource[this.baseTerrain]
      let url = configItem.config[this.terrain].url
      let layerTitle = configItem.config[this.terrain].name
      // let url =
      //   "https://yeepms.yeec.com.cn/iserver/services/3D-sxgk_dem/rest/realspace/datas/TF_PAPN_DEM@sxgk_base";
      // let layerTitle = "dixing";
      let viewerDiv = this.$refs.miniMap_container
      this._viewer = new Cesium.Viewer(viewerDiv, {
        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._viewer._cesiumWidget._creditContainer.style.display = 'none' //去掉logo
      this.$emit('done')

      this.isInit = true

      this.initCesiumStatus()
      //this._viewer.scene.logarithmicDepthBuffer = false;
      //高动态范围渲染
      //this._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 camera = cartes3
      this._viewer.camera.setView({
        destination: new Cesium.Cartesian3(camera.x, camera.y, camera.z),
        orientation: {
          heading: 0,
          pitch: Cesium.Math.toRadians(-90),
          roll: 0
        }
      })
      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
            })
          }
        }
      })
    },
    /**
     * 地图服务配置
     */
    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
            })
          }
        }
      }
      this.baselayer = baseLayer
    },
    /**
     * 加载初始化场景
     */
    addInitScene() {
      let 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]
            let promise = this._viewer.scene.open(item.url, undefined, {
              autoSetView: false
            })
            Cesium.when(
              promise,
              function (layers) {
                this.scenesIndex += 1
                for (let i = 0; i < layers.length; i++) {
                  let ly = layers[i]
                  ly.selectEnabled = false
                  ly.clearMemoryImmediately = false
                  ly.cullEnabled = false
                  //ly.lodRangeScale=0.01
                  let 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.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() {},
    /**
     * 添加单个坐标点
     */
    addMarker(coordinate) {
      if (this._viewer.entities.getById('marker-gjklp34hj8rii9f9')) {
        this._viewer.entities.removeById('marker-gjklp34hj8rii9f9')
      }
      if (coordinate.length > 1) {
        const position = Cesium.Cartesian3.fromDegrees(coordinate[0], coordinate[1], 0)
        let entity = new Cesium.Entity({
          id: 'marker-gjklp34hj8rii9f9',
          position: position,
          billboard: {
            image: require('@/views/spectrum/common/images/location.png'),
            width: 32,
            height: 32,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            eyeOffset: Cesium.Cartesian3.ZERO,
            disableDepthTestDistance: 9999999
          }
        })
        this._viewer.entities.add(entity)
        this._viewer.flyTo(entity)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.miniMap_container {
  width: 100%;
  height: 100%;
  position: relative;
  .cesium-viewer-navigationContainer {
    display: none !important;
  }
  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 {
    right: unset !important;
    left: 0 !important;
  }
  .top-bar {
    position: absolute;
    z-index: 990;
    top: 13px;
    right: 17px;
    display: block;
    border-radius: 4px;
    box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.4);
    background-color: #fff;
    > div {
      width: 82px;
      height: 38px;
      line-height: 38px;
      text-align: center;
      float: left;
      font-size: 14px;
      cursor: pointer;
      color: #606266;
      position: relative;
      &:hover {
        color: #409eff;
      }
      &:nth-child(n + 2) {
        &::before {
          content: '';
          display: block;
          width: 1px;
          height: 20px;
          position: absolute;
          top: 9px;
          background-color: #d1d4da;
          left: -0.5px;
          color: #606266;
          font-size: 18px;
        }
      }
    }
  }
}
</style>
