<template>
  <div>
    <div id='container'></div>
    <div id="mouse_state"></div>
  </div>
</template>

<script>
import bigemap3d from '@/utils/bigemap/3dmap'

export default {
  name: "bigeMap3D",
  props: {mapValue: Object},
  watch: {
    mapValue: {
      immediate: true,
      handler(value) {
        if (value.params !== undefined) {
          // console.log("3D地形图：" + value)
          this.mapData = value
          this.level = value.level
          this.center = {lng: value.center[1], lat: value.center[0]}
          this.init()
        }

      }
    }
  },
  data() {
    return {
      A: 40487.57,
      B: 0.00007096758,
      C: 91610.74,
      D: -40467.74,
      level: 10,
      center: {},
    }
  }, mounted() {

  },
  methods: {
    init() {
      let _self = this
      //  高度
      let altitude = this.C * Math.pow((this.A - this.D) / (this.level - this.D) - 1, 1 / this.B)
      // console.log(this.C * Math.pow((this.A - this.D) / (this.level - this.D) - 1, 1 / this.B))
      let center = this.center === [] ? [129.64920, 46.2844] : [this.center.lng, this.center.lat];
      bigemap3d.then(() => {
        // var center = [104.73673266358675,31.463626972537455];
        // console.log(center, 154);
        // window.bmgl.Config.HTTP_URL ='http://www.bigemap.com:9000';
        window.bmgl.Config.HTTP_URL = 'http://49.4.78.194:17143';
        // window.bmgl.Config.HTTP_URL = 'http://localhost:9000';
        let viewer = new bmgl.Viewer('container', {
          // mapId: 'bigemap.zhongkexingtu',
          terrainId: 'bigemap.hl-gaocheng',
          mapId:'bigemap.re-huafu',
        });
        window.viewer=viewer;
        viewer.camera.setView({
          destination: window.bmgl.Cartesian3.fromDegrees(...center, altitude),
          // viewer.camera.computeViewRectangle()
          // orientation: {
          //   heading: 5.737109377827798,
          //   roll: 6.281571490802099,
          //   pitch: -0.3089655832119651,
          // }
        });

        let helper = new bmgl.EventHelper();
        helper.add(viewer.scene.globe.tileLoadProgressEvent, e => {
          var layer=viewer.imageryLayers.get(0);
          layer.imageryProvider._imageryProvider._resource._url=layer.imageryProvider._imageryProvider._resource._url.replace('9000','17143');
          console.log(layer.imageryProvider._imageryProvider._resource._url)
          helper.removeAll();
          helper=null;
        });

        var scene = viewer.scene;
        var handler = new bmgl.ScreenSpaceEventHandler(scene.canvas);
        var ellipsoid = scene.globe.ellipsoid; //得到当前三维场景的椭球体

        var longitudeString = null;
        var latitudeString = null;
        var height = null;
        var cartesian = null;
        var mouse_state = document.getElementById("mouse_state"); //显示状态信息

        // 鼠标移动触发事件
        handler.setInputAction(function (movement) {
          //通过指定的椭球或者地图对应的坐标系，将鼠标的二维坐标转换为对应椭球体三维坐标
          var ray = viewer.camera.getPickRay(movement.endPosition);
          var cartesian = viewer.scene.globe.pick(ray, viewer.scene);
          if (cartesian) {
            //将笛卡尔坐标转换为地理坐标
            var cartographic = ellipsoid.cartesianToCartographic(cartesian);
            //将弧度转为度的十进制度表示
            longitudeString = window.bmgl.Math.toDegrees(cartographic.longitude).toFixed(
              7);
            latitudeString = window.bmgl.Math.toDegrees(cartographic.latitude).toFixed(7);
            //获取相机高度
            height = Math.ceil(viewer.camera.positionCartographic.height).toFixed(
              3);
            mouse_state.innerText =
              `移动：经度: ${longitudeString},纬度:  ${latitudeString} , 相机高度:  ${height} `;
          } else {
            mouse_state.innerText = "";
          }
        }, window.bmgl.ScreenSpaceEventType.MOUSE_MOVE);

        // handler.setInputAction(function (movement) {
        //   console.log(2)
        //   cartesian = viewer.camera.pickEllipsoid(movement.position,
        //     ellipsoid); //movement.endPosition
        //   if (cartesian) {
        //     //将笛卡尔坐标转换为地理坐标
        //     var cartographic = window.bmgl.Cartographic.fromCartesian(cartesian);
        //     longitudeString = window.bmgl.Math.toDegrees(cartographic.longitude).toFixed(
        //       3);
        //     latitudeString = window.bmgl.Math.toDegrees(cartographic.latitude).toFixed(3);
        //     //获取相机高度
        //     height = Math.ceil(viewer.camera.positionCartographic.height);
        //     mouse_state.innerText =
        //       `左键双击 ：( 经度: ${longitudeString.toFixed(5)},纬度:  ${latitudeString.toFixed(5)} , 相机高度:  ${height}  )`;
        //   } else {
        //     mouse_state.innerText = '';
        //   }
        // }, window.bmgl.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
        // 鼠标平移

        //鼠标平移触发事件
        handler.setInputAction(function (movement) {
          var p = window.bmgl.Cartographic.fromCartesian(viewer.camera.position);
          cartesian = viewer.camera.pickEllipsoid(movement.position,
            ellipsoid); //movement.endPosition
          if (cartesian) {
            //将笛卡尔坐标转换为地理坐标
            var cartographic = window.bmgl.Cartographic.fromCartesian(cartesian);
            longitudeString = window.bmgl.Math.toDegrees(cartographic.longitude);
            //.toFixed(3);
            latitudeString = window.bmgl.Math.toDegrees(cartographic.latitude);
            //.toFixed(3);
            //获取相机高度
            height = Math.ceil(viewer.camera.positionCartographic.height);
            mouse_state.innerText =
              `左键抬起 ： 经度: ${longitudeString.toFixed(5)},纬度:    ${latitudeString.toFixed(5)} , 相机高度:  ${height}  `;
          } else {
            mouse_state.innerText = '';
          }
          _self.level = Math.round(_self.D + (_self.A - _self.D) / (1 + Math.pow(height / _self.C, _self.B)));
          _self.center = {lng: window.bmgl.Math.toDegrees(p.latitude), lat: window.bmgl.Math.toDegrees(p.longitude)};
          _self.$emit('changeZoom', _self.level)
          // console.log(_self.level,_self.center)
        }, window.bmgl.ScreenSpaceEventType.LEFT_DOWN);
        // 鼠标缩进触发事件
        handler.setInputAction(function (wheelment) {
          var p = window.bmgl.Cartographic.fromCartesian(viewer.camera.position);
          height = Math.ceil(viewer.camera.positionCartographic.height);
          mouse_state.innerText = `相机高度: ${height} (米)`;
          let position = {
            lng: window.bmgl.Math.toDegrees(p.longitude),
            lat: window.bmgl.Math.toDegrees(p.latitude)
          };
          // 高度转化成2D的地图级别
          _self.level = Math.round(_self.D + (_self.A - _self.D) / (1 + Math.pow(height / _self.C, _self.B)));
          _self.center = position;
          _self.$emit('changeZoom', _self.level)
          // console.log(_self.level,_self.center)
        }, window.bmgl.ScreenSpaceEventType.WHEEL);

        // 地图调整角度触发事件
        viewer.camera.changed.addEventListener(function (e) {
          // console.log("event");
          var p = window.bmgl.Cartographic.fromCartesian(viewer.camera.position);
          _self.level = Math.round(_self.D + (_self.A - _self.D) / (1 + Math.pow(p.height / _self.C, _self.B)));
          _self.center = {lng: window.bmgl.Math.toDegrees(p.latitude), lat: window.bmgl.Math.toDegrees(p.longitude)};
          _self.$emit('changeZoom', _self.level)
          // console.log(_self.level,_self.center)
          // console.log("-----------");
        })


        // 渲染所有风机、塔、拐点标记点位
        // console.log(this.mapData.allPointInfo)
        if (this.mapData.allPointInfo !== null && this.mapData.allPointInfo !== undefined) {
          let defaultImage = {
            heightReference: bmgl.HeightReference.CLAMP_TO_GROUND,
            image: '/img/fengji.png',
            scale: 0.6
          }
          let blueImage = {
            heightReference: bmgl.HeightReference.CLAMP_TO_GROUND,
            image: '/img/fengji/fengjiblue.png',
            scale: 0.2
          }
          let redImage = {
            heightReference: bmgl.HeightReference.CLAMP_TO_GROUND,
            image: '/img/fengji/fengjired.png',
            scale: 0.2
          }
          let image = [{
            billboard: {
              heightReference: bmgl.HeightReference.CLAMP_TO_GROUND,
              image: '/img/fengji/fengjigreen.png',
              scale: 0.2
            }
          }, {
            billboard: {
              heightReference: bmgl.HeightReference.CLAMP_TO_GROUND,
              image: '/img/fengji/fengjiyellow.png',
              scale: 0.2
            }
          }]
          let data = this.mapData.allPointInfo
          let i = 0
          for (let fan of data.fan) {
            if (i > 1) i = 0
            for (let item of fan.data) {
              if(fan.type === 'project'){
                viewer.entities.add({
                  position: bmgl.Cartesian3.fromDegrees(Number(item.longitudeFan), Number(item.latitudeFan)),
                  billboard: redImage
                });
              }else {
                if (item.type !== null) {
                  if (item.type === '新') {
                    viewer.entities.add({
                      position: bmgl.Cartesian3.fromDegrees(Number(item.longitudeFan), Number(item.latitudeFan)),
                      billboard: defaultImage
                    });
                  } else {
                    viewer.entities.add({
                      position: bmgl.Cartesian3.fromDegrees(Number(item.longitudeFan), Number(item.latitudeFan)),
                      billboard: blueImage
                    });
                  }
                } else {
                  viewer.entities.add({
                    position: bmgl.Cartesian3.fromDegrees(Number(item.longitudeFan), Number(item.latitudeFan)),
                    billboard: image[i].billboard
                  });
                }
              }
            }
            i++;
          }
          for (let coordinatesList of data.coordinatesList) {
            for (let key in coordinatesList) {
              let coordinates = coordinatesList[key]
              for (let item of coordinates) {
                if (item.length > 0) {
                  let latlngs = []
                  for (let coor of item) {
                    latlngs.push(Number(coor.longitude))
                    latlngs.push(Number(coor.latitude))
                  }
                  viewer.entities.add({
                    polygon: {
                      hierarchy: bmgl.Cartesian3.fromDegreesArray(latlngs),
                      extrudedHeight: 0,
                      perPositionHeight: true,
                      material: bmgl.Color.CYAN.withAlpha(0),
                      outline: true,
                      outlineColor: bmgl.Color.CYAN
                    },
                  });
                }
              }
            }
          }
          // 项目或者场站id

          let id = this.mapData.id

          for (let item of data.towerList) {
            let marker = viewer.entities.add({
              position: bmgl.Cartesian3.fromDegrees(Number(item.longitude), Number(item.latitude)),
              billboard: {
                heightReference: bmgl.HeightReference.CLAMP_TO_GROUND,
                image: '/largeScreenImg/project.png',
                scale: 0.15
              },
            });
          }
          /*环境监测仪*/
          for (let item of data.weather) {
            let marker = viewer.entities.add({
              position: bmgl.Cartesian3.fromDegrees(Number(item.longitude), Number(item.latitude)),
              billboard: {
                heightReference: bmgl.HeightReference.CLAMP_TO_GROUND,
                image: '/largeScreenImg/huanjingjianceyi.png',
                scale: 0.5
              },
            });
          }
          /*逆变器*/

          for (let inverter of data.inverter) {
            for (let item of inverter.data) {
              let marker = viewer.entities.add({
                position: bmgl.Cartesian3.fromDegrees(Number(item.longitude), Number(item.latitude)),
                billboard: {
                  heightReference: bmgl.HeightReference.CLAMP_TO_GROUND,
                  image: '/largeScreenImg/nibianqi.png',
                  scale: 0.5
                },
              });
            }
          }
        }
      })
    }
  }
}
</script>

<style scoped>
#container {
  width: 100%;
  height: calc(90vh);
}

#mouse_state {
  position: absolute;
  bottom: 0;
  right: 5%;
  background-color: rgb(160, 160, 160);
  border: 1px solid rgb(89, 103, 116);
  color: rgba(51, 51, 51, 1);
  padding: 0 5px;
}
</style>
