<!--  -->
<template>
  <div>
    <titles v-if="titleBlock" :titleName="titleName"></titles>
    <div v-if="!map" id="player" class="map"></div>
    <div v-if="map" class="map" id="allmap"></div>
    <!-- <slot></slot> -->
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

// Cesium.Ion.defaultAccessToken =
//   "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhYzM1YjY5ZS04ZGRlLTRiMDItOTdkMy00MGUwZTEyOTY2MTciLCJpZCI6NzYwOTYsImlhdCI6MTYzOTEyMTI3OH0.XVmHCHCR4sduHWa1wUtwsvi-T2A7SeAAeMkeXfmMjXo";
import titles from "../../components/title";
// import "/public/DynamicWallMaterialProperty";
export default {
  name: "mainPage",
  //import引入的组件需要注入到对象中才能使用
  components: { titles },
  data() {
    //这里存放数据
    return {
      MapObj: {},
      viewer: {},
    };
  },
  props: {
    titleBlock: Boolean, //是否显示标题栏
    titleName: String, //标题名称
    mapobj: Object, //map对象
    map: Boolean, //是否使用map
    url_3d: String, //3D加载模型的路径
    init_3d: {
      type: Object,
      default: {
        //初始化参数
        fullscreenButton: true, //是否显示全屏按钮
        longitude: 116.397454, //经度
        latitude: 39.909152, //纬度
        viewHeight: 1000, //视点高度
        rotationAngle: 0, //旋转角度
        viewAngle: -90, //视角角度
        defaultLocation: false, //自动定位到加载模型的位置
      },
    },
    model_3d: {
      type: Object,
      default: () => {
        return { height: 17 }; //模型高度
      },
    },
    sign_3d: {
      //自定义图标
      type: Array,
      default: () => {
        return [
          // {
          //   id: "",
          //   name: "",
          //   longitude: "", //经度
          //   latitude: "", //纬度
          //   signHeight: "", //标记高度
          //   image: "", //图标地址
          //   pixelOffset: [0, 0], //偏移量(x,y)
          //   horizontalOption: "", //水平图标的位置：LEFT-左、RIGHT-右、CENTER-中
          //   verticalOption: "", //垂直图标的位置：CENTER-中间、TOP-顶部、BOTTOM-底部
          //   scale: 0, //缩放比例
          //   show: true, //是否显示
          //   width: 0, //宽
          //   height: 0, //高
          //   label: {},
          // },
        ]; //模型高度
      },
    },
    enclosure_3d: {
      //电子围栏默认数据格式
      type: Array,
      default: () => {
        return [
          // {
          //   id: "",
          //   name: "",
          //   data: [[]], //路径
          //   color: "", //颜色
          //   height: 300, //高度
          //   isAnimation: false, //动画
          // },
        ];
      },
    },

    line_3d: {
      //绘制路径默认数据格式
      type: Array,
      default: () => {
        return [
          // {
          //   id: "1",
          //   name: "边界",
          //   data: [
          //     //路径，高度
          //     [118.361337, 39.607557, 0],
          //     [118.351337, 39.607557, 100],
          //     [118.362337, 39.627557, 0],
          //     [118.371337, 39.607557, 100],
          //     [118.372337, 39.627557, 0],
          //   ],
          //   color: "#73f9f0", //颜色
          //   opacity: 1, //不透明度
          //   width: 5.0, //宽度
          // },
        ];
      },
    },
    heatmap_3d: {
      //绘制路径默认数据格式
      type: Object,
      default: () => {
        return {
          // id: "1",
          // name: "边界",
          // data: [
          //   { x: 118.361337, y: 39.607557, value: 99, radius: 20 },
          //   { x: 118.363337, y: 39.609957, value: 99, radius: 20 },
          // ],
          // color: "#73f9f0", //颜色
          // opacity: 1, //不透明度
          // width: 5.0, //宽度
        };
      },
    },
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    mapobj(newvla) {
      this.MapObj = newvla;
    },
    sign_3d() {
      // console.log("123123",this.viewer)
      // this.viewer.scence.forceRender();
      // this.viewer ={};
      // this.initCesiuim();
    },
  },
  //方法集合
  methods: {
    map_common_addDatasouce(viewer, datasouceName) {
      let datasouce = viewer.dataSources._dataSources.find((t) => {
        return t && t.name == datasouceName;
      });
      if (!datasouce) {
        datasouce = new Cesium.CustomDataSource(datasouceName);
        viewer.dataSources.add(datasouce);
      }
      return datasouce;
    },
    //绘制渐变
    getColorRamp(val) {
      // console.log(val);
      if (val == null) {
        val = {
          0.0: "blue",
          0.1: "cyan",
          0.37: "lime",
          0.54: "yellow",
          1: "red",
        };
      }
      var ramp = document.createElement("canvas");
      ramp.width = 1;
      ramp.height = 100;
      var ctx = ramp.getContext("2d");
      var grd = ctx.createLinearGradient(0, 0, 0, 100);
      for (var key in val) {
        grd.addColorStop(1 - Number(key), val[key]);
      }
      ctx.fillStyle = grd;
      ctx.fillRect(0, 0, 1, 100);
      return ramp;
    },
    //绘制电子围栏
    electronicFencing(viewer) {
      //电子围栏
      //路径
      //颜色
      //高度
      var dataList = this.enclosure_3d;
      dataList.forEach((item) => {
        let coor = Array.prototype.concat.apply([], item.data);
        let datasouce = this.map_common_addDatasouce(viewer, "wall");
        var rgba = Cesium.Color.fromCssColorString(item.color);
        var x = 1.0;
        var flog = true;

        datasouce.entities.add({
          wall: {
            positions: Cesium.Cartesian3.fromDegreesArray(coor),
            maximumHeights: new Array(item.data.length).fill(item.height),
            minimunHeights: new Array(item.data.length).fill(0),
            //颜色
            material: new Cesium.ImageMaterialProperty({
              transparent: true,
              image: this.getColorRamp({
                0.0: rgba.withAlpha(x).toCssColorString().replace(")", ",1.0)"),
                0.045: rgba.withAlpha(x - 0.2).toCssColorString(),
                0.1: rgba.withAlpha(x - 0.4).toCssColorString(),
                0.15: rgba.withAlpha(x - 0.6).toCssColorString(),
                0.37: rgba.withAlpha(x - 0.8).toCssColorString(),
                0.54: rgba.withAlpha(x - 0.9).toCssColorString(),
                1.0: rgba.withAlpha(x - 1.0).toCssColorString(),
              }),
            }),

            //图片
            // material: new Cesium.ImageMaterialProperty({
            //   transparent: true,
            //   image: require("./01.png"),
            // }),
          },
        });
        if (item.isAnimation) {
          //动画
          datasouce.entities.add({
            wall: {
              positions: Cesium.Cartesian3.fromDegreesArray(coor),
              maximumHeights: new Array(item.data.length).fill(item.height),
              minimunHeights: new Array(item.data.length).fill(0),

              material: new Cesium.ColorMaterialProperty(
                new Cesium.CallbackProperty(function () {
                  if (flog) {
                    x = x - 0.03;
                    if (x <= 0.03) {
                      flog = false;
                    }
                  } else {
                    x = x + 0.03;
                    if (x >= 0.97) {
                      flog = true;
                    }
                  }
                  return Cesium.Color.fromCssColorString(item.color).withAlpha(
                    x
                  );
                }, false)
              ),
            },
          });
        }
      });
    },
    //绘制路径
    addLine(viewer) {
      this.line_3d.forEach((item) => {
        if (item && item.data && item.data.length > 0) {
          let datasource = this.map_common_addDatasouce(viewer, "line");
          // datasource.entities.removeAll();
          let positions = Array.prototype.concat.apply([], item.data);
          datasource.entities.add(
            new Cesium.Entity({
              polyline: {
                positions: Cesium.Cartesian3.fromDegreesArrayHeights(positions),
                width: item.width,
                //纯色
                material: Cesium.Color.fromCssColorString(item.color).withAlpha(
                  item.opacity
                ),
                //发光效果
                // material: new Cesium.PolylineGlowMaterialProperty({
                //   color: Cesium.Color.fromCssColorString("#00FF66"),
                //   glowPower: 1,
                // }),
              },
              properties: new Cesium.PropertyBag({
                type: "line",
                details: item,
              }),
            })
          );
        }
      });
    },
    //添加热力图
    addHeatMap(viewer) {
      // 矩形坐标
      var bounds = {
        west: 118.2, //西
        south: 39.5, //南
        east: 118.5, //东
        north: 39.7, //北
      };

      // 初始化CesiumHeatmap
      var heatMap = CesiumHeatmap.create(
        viewer, // 视图层
        bounds, // 矩形坐标
        {
          // heatmap相应参数
          maxOpacity: 0.5,
          minOpacity: 0,
          blur: 0.75,
        }
      );

      console.log(this.heatmap_3d.data, "sourceData");

      // 添加数据 最小值，最大值，数据集
      heatMap.setWGS84Data(0, 100, this.heatmap_3d.data);
      // viewer.zoomTo(viewer.entities);
    },
    initCesiuim() {
      var that = this;
      let viewerOption = {
        fullscreenButton: that.init_3d.fullscreenButton, //是否显示全屏按钮
        animation: false, //是否创建动画小器件，左下角仪表
        baseLayerPicker: false, //是否显示图层选择器
        geocoder: false, //是否显示geocoder小器件，右上角查询按钮
        homeButton: false, //是否显示Home按钮
        infoBox: false, //是否显示信息框
        sceneModePicker: false, //是否显示3D/2D选择器
        selectionIndicator: false, //是否显示选取指示器组件
        timeline: false, //是否显示时间轴
        navigationHelpButton: false, //是否显示右上角的帮助按钮
        scene3DOnly: true, //如果设置为true，则所有几何图形以3D模式绘制以节约GPU资源
        fullscreenElement: document.body, //全屏时渲染的HTML元素,
        useDefaultRenderLoop: true, //如果需要控制渲染循环，则设为true
        targetFrameRate: undefined, //使用默认render loop时的帧率
        showRenderLoopErrors: false, //如果设为true，将在一个HTML面板中显示错误信息
        automaticallyTrackDataSourceClocks: true, //自动追踪最近添加的数据源的时钟设置
        shouldAnimate: true, //时间开始动
      };
      this.viewer = new Cesium.Viewer("player", viewerOption);
      this.viewer._cesiumWidget._creditContainer.style.display = "none"; // 隐藏版权

      var tileset = this.viewer.scene.primitives.add(
        new Cesium.Cesium3DTileset({
          url: that.url_3d,
          maximumScreenSpaceError: 50,
        })
        // requestRenderMode:true
      );
      // maximumScreenSpaceError: 1,
      var h = that.model_3d.height;
      tileset.readyPromise
        .then(function (tileset) {
          //调整高度
          var translation = Cesium.Cartesian3.fromArray([0, 0, -100]);
          var m = Cesium.Matrix4.fromTranslation(translation); //fromTranslation()方法
          tileset.modelMatrix = m;
        })
        .otherwise(function (error) {
          console.log(error);
        });

      //判断是否初始化方式
      if (that.init_3d.defaultLocation) {
        //自动定位到模型加载位置
        this.viewer.flyTo(tileset);
      } else {
        //设置初始化参数
        this.viewer.scene.camera.setView({
          destination: new Cesium.Cartesian3.fromDegrees(
            that.init_3d.longitude == "" || that.init_3d.longitude == 0
              ? 116.397454
              : that.init_3d.longitude, //经度
            that.init_3d.latitude == "" || that.init_3d.latitude == 0
              ? 39.909152
              : that.init_3d.latitude, //纬度
            that.init_3d.viewHeight //视点高度
          ),
        });
      }
      this.viewer.scene.camera.setView({
        orientation: {
          heading: Cesium.Math.toRadians(that.init_3d.rotationAngle), //水平旋转的角度
          pitch: Cesium.Math.toRadians(that.init_3d.viewAngle), //视角角度 从上往下看为-90
          roll: 0, //
        },
      });

      //点击事件
      var handler = new Cesium.ScreenSpaceEventHandler(
        this.viewer.scene.canvas
      );
      handler.setInputAction(function (click) {
        try {
          const pick = that.viewer.scene.pick(click.position);
          var info = { id: pick.id._id, name: pick.id._name };
          // console.log(info);
          that.$emit("clickIcon3d", info);
        } catch {}
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      handler.setInputAction(function (event) {
        let cartesian = that.viewer.scene.pickPosition(event.position);
        let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        let lng = Cesium.Math.toDegrees(cartographic.longitude); // 经度
        let lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度
        let alt = cartographic.height; // 高度
        let coordinate = {
          longitude: Number(lng.toFixed(9)),
          latitude: Number(lat.toFixed(9)),
          altitude: Number(alt.toFixed(3)),
        };
        // console.log("模型上的点:", coordinate);
        that.$emit("coordinate", coordinate);
      }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

      //添加自定义点
      // var enetity = this.viewer.entities.add({
      //   id: 12,
      //   name: "标点",
      //   position: new Cesium.Cartesian3.fromDegrees(118.361337, 39.607557, 10),
      //   point: {
      //     pixelSize: 10, //一个数字属性，以像素为单位指定大小。
      //     color: Cesium.Color(223, 20, 24, 0.5), //颜色
      //     outlineWidth: 2, //轮廓宽度
      //     outlineColor: Cesium.Color(20, 20, 20, 0.5),
      //   },
      // });
      // this.viewer.flyTo(enetity);

      // 添加自定义图标
      var enetity_billboard_list = [];
      for (let i = 0; i < that.sign_3d.length; i++) {
        const item = that.sign_3d[i];
        var enetity_billboard = this.viewer.entities.add({
          id: item.id,
          name: item.name,
          position: new Cesium.Cartesian3.fromDegrees(
            item.longitude,
            item.latitude,
            item.signHeight
          ),
          label: {
            //文字标签
            text: item.label.text, //文字内容label
            font: item.label.font, // 15pt monospace
            scale: item.label.scale, //缩放label
            style: Cesium.LabelStyle.FILL,
            fillColor: Cesium.Color.WHITE,
            pixelOffset: new Cesium.Cartesian2(
              item.label.pixelOffsetX,
              item.label.pixelOffsetY
            ), //偏移量v
            showBackground: false, //labelShowBackground
            backgroundColor: new Cesium.Color(
              26 / 255,
              196 / 255,
              228 / 255,
              1.0
            ), //背景颜色labelBackgroundColor
          },
          billboard: {
            image: item.image, //图标地址
            horizontalOrigin: Cesium.HorizontalOrigin[item.horizontalOption], //图标的位置：LEFT-左、RIGHT-右、CENTER-中
            verticalOrigin: Cesium.VerticalOrigin[item.verticalOption], //图标的位置：CENTER-中间、TOP-顶部、BOTTOM-底部、BASELINE-底部
            pixelOffset: new Cesium.Cartesian2(
              item.pixelOffset[0],
              item.pixelOffset[1]
            ), //偏移量(x,y)
            scale: item.scale, //缩放比例
            show: item.show, //是否显示
            width: item.width, //宽
            height: item.height, //高
          },
        });
        // this.viewer.flyTo(enetity_billboard);
        enetity_billboard_list.push(enetity_billboard);
        // console.log(enetity_billboard_list);
      }

      //添加面
      this.electronicFencing(this.viewer);

      //添加线
      this.addLine(this.viewer);

      console.log("456", this.viewer);
      //添加热力图
      // this.addHeatMap(viewer);

      // let handler3 = new Cesium.ScreenSpaceEventHandler(
      //   this.viewer.scene.canvas
      // );

      //鼠标滑过事件
      // handler.setInputAction(function (movement) {
      //   const pickedObject = viewer.scene.pick(movement.endPosition);
      //   try {
      //     if (pickedObject.id != undefined) {
      //       pickedObject.id.billboard.scale = 1.2;
      //       // entity.label.pixelOffset = new Cesium.Cartesian2(110, -70);
      //       pickedObject.id.label.scale = 0.8;
      //     } else {
      //       for (const item in enetity_billboard_list) {
      //         if (Object.hasOwnProperty.call(enetity_billboard_list, item)) {
      //           const element = enetity_billboard_list[item];
      //           element.billboard.scale = 1.0;
      //           pickedObject.id.label.scale = 0.6;
      //         }
      //       }
      //     }
      //   } catch {}
      // }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    if (this.map) {
      this.MapObj = new BMapGL.Map("allmap"); // 创建Map实例
      this.MapObj.centerAndZoom(new BMapGL.Point(116.28019, 40.049191), 19); // 初始化地图,设置中心点坐标和地图级别
      this.MapObj.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
      this.MapObj.setHeading(64.5);
      this.MapObj.setTilt(73);
      this.$emit("change_map", this.MapObj);
    } else {
      this.initCesiuim();
    }
  },
};
</script>
<style scoped>
.map {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  margin: 0;
}
.btn {
  width: 10vw;
  height: 5vh;
  position: fixed;
  top: 0vh;
  left: 0vw;
  background-color: rgb(145, 145, 145);
}
.btn2 {
  width: 10vw;
  height: 5vh;
  position: fixed;
  top: 0vh;
  left: 10vw;
  background-color: rgb(194, 63, 63);
}
</style>
