<template>
  <div v-show="isCutFill" class="cut_fill_box">
    <el-radio v-model="radio" label="cut">地形填挖方分析</el-radio>
    <el-radio v-model="radio" label="smooth">地形平整分析</el-radio>

    <div v-show="radio == 'cut'">
      <div class="cut_fill_centent1">
        填挖深度(米)：
        <el-input
          class="cut_fill_input"
          v-model="height"
          placeholder=""
        ></el-input>
        <br />
        土石方量(立方米)：
        <el-input
          class="cut_fill_input"
          v-model="result"
          placeholder=""
        ></el-input>
      </div>
    </div>

    <div v-show="radio == 'smooth'">
      <div class="cut_fill_centent1">
        平整深度(米)：
        <el-input
          class="cut_fill_input"
          v-model="smooth_height"
          placeholder=""
          readonly="readonly"
        ></el-input>
        <br />
        土石方量(立方米)：
        <el-input
          class="cut_fill_input"
          v-model="result"
          placeholder=""
        ></el-input>
        <br />
        <br />

        土石面积(平方米)：
        <el-input
          class="cut_fill_input"
          v-model="result_area"
          placeholder=""
        ></el-input>
      </div>
    </div>
    <div class="cut_fill_Buttons">
      <el-button size="mini" type="primary" @click="draw">绘制</el-button>
      <el-button size="mini" type="primary" @click="clear">清除</el-button>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
import CutFillAnalysis from "./CutFillAnalysis.js";
let cutFillAnalysis = null;
import { getDsm } from "@/api/analse";
import * as turf from "@turf/turf";

export default {
  name: "TerrainCutFillAnalysis",
  components: {},
  data() {
    return {
      radio: "cut",
      input: "",
      sharedState: store.state,
      height: 300,
      result: null,
      handler_Cut_fill: null,
      array3D: [],
      smooth_height: 0,
    };
  },
  //监听属性 类似于data概念
  computed: {
    isCutFill: function () {
      return this.sharedState.terrain[4];
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //地形抽出部分
    extract(positions) {
      viewer.scene.globe.removeAllExtractRegion();
      viewer.scene.globe.addExtractRegion({
        name: "extract", //名称
        position: positions, //区域
        height: this.height, //开挖深度
        transparent: false, //封边是否透明
        extractHeight: Number(this.height), //抽出高度
        granularity: 1, //精度
      });
    },
    cutana(positions) {
      viewer.scene.globe.removeAllExcavationRegion();
      viewer.scene.globe.addExcavationRegion({
        name: "ggg",
        position: positions,
        height: Number(-this.height),
        transparent: false,
      });
    },
    coordsToWktPolygon(coords) {
      // 检查坐标数组的长度是否为偶数
      if (coords.length % 2 !== 0) {
        throw new Error("Coordinate array length must be even.");
      }

      // 构建WKT Polygon字符串
      let wktPolygon = "POLYGON((";
      for (let i = 0; i < coords.length; i += 2) {
        // 添加经度和纬度对
        wktPolygon += `${coords[i]} ${coords[i + 1]}`;
        // 如果不是最后一对坐标，则添加逗号
        if (i + 2 < coords.length) {
          wktPolygon += ", ";
        }
      }
      // 闭合多边形，添加第一个点
      wktPolygon += `, ${coords[0]} ${coords[1]}))`;

      return wktPolygon;
    },
    async smooth_ana(positions, positions_noHeight, threeArray, height) {
      let data = await getDsm({
        geom: this.coordsToWktPolygon(positions_noHeight),
        type: "min",
      });

      viewer.scene.globe.removeAllExcavationRegion();
      viewer.scene.globe.addExcavationRegion({
        name: "ggg",
        position: positions,
        height: data.data,
        transparent: false,
      });

      this.smooth_height = data.data.toFixed(2);

      let cutVolume = cutFillAnalysis.VolumeAnalysis(threeArray, height);
      that.result = cutVolume.toFixed(2);
    },
    async smooth_ana1(positions, positions_noHeight, threeArray, height) {
      console.log("positions: ", positions);

      let data = await getDsm({
        geom: this.coordsToWktPolygon(positions_noHeight),
        type: "max",
      });

      let newArr = positions.map((item, index) => {
        return (index + 1) % 3 === 0 ? data.data : item;
      });
      viewer.scene.globe.removeAllModifyRegion();
      viewer.scene.globe.addModifyRegion({
        name: "ggg",
        position: newArr,
      });

      this.smooth_height = data.data.toFixed(2);
      // let cutVolume = cutFillAnalysis.VolumeAnalysis1(threeArray, Number(height));
      // console.log('cutVolume: ', cutVolume);

      let newArray = [];
      for (let i = 0; i < positions_noHeight.length; i += 2) {
        // 将每两个连续的元素组合成一个新的数组，并添加到新数组中
        newArray.push([positions_noHeight[i], positions_noHeight[i + 1]]);
      }
      newArray.push(newArray[0]);

      var polygon = turf.polygon([newArray]);

      this.result_area = turf.area(polygon).toFixed(2);
    },

    draw() {
      const that = this;
      that.clear();

      if (that.handler_Cut_fill == null) {
        that.handler_Cut_fill = new Cesium.DrawHandler(
          viewer,
          Cesium.DrawMode.Polygon,
          0
        );
      }

      var tooltip = createTooltip(viewer._element);
      //绘制多边形
      that.handler_Cut_fill.activeEvt.addEventListener(function (isActive) {
        if (isActive == true) {
          viewer.enableCursorStyle = false;
          viewer._element.style.cursor = "";
          // $('body').removeClass('drawCur').addClass('drawCur');
        } else {
          viewer.enableCursorStyle = true;
          // $('body').removeClass('drawCur');
        }
      });
      that.handler_Cut_fill.movingEvt.addEventListener(function (
        windowPosition
      ) {
        if (windowPosition.x < 200 && windowPosition.y < 150) {
          tooltip.setVisible(false);
          return;
        }
        if (that.handler_Cut_fill.isDrawing) {
          tooltip.showAt(
            windowPosition,
            "<p>点击确定开挖区域中间点</p><p>右键单击结束绘制,进行开挖</p>"
          );
        } else {
          tooltip.showAt(windowPosition, "<p>点击绘制开挖区域第一个点</p>");
        }
      });
      that.handler_Cut_fill.drawEvt.addEventListener(function (result) {
        if (!result.object.positions) {
          tooltip.showAt(result, "<p>请绘制正确的多边形</p>");
          that.handler_Cut_fill.polygon.show = false;
          that.handler_Cut_fill.polyline.show = false;
          that.handler_Cut_fill.deactivate();
          that.handler_Cut_fill.activate();
          return;
        }
        var array = [].concat(result.object.positions);
        tooltip.setVisible(false);

        that.array = array;

        var positions = [];
        var positions_noHeight = [];

        for (var i = 0, len = array.length; i < len; i++) {
          var cartographic = Cesium.Cartographic.fromCartesian(array[i]);
          var longitude = Cesium.Math.toDegrees(cartographic.longitude);
          var latitude = Cesium.Math.toDegrees(cartographic.latitude);
          var h = cartographic.height;
          if (
            positions.indexOf(longitude) == -1 &&
            positions.indexOf(latitude) == -1
          ) {
            positions.push(longitude);
            positions.push(latitude);
            positions.push(h);
            positions_noHeight.push(longitude);
            positions_noHeight.push(latitude);
          }
        }
        let threeArray = null;

        if (positions.length % 2 == 0) {
          threeArray = positions;
        } else {
          threeArray = that.appendLastThree(positions);
        }

        if (that.radio == "smooth") {
          // that.smooth_ana(positions, positions_noHeight, threeArray, -that.height);
          that.smooth_ana1(
            positions,
            positions_noHeight,
            threeArray,
            -that.height
          );
        } else if (that.radio == "cut") {
          if (that.height < 0) {
            that.cutana(threeArray);
          } else {
            that.extract(threeArray);
          }
        }

        that.handler_Cut_fill.polygon.show = false;
        that.handler_Cut_fill.polyline.show = false;
        that.handler_Cut_fill.deactivate();
        // that.handler_Cut_fill.activate();

        let cutVolume = cutFillAnalysis.VolumeAnalysis(
          that.array,
          -that.height
        );
        that.result = cutVolume.toFixed(2);
      });
      that.handler_Cut_fill.activate();
    },
    clear() {
      const that = this;

      if (that.handler_Cut_fill != null) {
        that.handler_Cut_fill.clear();
        viewer.scene.globe.removeAllExcavationRegion();
        viewer.scene.globe.removeAllExtractRegion();
        viewer.scene.globe.removeAllModifyRegion();

        that.handler_Cut_fill.deactivate();
        that.handler_Cut_fill = null;
        that.result = null;
        that.smooth_height = null;
        that.result_area = null;
      }
    },
    appendLastThree(arr) {
      // 创建一个新数组来存储结果
      let result = [...arr]; // 使用扩展运算符复制原始数组

      // 检查数组长度是否至少有三个元素
      // if (arr.length >= 3) {
      // 获取后三个元素并添加到结果数组末尾
      result.push(...arr.slice(-3));
      // }

      // 返回结果数组
      return result;
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  created() {
    // const terrainP = new Cesium.CesiumTerrainProvider({
    //   url: 'http://192.168.60.3:8099/iserver/services/3D-local3DCache-SanYaDSMHuanCun/rest/realspace/datas/dsm@dsm',
    //   isSct: true//地形服务源自SuperMap iServer发布时需设置isSct为true
    // });
    // const terrainP = new Cesium.CesiumTerrainProvider({
    //   url: 'https://www.supermapol.com/realspace/services/3D-stk_terrain/rest/realspace/datas/info/data/path',
    //   requestWaterMask: true,
    //   requestVertexNormals: true,
    //   isSct: false,
    // });
    // // 设置相机视角
    // viewer.scene.camera.setView({
    //   destination: Cesium.Cartesian3.fromDegrees(88.3648, 29.0946, 90000),
    //   orientation: {
    //     heading: 6.10547067016156,
    //     pitch: -0.8475077031996778,
    //     roll: 6.2831853016686185
    //   }
    // });
    // viewer.terrainProvider = terrainP;
  }, //生命周期 - 创建完成（可以访问当前this实例）
  beforeMount() {}, //生命周期 - 挂载之前
  mounted() {
    this.$nextTick((res) => {
      cutFillAnalysis = new CutFillAnalysis(viewer, 80);
      // viewer.scene.globe.depthTestAgainstTerrain = false;

      // const terrainP = new Cesium.CesiumTerrainProvider({
      //   url: 'http://192.168.60.2:8090/iserver/services/3D-local3DCache-SanYaShi_GaoCheng_Level_16DataSource/rest/realspace/datas/%E4%B8%89%E4%BA%9A%E5%B8%82_%E9%AB%98%E7%A8%8B_Level_16%40DataSource',
      //   isSct: true//地形服务源自SuperMap iServer发布时需设置isSct为true
      // });

      // viewer.terrainProvider = terrainP;
    });
  }, //生命周期 - 挂在完成
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroy() {}, //生命周期 - 销毁完成
  activated() {}, //若组件实例是 <KeepAlive> 缓存树的一部分，当组件被插入到 DOM 中时调用。
  deactivated() {}, //若组件实例是 <KeepAlive> 缓存树的一部分，当组件从 DOM 中被移除时调用。
};
</script>
<style lang="scss" scoped>
.el-radio {
  color: white;
}

.cut_fill_centent1 {
  width: 100%;
  text-align: left;
  margin-left: 10%;
  margin-top: 5%;
  margin-bottom: 6%;
}

.cut_fill_input {
  display: inline-block;
  width: 50%;
}

.cut_fill_input:first-child {
  margin-left: 7%;
  margin-bottom: 5%;
}

.cut_fill_Buttons {
  margin-bottom: 2%;
  float: right;
}
</style>