<template>
  <div class="sm-function-module-content ZTGlobal">
    <el-row
      :gutter="5"
      style="border-top: 1px dashed #02a7f0; padding: 0.5rem; color: #ffffff"
    >
      {{ viewshed }}
      <el-col style="padding: 0.5rem">
        观察者高度(米):
        <el-input-number
          size="small"
          label="观察者高度:"
          min="0"
          max="50"
          :step="0.5"
          precision="1"
          v-model="personH"
        ></el-input-number>
      </el-col>
      <el-col :span="8">
        <el-button size="mini" type="default" @click="addGCD">
          添加观察点
        </el-button>
      </el-col>
      <el-col :span="8">
        <el-button size="mini" type="default" @click="addTagget">
          添加目标点
        </el-button>
      </el-col>
      <el-col :span="7">
        <el-button size="mini" type="default" @click="clearViewshed">
          清除
        </el-button>
      </el-col>
      <!-- <el-col :span="7">
        <el-button size="mini" type="default" @click="changeView"
          >切换视角</el-button
        >
      </el-col> -->
    </el-row>
    <!-- </el-row> -->
    <!-- 绿线为可见区域，红线为不可见区域 -->

    <div class="boxchild">
      <el-button type="primary" size="mini" @click="ExportResult">
        导出结果
      </el-button>
      <!-- <el-button type="primary" size="mini" @click="clear">清除</el-button> -->
    </div>
  </div>
</template>

<script>
import { init } from "@/utils/MapHelper/sightCorridor.js";
// import RSAnalysis from "@/utils/MapHelper/RSAnalysis.js";
// 观察点，目标点
import { Cartesian2toDegrees } from "@/utils/MapHelper/help.js";
let sightline, handlerPoint, points;

import { download } from "@/utils/MapHelper/help.js";
export default {
  // mixins: [RSAnalysis],
  data() {
    return {
      addViewFlag: false,
      addTargetFlag: false,
      isFrom2To: true,
      personH: 1.8,
      proform: {
        horizontal: 2,
        vertical: 1,
        distance: 200,
        visibleLine: true,
      },
      viewshed: null,
      points: [],
    };
  },
  mounted() {
    // if (this.analysisShow && this.skylineComb) {
    // }
    this.$nextTick(() => {
      this.initPoint();
      // init();
    });
  },
  methods: {
    initViewshed3D(point1, point2) {
      this.clearViewshed();
      // 创建可视域分析对象
      var viewshed3D = new Cesium.ViewShed3D(scene);
      viewshed3D.visibleAreaColor =
        Cesium.Color.fromCssColorString("rgba(255,0,0,0.5)");
      viewshed3D.hiddenAreaColor =
        Cesium.Color.fromCssColorString("rgba(0,255,0,0)");
      viewshed3D.viewPosition = point1;
      viewshed3D.build();
      viewshed3D.setDistDirByPoint(point2);
      viewshed3D.horizontalFov = 40;
      viewshed3D.verticalFov = 20;
      this.viewshed = viewshed3D;
    },
    clearViewshed() {
      if (!this.viewshed) return;
      this.viewshed.removeAllClipRegion();
      this.viewshed.distance = 0.1;
      this.clearScope();
    },
    ExportResult() {
      var legends = [];
      legends.push({ name: "视廊分析", value: "", unit: "" });
      legends.push({ name: "观察者高度", value: this.personH, unit: "米" });
      legends.push({ name: "观察者坐标", value: this.points[0], unit: "" });
      legends.push({ name: "目标点坐标", value: this.points[1], unit: "" });
      var promise = scene.outputSceneToFile();
      Cesium.when(promise, (base64data) => {
        download(base64data, legends);
      });
    },

    /**
     * 添加观察点
     */
    addGCD() {
      let that = this;
      this.clearScope();
      sightline.removeAllTargetPoint();
      that.addViewFlag = true;
      that.addTargetFlag = false;
      // that.isFrom2To = true;
      if (handlerPoint) handlerPoint.clear();
      this.setInput();
    },
    /**
     * 添加目标点
     */
    addTagget() {
      let that = this;
      that.addViewFlag = false;
      that.addTargetFlag = true;
      this.setInput();
    },
    initPoint() {
      sightline = new Cesium.Sightline(viewer.scene);
      sightline.build();
      handlerPoint = new Cesium.DrawHandler(viewer, Cesium.DrawMode.Point);
      viewer.scene.undergroundMode = false;
    },
    /**
     * 输入点
     */
    setInput() {
      var that = this;
      // that.changCount = 0;
      handlerPoint = new Cesium.DrawHandler(viewer, Cesium.DrawMode.Point);
      handlerPoint.activate();
      handlerPoint.drawEvt.addEventListener(function (result) {
        var point = result.object;
        // point.show = false;
        var position = result.object.position;
         
        //将获取的点的位置转化成经纬度
        var cartographic = Cartesian2toDegrees(position);
        // if (cartographic[2] < 0) cartographic[2] = 0;
        cartographic[2] += that.personH;
        //添加观察点
        if (that.addViewFlag) {
          //设置观察点

          sightline.viewPosition = cartographic;
          that.addViewFlag = false;
          viewer.entities.removeById("gcPoint");
          var labelentity = new Cesium.Entity({
            id: "gcPoint",
            position: Cesium.Cartesian3.fromDegrees(
              cartographic[0],
              cartographic[1],
              cartographic[2]
            ),
            point: {
              // 点的大小（像素）
              pixelSize: 10,
              // 点位颜色，fromCssColorString 可以直接使用CSS颜色
              color: Cesium.Color.RED,
              // 边框颜色
              outlineColor: Cesium.Color.fromCssColorString("#fff"),
              // 边框宽度(像素)
              outlineWidth: 2,
              // 显示在距相机的距离处的属性，多少区间内是可以显示的
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                0,
                1500
              ),
              // 是否显示
              show: true,
            },
            label: {
              show: true,
              text: "观察点",
              font: "15px sans-serif",
              pixelOffset: new Cesium.Cartesian2(0, -20), //文字偏移
              fillColor: Cesium.Color.RED,
              // backgroundColor:new Cesium.Color(0, 0, 0, 1),
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                0,
                1500
              ), //达到一定高度隐藏
              disableDepthTestDistance: Number.POSITIVE_INFINITY,
            },
          });
          // that.points.push(entity)
          // viewer.entities.add(entity);
          that.gcPoint = cartographic;
          points.push(labelentity);
          viewer.entities.add(labelentity);
        } else if (that.addTargetFlag) {
          //添加目标点
          //设置目标点
          sightline.addTargetPoint({
            position: cartographic,
            name: "目标点",
          });
          viewer.entities.removeById("targetPoint");
          var labelentity = new Cesium.Entity({
            id: "targetPoint",
            position: Cesium.Cartesian3.fromDegrees(
              cartographic[0],
              cartographic[1],
              cartographic[2]
            ),
            point: {
              // 点的大小（像素）
              pixelSize: 10,
              // 点位颜色，fromCssColorString 可以直接使用CSS颜色
              color: Cesium.Color.RED,
              // 边框颜色
              outlineColor: Cesium.Color.fromCssColorString("#fff"),
              // 边框宽度(像素)
              outlineWidth: 2,
              // 显示在距相机的距离处的属性，多少区间内是可以显示的
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                0,
                1500
              ),
              // 是否显示
              show: true,
            },
            label: {
              show: true,
              text: "目标点",
              font: "15px sans-serif",
              pixelOffset: new Cesium.Cartesian2(0, -20), //文字偏移
              fillColor: Cesium.Color.RED,
              // backgroundColor:new Cesium.Color(0, 0, 0, 1),
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                0,
                1500
              ), //达到一定高度隐藏
              disableDepthTestDistance: Number.POSITIVE_INFINITY,
            },
          });
          points.push(labelentity);
          viewer.entities.add(labelentity);
          that.addTargetFlag = false;
          that.targetPoint = cartographic;
          sightline.build();
          that.ComputationalPerspective();
        }
        handlerPoint.deactivate();
        handlerPoint.clear();
      });
    },
    /**
     * 计算方位角
     * @param {} points
     */
    ComputationalPerspective() {
      // this.changCount++;
      var point1;
      var point2;
      if (
        sightline.viewPosition[0] == 0 ||
        sightline.viewPosition[1] == 0 ||
        sightline._currentTargetPoint[0] == 0 ||
        sightline._currentTargetPoint[1] == 0
      ) {
        this.$message.warning("请添加观察点或目标点");
        return;
      }
      if (this.isFrom2To) {
        point1 = [
          sightline.viewPosition[0],
          sightline.viewPosition[1],
          sightline.viewPosition[2],
        ];
        point2 = [
          sightline._currentTargetPoint[0],
          sightline._currentTargetPoint[1],
          sightline._currentTargetPoint[2],
        ];
      } else {
        point1 = [
          sightline._currentTargetPoint[0],
          sightline._currentTargetPoint[1],
          sightline._currentTargetPoint[2],
        ];
        point2 = [
          sightline.viewPosition[0],
          sightline.viewPosition[1],
          sightline.viewPosition[2],
        ];
      }
      var positionA = Cesium.Cartesian3.fromDegrees(
        point1[0],
        point1[1],
        point1[2]
      );
      var positionB = Cesium.Cartesian3.fromDegrees(
        point2[0],
        point2[1],
        point2[2]
      );
      this.points = [point1, point2];
      let finalPosition = new Cesium.Cartesian3();
      let matrix4 = Cesium.Transforms.eastNorthUpToFixedFrame(positionA);
      Cesium.Matrix4.inverse(matrix4, matrix4);
      Cesium.Matrix4.multiplyByPoint(matrix4, positionB, finalPosition);
      Cesium.Cartesian3.normalize(finalPosition, finalPosition);
      
      // const resultHead = Cesium.Math.toDegrees(
      //   Math.atan2(finalPosition.x, finalPosition.y)
      // );
      // const resultPitch = Cesium.Math.toDegrees(Math.asin(finalPosition.z));
      // viewer.camera.setView({
      //   destination: positionA,
      //   orientation: {
      //     heading: Cesium.Math.toRadians(resultHead), // east, default value is 0.0 (north)
      //     pitch: Cesium.Math.toRadians(resultPitch), // default value (looking down)
      //     roll: 0.0, // default value
      //   },
      // });
      this.initViewshed3D(point1, point2);
    },
    /**
     * 停止飞行、漫游、清除图元
     */
    clearScope() {
      viewer.entities.removeAll();
      points = [];
      sightline.removeAllTargetPoint();
      if (handlerPoint) {
        handlerPoint.clear();
        handlerPoint.deactivate();
      }
      // this.tooltip.setVisible(false);
      // viewer.scene.camera.stopFlyCircle();
      // this.changCount = 0;
      // viewer.scene.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
    },
  },
};
</script>

<style>
/* @import "@/views/ConstructionApplication3D/zt.scss"; */
</style>