<template>
  <div
    v-show="isCutFill"
    class="cut_fill_box"
    v-loading="loading"
    element-loading-text="正在分析中...."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <el-radio v-model="radio" label="cut">地形填挖方分析</el-radio>
    <el-radio v-model="radio" label="smooth">地形平整分析</el-radio>
    <el-form
      :model="cutData"
      ref="ruleForm"
      label-width="100px"
      :rules="rules"
      class="ruleForm"
    >
      <el-form-item label="分析范围:" prop="xzmj">
        <range type="cutfill" :keys="['hx', 'sc']" class="range" ref="range" />
      </el-form-item>
      <el-form-item label="填挖基准:" v-if="radio == 'cut'">
        <!-- readonly="readonly" -->
        <el-input v-model="smooth_height" placeholder="" size="mini"></el-input>
      </el-form-item>
      <div class="sdatadiv">
        分析结果：
        <p v-for="(sitem, index) in sdata" :key="index">
          <!-- <img src="/static/images/ghzc/iconSun.png" .toFixed(2) /> -->
          <span class="ptitle">{{ sitem.name }}</span>
          <span class="pvalue">
            {{ cutData[sitem.prop] || 0 }}{{ sitem.unit }}
          </span>
        </p>
      </div>
    </el-form>
    <div class="bottomBtns">
      <!-- <el-button size="mini" type="primary" @click="draw">绘制</el-button> -->
      <!-- <el-button size="mini" type="primary" @click="submitData">确定</el-button>
      <el-button size="mini" type="primary" @click="reset">清除</el-button> -->
      <span class="clearBtn" @click="reset">取消</span>
      <span class="sureBtn" @click="submitData">确定</span>
      <span
        class="sureBtn"
        :disabled="!cutData.fillVolume"
        @click="ExportResult"
        >导出结果</span
      >
    </div>
    <el-descriptions border size="mini" :column="2">
      <el-descriptions-item v-for="item in sdh" :key="item" :label="item.scS"
        ><div
          style="width: 4.5rem; height: 100%"
          :style="{ 'background-color': item.fill }"
        >
          &nbsp;
        </div>
      </el-descriptions-item>
    </el-descriptions>
  </div>
</template>

<script>
import { getDsm, cutFill } from "@/api/analse";
import * as turf from "@turf/turf";
import parse from "wellknown";
import { listToMatrix, loadGeoJSON, download } from "@/utils/MapHelper/help.js";
import range from "@/components/mapview/range.vue"; ///mapview/range
export default {
  name: "TerrainCutFillAnalysis",
  components: { range },
  data() {
    return {
      radio: "smooth",
      sharedState: store.state,
      loading: false,
      smooth_height: "",
      cutData: {},
      // 石方量
      sdata: [
        { name: "填土体积:", prop: "fillVolume", unit: "立方米", value: "" },
        { name: "开挖体积:", prop: "cutVolume", unit: "立方米", value: "" },
        { name: "填挖差值:", prop: "cz", unit: "立方米", value: "" },
        { name: "最大高程:", prop: "maxHeight", unit: "米", value: "" },
        { name: "最小高程:", prop: "minHeight", unit: "米", value: "" },
        { name: "填挖基准:", prop: "midHeight", unit: "米", value: "" },
      ],
      sdh: [
        { scS: "填土", fill: "#1E90A8" },
        { scS: "开挖", fill: "#FF0000" },
      ],
    };
  },
  //监听属性 类似于data概念
  computed: {
    isCutFill: function () {
      return this.sharedState.terrain[4];
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    reset() {
      this.cutData = {};
      this.$refs.range.reset();
      viewer.entities.removeAll();
      viewer.dataSources.removeAll();
    },
    submitData() {
      var _temp = this.$refs.range.getRange();
      if (!_temp.geom) {
        this.$message.warning("请绘制或导入分析范围!");
        return;
      }
      this.cutFill(_temp.geom);
    },
    clear() {
      common.clearHandlerDrawing("Polygon");
    },
    async cutFill(geom) {
      this.loading = true;
      let res = await cutFill({
        geom,
        height: this.smooth_height,
      });
      if (res.success) {
        this.$refs.range.reset();
        this.cutData = res.data;

        Object.keys(this.cutData).forEach((key) => {
          if (typeof this.cutData[key] == "number")
            this.cutData[key] = this.cutData[key].toFixed(2);
        });
        this.cutData.cz = res.data.cutVolume - res.data.fillVolume;

        this.loading = false;
        let pitch = Cesium.Math.toRadians(-45.0);
        let params = { sw: 0.001, fill_a: 0.8 };
        loadGeoJSON(res.data.bottomGeom, "#1E90A8", params, (data) => {
          viewer.flyTo(data, {
            offset: new Cesium.HeadingPitchRange(0, -45, 100),
          });
        });
        loadGeoJSON(res.data.midGeom, "#ff0000", params, (data) => {
          viewer.flyTo(data, {
            offset: new Cesium.HeadingPitchRange(0, -45, 100),
          });
        });
      }

      // 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);
    },
    ExportResult() {
      let _this = this;
      // let box = that.squarePolygon(entitys);
      // viewer.camera.flyTo({
      //   destination: Cesium.Rectangle.fromDegrees(
      //     box[0][0] + 0.0002,
      //     box[0][1] - 0.0002,
      //     box[2][0] - 0.0002,
      //     box[2][1] + 0.0002
      //   ),
      // });
      setTimeout(function () {
        var promise = scene.outputSceneToFile();
        Cesium.when(promise, function (base64data) {
          download(base64data, _this.drawLegends);
        });
      }, 1000);
    },
    /**
     * 根据图片生成画布
     */

    // 绘制图例
    drawLegends(canvas, ctx) {
      let _this = this;
      console.log("-----");
      var legends = [...this.sdata, ...this.sdh];
      var padding = 10; // 图例与边缘的间距
      var lineHeight = 30; // 每行图例的高度
      var labW = 200;
      var x = canvas.width - padding - labW; // 图例的起始X坐标
      var y = canvas.height - legends.length * lineHeight - padding; // 图例的起始Y坐标
      // 绘制颜色块
      ctx.fillStyle = "#ffffff";
      ctx.fillRect(
        x - padding,
        y - padding,
        canvas.width - x + padding,
        canvas.height - y + padding
      );
      legends.forEach(function (legend, index) {
        // 绘制文本
        if (legend.scS) {
          ctx.fillStyle = "black";
          ctx.fillText(legend.scS, x, y + index * lineHeight + lineHeight / 2);
          // 绘制颜色块
          ctx.fillStyle = legend.fill;
          ctx.fillRect(
            x + (labW / 3) * 2,
            y + index * lineHeight,
            30,
            lineHeight
          );
        } else {
          ctx.fillStyle = "black";
          let text = `${legend.name}:${_this.cutData[legend.prop]}${
            legend.unit
          }`;
          ctx.fillText(text, x, y + index * lineHeight + lineHeight / 2);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.cut_fill_box {
  width: 100%;
  height: 550px;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
  .ruleForm {
    width: 100%;
    height: calc(100% - 120px);
    overflow-y: auto;
  }
  .el-form-item {
    margin-bottom: 0px !important;
  }
  .range {
    width: 90% !important;
  }
  .sdatadiv {
    text-align: left;
    line-height: 40px;
  }
  .ptitle {
    width: 100px;
    color: #cddeeb;
    text-align: right;
    padding: 0 12px 0 0;
    display: inline-block;
  }
  .pvalue {
    color: #02a7f0;
  }
}
.el-radio {
  color: white;
}

.bottomBtns {
  line-height: 30px;
  width: 100%;
  // background-color: rgba(255, 192, 203, 0.418);
  display: flex;
  justify-content: space-between;
  text-align: center;
  // position: absolute;
  // bottom: 70px;

  .sureBtn {
    width: 30%;
    background-color: #0f7ac8;
    cursor: pointer;

    &:hover {
      font-weight: bold;
    }
  }

  .clearBtn {
    cursor: pointer;
    width: 30%;
    background-color: #3f94f53f;
    border: 1px solid #3f93f5;
    color: #b6e0ff;

    &:hover {
      font-weight: bold;
    }
  }
}
</style>
<style lang="scss">
.cut_fill_box {
  .el-descriptions {
    color: #fff;
    margin-top: 20px;
    // position: absolute;
    // bottom: 20px;
  }

  .el-descriptions__body {
    color: #fff;
    background-color: #fff0;
  }
  .el-descriptions .is-bordered .el-descriptions-item__cell {
    border: 1px solid rgba(15, 122, 200, 0.4);
  }
  .el-descriptions-item__label.is-bordered-label {
    font-weight: 700;
    color: #ffffff;
    background: rgba(4, 28, 50, 0.6);
  }
  .el-date-editor .el-range-input {
    background-color: rgba(4, 28, 50, 0.5);
  }
}
</style>