<template>
  <div id='cesiumContainer'>
  </div>
  <!-- 底图切换按钮 -->
  <div class="maptab">
    <div class="maptabs_box" :style="cursor" @mouseover="expandMapList" @mouseleave="collapseMapList">
      <div class="layer1" :style="{ backgroundImage: 'url(' + mapList[0].bg + ')' }" @click="switchMap(0)">
        <div class="title">{{ mapList[0].name }}</div>
      </div>
      <div :class="[expand ? 'layer3' : 'layer2']" :style="{ backgroundImage: 'url(' + mapList[1].bg + ')' }" @click="switchMap(1)">
        <div class="title">{{ mapList[1].name }}</div>
      </div>

    </div>
  </div>
  <!-- 工具栏 -->
  <div class="tools">
    <div class="item" @click="zoomIn">
      <img src="@/assets/img/zoomIn.png" />
    </div>
    <div class="item" @click="zoomOut">
      <img src="@/assets/img/zoomout.png" />
    </div>
    <div class="item" @click="reset">
      <img src="@/assets/img/located.png" />
    </div>
    <div class="item">
      <img src="@/assets/img/measureLength.png" />
    </div>
    <div class="item" style="border:0px">
      <img src="@/assets/img/measureArea.png" />
    </div>
  </div>
  <!-- <div class="maptabs_box" :style="cursor" @mouseover="expandMapList" @mouseleave="collapseMapList">
     
      <div
        class="layer1"
        :style="{backgroundImage:'url('+mapList[0].bg+')'}"
        @click="switchMap(0)"
      >
        <div class="title">{{mapList[0].name}}</div>
      </div>
      <div
        :class="[expand?'layer3':'layer2']"
        :style="{backgroundImage:'url('+mapList[1].bg+')'}"
        @click="switchMap(1)"
      >
        <div class="title">{{ mapList[1].name }}</div>
      </div>
    </div> -->

  <!-- 图层管理 -->
  <n-tree block-line :data="treeData" :default-expanded-keys="defaultExpandedKeys" checkable expand-on-click selectable
    class="layer-tree"></n-tree>
</template>

<script>
import { useRouter } from 'vue-router'
import { ref, reactive, onMounted, toRefs } from 'vue'
import axios from 'axios'
import { repeat } from 'seemly'
import sallitePng from '@/assets/img/satelliteMap.png'
import TDMapPng from '@/assets/img/TDMap.png'
import AdministrtivePng from '@/assets/img/Administrative.png'

function createData(level = 4, baseKey = "") {
  if (!level)
    return void 0;
  return repeat(6 - level, void 0).map((_, index) => {
    const key = "" + baseKey + level + index;
    return {
      label: createLabel(level),
      key,
      children: createData(level - 1, key)
    };
  });
}

function createLabel(level) {
  if (level === 4)
    return "图层四";
  if (level === 3)
    return "图层三";
  if (level === 2)
    return "图层二";
  if (level === 1)
    return "图层一";
  return "";
}

export default {
  name: 'HomePage',
  components: {

  },
  setup(props) {
    const router = useRouter()

    const data = {
      viewer: null,
      mapList: [
        { name: '电子图', bg: TDMapPng },
        { name: '影像图', bg: sallitePng },
        { name: '行政区划图', bg: AdministrtivePng }
      ],
      cursor: { cursor: '' },
      expand: false,
      mapChooseIndex: 0,
      currentChooseIndex: 0,
      //测距
      tempEntities: [],
      pointNum: 0,
      floatingPoint: undefined,
      activeShape: undefined
    }
    function toSystem() {
      router.push({ path: '/login' })
    }


    const initMap = () => {
      //设置相机初始飞到中国上空
      // Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(90, -20, 110, 90)
      data.viewer = new Cesium.Viewer('cesiumContainer', {
        // 右上角 搜索
        geocoder: false,
        // 右上角 Home
        homeButton: false,
        // 右上角 2D/3D切换
        sceneModePicker: false,
        // 右上角 地形
        baseLayerPicker: false,
        // 右上角 Help
        navigationHelpButton: false,
        // 左下角 圆盘动画控件
        animation: false,
        // 时间轴
        timeline: false,
        // 右小角 全屏
        fullscreenButton: false,
        vrButton: false,
        // 点击要素后提示信息
        infoBox: false,
        selectionIndicator: false,
        // 每个几何实例将只能以3D渲染以节省GPU内存
        scene3DOnly: false,
        // 关闭地球光环
        skyAtmosphere: false,
        // 初始化底图
        // imageryProvider: new Cesium.SingleTileImageryProvider({
        //   url: 'https://gisdata.t-aaron.com/GlobalBkLayer.jpg'
        // }),
        imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
          url: "http://t0.tianditu.gov.cn/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=f634525a82da65f715d168d7ba1899c0",
          layer: "tdtImgLayer",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "GoogleMapsCompatible",//使用谷歌的瓦片切片方式
          show: true
        }),
        shouldAnimate: true,
        orderIndependentTranslucency: false,
        contextOptions: {
          webgl: {
            alpha: true
          }
        }
      })
      //设置相机飞到中国上空
      data.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(116.435314, 40.960521, 10000000.0),
        duration: 5
      })
      renderDistrict()
      renderData()
      // load3dtiles()
    }
    /**
     * wms,wmts,tms,wfs服务的加载方法
     */
    const renderDistrict = () => {
      //加载wms服务
      const wmsLayer = new Cesium.WebMapServiceImageryProvider({
        url: 'https://geoserver.t-aaron.com:4080/geoserver/ows',
        layers: 'liuyang:town',
        parameters: {
          service: 'WMS',
          format: 'image/png',
          transparent: true//务必设置为true,否则不显示底图
        }
      })
      data.viewer.imageryLayers.addImageryProvider(wmsLayer)

      //加载wmts服务
      //加载arcgis server发布的wmts服务
      const arcgisLayer = new Cesium.WebMapTileServiceImageryProvider({
        url: 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSHydroCached/MapServer/WMTS',
        layer: 'USGSHydroCached',
        style: 'default',
        format: 'image/png',
        tileMatrixSetID: 'default028mm',
        maximumLevel: 18,
        credit: 'U. S. Geological Survey'
      })
      data.viewer.imageryLayers.addImageryProvider(arcgisLayer)
      //加载 geoserver发布的wmts服务
      const wmtsurl = 'http://192.168.11.35:8999/geoserver/gwc/service/wmts/rest/sz_pg:yaotanghe1/{style}/{TileMatrixSet}/{TileMatrixSet}:{TileMatrix}/{TileRow}/{TileCol}?format=image/png';
      const wmtsLayer = new Cesium.WebMapTileServiceImageryProvider({
        url: wmtsurl,
        layer: 'sz_pg:yaotanghe1',
        style: '',
        format: "image/png",

        tileMatrixSetID: "EPSG:4326",
        tilingScheme: new Cesium.GeographicTilingScheme(),
        // tilingScheme: new Cesium.GeographicTilingScheme()

        //tileMatrixSetID:"EPSG:900913",//不能设置为4326,否则cesium中不显示
      })
      data.viewer.imageryLayers.addImageryProvider(wmtsLayer)

      //加载wfs服务
      axios.get('https://geoserver.t-aaron.com:4080/geoserver/lusong/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=lusong%3Arivers&maxFeatures=50&outputFormat=application%2Fjson').then((res) => {
        var datasource = Cesium.GeoJsonDataSource.load(res.data)

        data.viewer.dataSources.add(datasource)
        //改变所加载图层的样式
      }).catch((err) => {
        console.log(err)
      })
      //加载tms服务
      const urlTemplateImageryProvider = new Cesium.UrlTemplateImageryProvider({
        url: "https://geoserver.t-aaron.com:4080/geoserver/gwc/service/tms/1.0.0/jiangning%3Avillage-lines@EPSG%3A4326@png",
      })
      data.viewer.imageryLayers.addImageryProvider(urlTemplateImageryProvider)

    }
    /**
     * geojson,wkt,gml等数据的加载
     */
    const renderData = () => {
      //加载本地geojson/geoserver发布的geojson,本地的文件要放在public目录下
      data.viewer.dataSources.add(
        Cesium.GeoJsonDataSource.load(
          //'https://geoserver.t-aaron.com:4080/geoserver/liuyang/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=liuyang%3Aclassification&maxFeatures=50&outputFormat=application%2Fjson',
          '/liuyang.json',
          {
            stroke: Cesium.Color.White,//边框颜色
            fill: Cesium.Color.RED.withAlpha(0.5),//填充颜色
            strokeWidth: 3//边框宽度
          }
        )
      )
      //加载wkt数据

    }
    //加载3dtiles数据
    const load3dtiles = () => {
      //加载倾斜摄影b3dm格式
      const palaceTileset = new Cesium.Cesium3DTileset({
        url: 'https://gisdata.t-aaron.com/b3dm/lusongqu_b3dm/tileset.json',
        //控制切片视角显示的数量，可调节性能
        maximumScreenSpaceError: 2,
        maximumNumberOfLoadedTiles: 100000

      })
      data.viewer.scene.primitives.add(palaceTileset)
      //控制模型的位置
      palaceTileset.readyPromise.then(function (palaceTileset) {
        data.viewer.scene.primitives.add(palaceTileset)
        var heightOffset = 0.0
        var boundingSphere = palaceTileset.boundingSphere//获取3DTiles的bounds范围
        var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center)//获取3DTiles的范围中心点的弧度
        var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0)//模型本身的位置
        var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset)//模型改变的位置
        var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3())//定义模型的改变状态
        palaceTileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation)//修改模型的位置
        data.viewer.zoomTo(palaceTileset, new Cesium.HeadingPitchRange(0.5, -0.2, palaceTileset.boundingSphere.radius * 1.0))
      })
      //定位到三维模型
      data.viewer.zoomTo(palaceTileset)
    }
    /**
     * 鼠标移入展开地图栏
     */
    const expandMapList = () => {
      console.log('222')
      data.cursor = { cursor: 'pointer' }
      data.expand = true
      if (data.currentChooseIndex !== data.mapChooseIndex) {
        data.mapList = data.mapList.reverse()
        data.currentChooseIndex = 0
      }
    }
    /**
     * 鼠标移出收起地图栏
     */
    const collapseMapList = () => {
      console.log('111')
      data.cursor = { cursor: '' }
      data.expand = true
      if (data.currentChooseIndex !== data.mapChooseIndex) {
        //切换底图
        data.mapList = data.mapList.reverse()
        data.currentChooseIndex = 0
      }
    }
    //切换底图
    const switchMap = (index) => {
      console.log(index, '索引')
      data.currentChooseIndex = index

      // switch (data.mapList[index].name) {
      //   case '电子图':
      //     data.tdtImgMap.setVisible(false)
      //     data.tdtLineMap.setVisible(true)
      //     break
      //   case '影像图':
      //     data.tdtImgMap.setVisible(true)
      //     data.tdtLineMap.setVisible(false)
      // }
    }
    // 放大地图
    const zoomIn = () => {
      data.viewer.camera.zoomIn()
      //  let position=data.viewer.camera.position
      //  let cameraHeight=data.viewer.scene.globe.ellipsoid.cartesianToCartographic(position).height;
      //  //每次缩小20倍,参数可改
      //  let moveRate=cameraHeight/20.0
      //  data.viewer.camera.moveBackward(moveRate)
    }
    //缩小地图
    const zoomOut = () => {
      data.viewer.camera.zoomOut()
      //  let position=data.viewer.camera.position;
      //  let cameraHeight=data.viewer.scene.globe.ellipsoid.cartesianToCartographic(position).height
      //  //每次缩小20倍,参数可改
      //  let moveRate=cameraHeight/20.0
      //  data.viewer.camera.moveForward(moveRate)
    }
    //复位
    const reset = () => {
      data.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(116.435314, 40.960521, 10000000.0),
        duration: 5
      })
    }
    //测量空间直线距离
    //根据类型绘制对象
   
   
   
    onMounted(() => {
      initMap()
    })
    return {
      toSystem,
      ...toRefs(data),
      treeData: createData(),
      defaultExpandedKeys: ref(['40', '41']),
      collapseMapList,
      expandMapList,
      switchMap,
      zoomIn,
      zoomOut,
      reset,
     
    }
  },
  
}
</script>
<style lang="scss" scoped>
.tabbar {
  position: absolute;
  width: 80px;
  height: 100px;
  bottom: 15px;
  right: 15px;
  background-color: white;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  span {
    margin-bottom: 10px;
    cursor: pointer;
  }
}

// 图层管理
.layer-tree {
  position: absolute;
  top: 15px;
  left: 15px;
}

//底图切换按钮
.maptab {
  position: absolute;
  right: 0;
  bottom: 15px;

  //底部切换按钮
  .maptabs_box {
    float: right;
    position: relative;
    width: 150px;
    height: 60px;

    .layer1,
    .layer2,
    .layer3 {
      width: 74px;
      height: 60px;
      border: 1px solid #fff;
      box-shadow: 0 2px 2px rgb(0 0 0 /25%);
      position: absolute;
      bottom: 0;
    }

    .layer1 {
      right: 0;

      z-index: 1005;
    }

    .layer2 {
      right: 10px;

      z-index: 1004;
    }

    .layer3 {
      right: 84px;

      z-index: 1004;
    }

    .title {
      position: absolute;
      width: 50px;
      height: 20px;
      right: 0px;
      bottom: 0px;
      text-align: center;
      color: #fff;
      font-weight: 400;
      line-height: 20px;
      background: #2770d4;
    }
  }
}

//工具栏
.tools {
  position: absolute;
  right: 10px;
  bottom: 100px;
  background-color: white;
  border-radius: 6px;

  .item {
    padding: 5px;
    border-bottom: 1px solid rgb(46, 46, 46);
    cursor: pointer;

    img {
      width: 25px;
      height: 25px;
    }
  }
}
</style>
