<!--
  (仅限公司内部使用！！！)
   使用方法： Cesium 官网下载源码，复制到public目录下，cdn 引入以下内容

  <link rel="stylesheet" href="Cesium/Widgets/widgets.css">
  <script src="Cesium/Cesium.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@dvgis/cesium-map"></script>

    方法列表： ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  （。。。完善中）

    //隐藏图层                                                  hideLayer(layerId)
    //显示图层                                                  showLayer(layerId)
    //初始化地图                                                initMap(option=this.mapOption)
    //添加建筑矢量数据，url为建模json数据                          addBuildingData(url)
    //添加图层                                                  addLayer(layer,layerId)
    //移除指定图层                                              removeLayer(layerId)
    //移除所有图层                                              removeAllLayers()
    //指定位置并删除图层                                         flyToPositionWithoutLayers(longitude,latitude,height,heading,pitch,roll)
    //添加图标覆盖物(单个)                                       addBillBoard(longitude,latitude,height,image,option= {},id)
    //添加图标覆盖物(多个)                                       addBillBoards(element,option= {},layerId)           例: this.addBillBoards([[113.682062,34.662187, 0,'/data/device.png']],{scale: 0.1},'device')
    //去除覆盖物                                                removeEntity(id)
    //初始化数据                                                onload()

   信息框  --------------------->
    添加相应的信息框在相应的数组添加数据即可，具体添加可看数组元素注释部分
-->

<template>
  <div class="full" >
    <div class="full" id="viewer-container">
      <danger-circle :viewer="viewer" ref="dangerCircle"></danger-circle>
    </div>
    <info-layer ref="infoLayer" style="background: radial-gradient(transparent,rgba(0,0,0,0.1),rgba(0,0,0,0.5),rgba(0,0,0,1))"
      :box1="box1"
      :box2="box2"
    ></info-layer>
    <tools-bar></tools-bar>
    <el-button size="mini" style="position:absolute;top: 50px;left: 30%;z-index: 99" @click="changeMap">切换地图</el-button>
  </div>
</template>

<script>
 import InfoLayer from "./map-components/InfoLayer";
 import DangerCircle from "./map-components/overlays/dangerCircle";
 import ToolsBar from "./map-components/tools-bar/tools-bar";
 let scratch = new Cesium.Cartesian2();
export default {
  name: "Map3D",
  components: {ToolsBar, DangerCircle, InfoLayer},
  data(){
    return{
      viewer: {},
      //默认场景参数
      mapOption: {
        animation: false, // 动画小组件
        baseLayerPicker: false, // 底图组件，选择三维数字地球的底图（imagery and terrain）。
        fullscreenButton: false, // 全屏组件
        vrButton: false, // VR模式
        geocoder: false, // 地理编码（搜索）组件
        homeButton: false, // 首页，点击之后将视图跳转到默认视角
        infoBox: false, // 信息框
        sceneModePicker: false, // 场景模式，切换2D、3D 和 Columbus View (CV) 模式。
        selectionIndicator: false, //是否显示选取指示器组件
        timeline: false, // 时间轴
        navigationHelpButton: false, // 帮助提示，如何操作数字地球。
        // 如果最初应该看到导航说明，则为true；如果直到用户明确单击该按钮，则该提示不显示，否则为false。
        navigationInstructionsInitiallyVisible: false,
        imageryLayers: [],
        // skyBox: new Cesium.SkyBox({
        //   sources: {
        //     positiveX: '/sky/SKY_u.jpg',
        //     negativeX: '/sky/SKY_r.jpg',
        //     positiveY: '/sky/SKY_b.jpg',
        //     negativeY: '/sky/SKY_l.jpg',
        //     positiveZ: '/sky/SKY_f.jpg',
        //     negativeZ: '/sky/SKY_d.jpg',
        //   }
        // }),
      },
      isRound: true,
      layers: [],
      handle: {},
      box1: [
        // {position: [113.682062,34.702187],title: '汤阴小学',data:[{label: '地点' , value: '汤阴县'},{label: '联系方式' , value: '4664-858585'}],x:0,y:0}
      ],
      box2: [
        // {position: [113.682062,34.702187],data:'我是数据',x:0,y:0},
      ],
    }
  },
  mounted() {
    this.onload();
  },
  methods: {
    //隐藏图层
    hideLayer(layerId){
      this.layers.forEach(item => {
        if(item.layerId==layerId){
          item.layer.show = false;
        }
      })
    },
    //显示图层
    showLayer(layerId){
      this.layers.forEach(item => {
        if(item.layerId==layerId){
          item.layer.show = true;
        }
      })
    },
    changeMap(){
      this.viewer.imageryLayers.removeAll();
      this.viewer.imageryLayers.addImageryProvider(
        new Cesium.BaiduImageryProvider({
          style: 'midnight',
          crs: 'WGS84'
        })

      );
      //定位建筑群位置
      this.flyToPosition(113.682062,34.702187, 2000.0,0,-20.0,0.0);
      this.round();
    },
    //初始化地图
    initMap(option=this.mapOption){
      this.viewer = new Cesium.Viewer("viewer-container",option);
      // 隐藏logo
      this.viewer._cesiumWidget._creditContainer.style.display = "none";
       // viewer.scene.globe.show = false;   // 隐藏地球实体
      this.viewer.imageryLayers.removeAll();
      this.addBaiduLayer()
      this.viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString("rgba(20,56,76,0.5)");
      this.viewer.scene.preRender.addEventListener(this.moveListener);
      // this.addGltf([113.682062,34.702187,0],'/demo/8H.gltf');
    },
    //添加建筑矢量数据，url为建模json数据
    addBuildingData(url){
      this.viewer.scene.primitives.add(
        new Cesium.Cesium3DTileset({url})
      );
    },
    //添加图层
    addLayer(layer,layerId){
      this.layers.push({layerId, layer});
      this.viewer.scene.primitives.add(layer);
    },
    //移除指定图层
    removeLayer(layerId){
      this.layers.forEach(item => {
        if(item.layerId==layerId){
          this.viewer.scene.primitives.remove(item.layer);
        }
      })
    },
    //移除所有信息框
    removeAllBox(){
      this.box1 = [];
      this.box2 = [];
    },
    //添加gltf模型
    addGltf(position=[113.682062,34.702187,0],url,option={scale : 100.0}){
      var scene = this.viewer.scene;
      var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        Cesium.Cartesian3.fromDegrees(position[0],position[1],position[2]));
      var model = scene.primitives.add(Cesium.Model.fromGltf({
        url,
        modelMatrix,
        ...option,
      }));
    },
    //移除所有图层
    removeAllLayers(){
      this.layers.forEach(item => {
        this.viewer.scene.primitives.remove(item.layer);
      })
    },
    //指定相机位置
    flyToPosition(longitude,latitude,height,heading,pitch,roll){
      this.viewer.camera.flyTo({
        destination : Cesium.Cartesian3.fromDegrees(longitude,latitude,height),
        orientation : {
          heading : Cesium.Math.toRadians(heading),
          pitch : Cesium.Math.toRadians(pitch),
          roll : roll
        }
      });
    },
    //指定位置并删除图层
    flyToPositionWithoutLayers(longitude,latitude,height,heading,pitch,roll){
      this.removeAllLayers();
      this.flyToPosition(longitude,latitude,height,heading,pitch,roll);
    },
    //添加图标覆盖物(单个)
    addBillBoard(longitude,latitude,height,image,option= {},id){
      this.viewer.entities.add(
        {
          position : Cesium.Cartesian3.fromDegrees(longitude, latitude,height),
          billboard : {
            id,
          image ,
          ...option
          }
        }
      );
    },
    //添加百度地图地图
    addBaiduLayer(){
      this.viewer.imageryLayers.removeAll();
      this.viewer.imageryLayers.addImageryProvider(
        new Cesium.BaiduImageryProvider({
          style: 'normal',
          crs: 'WGS84'
        })
      );
    },
    //添加图标覆盖物(多个)
    addBillBoards(element,option= {},layerId){
     let layer =  new Cesium.BillboardCollection(option);
     element.forEach(item => {
       layer.add(
         {
           show : true,
           position : Cesium.Cartesian3.fromDegrees(item[0], item[1],item[2]),
           image : item[3],
           ...option
         }
       );
     })
     this.addLayer(layer,layerId)
    },
    //去除覆盖物
    removeEntity(id){
      this.viewer.entities.removeById(id);
    },
    //去除所有覆盖物
    removeAllEntity(){
      this.viewer.entities.removeAll();
    },
    //屏幕坐标转化
    convertScreen(list){
      list.forEach(item => {
        let location = this.viewer.scene.cartesianToCanvasCoordinates(
          Cesium.Cartesian3.fromDegrees(item.position[0], item.position[1], 0),
          new Cesium.Cartesian2()
        );
        if(Cesium.defined(location)) {
          item.x = location.x;
          item.y = location.y;
        }
      })

    },
    //绕点旋转
    round(){
      let _this = this;
      let x= Cesium.Math.toDegrees(_this.viewer.camera.heading);
      this.viewer.scene.preUpdate.addEventListener( () => {
        if(_this.isRound){
         x=x+0.1;
          this.viewer.scene.camera.setView({
            orientation: {
              heading : Cesium.Math.toRadians(x),
              pitch :this.viewer.camera.pitch,
            }
          });
        }
      });
    },
    //相机移动事件
    moveListener(){
      this.convertScreen(this.box1);
      this.convertScreen(this.box2);
    },
    //初始化数据
    onload(){
      //创建场景实例
      this.initMap();
      //初始化弹框图层
      this.$refs['infoLayer'].onload();
      this.$refs['dangerCircle'].onLoad();
      this.addBuildingData('/data/ningxia.json');
      //添加建筑矢量数据
      // this.addBuildingData('http://139.9.103.171/mapData/zhengzhou/tileset.json')
      //定位建筑群位置
      // this.flyToPosition(114.357763,35.924515, 2000.0,0,-20.0,0.0);
      this.flyToPosition(114.357763,35.924515, 2000.0,0,-20.0,0.0);
    },

 }
}
</script>

<style scoped>
  .full{
    width: 100%;
    height: 100%;
  }
</style>
