<template>
  <div
    class="sm-panel sm-function-module-content ghzc modelStretch"
    v-if="modelStretchShow"
    v-drag
  >
    <div class="sm-panel-header">
      <span>模型拉伸</span>
      <span class="closeBtn" @click="toggleVisibility">&times;</span>
    </div>
    <div class="xz_box">
      <el-form :model="form" ref="form" label-width="80px" :rules="rules">
        <el-form-item label="平面范围:" prop="xzmj">
          <range type="hgxfx" :keys="['hx', 'sc']" class="range" ref="range" />
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="14" style="text-align: center">
            <!-- 楼体高度:
            <el-input-number
              size="mini"
              step="1"
              v-model="form.BuildingHeight"
              @change="XYChange"
            ></el-input-number> -->
            <el-form-item label="模型高度:" prop="BuildingHeight">
              <el-input
                class="inputwidth"
                v-model.number="form.BuildingHeight"
                size="mini"
                type="number"
              ></el-input>
              米
            </el-form-item>
          </el-col>
          <el-col :span="10" style="text-align: center">
            <el-form-item label="层高:" prop="FLOORH" label-width="45px">
              <el-input
                class="inputwidth"
                v-model.number="form.FLOORH"
                size="mini"
                type="number"
              ></el-input>
              米
            </el-form-item>
            <!-- 层高:
            <el-input-number
              size="mini"
              step="0.1"
              v-model="form.FLOORH"
              @change="XYChange"
            ></el-input-number> -->
          </el-col>
        </el-row>
        <el-form-item label="模型名称:" prop="mxmc">
          <el-input
            v-model="form.mxmc"
            size="mini"
            placeholder="请输入模型名称"
          ></el-input>
        </el-form-item>

        <!-- <div class="SaveCenter">
              <el-button size="mini" type="primary" @click="onSubmit"
                >开始调整</el-button
              >
              <el-button size="mini" @click="removeEntities">清除</el-button>
            </div> -->
      </el-form>
      <div class="Btns">
        <el-button size="mini" @click="clear">清 除</el-button>
        <el-button type="primary" size="mini" @click="submit">确 定</el-button>
      </div>
    </div>
  </div>
</template>
  
  <script>
import range from "@/components/mapview/range.vue"; ///mapview/range
import {} from "@/api/map";
import parse from "wellknown";
let polygonids = [];
let dataSources = {};
export default {
  name: "modelStretch",
  components: {
    range,
  },
  data() {
    return { form: { BuildingHeight: 50, FLOORH: 5 } };
  },
  created() {},
  mounted() {},
  computed: {
    modelStretchShow() {
      return store.state.toolBar[13];
    },
  },
  methods: {
    toggleVisibility() {
      store.setToolBarAction(13);
      this.clear();
    },
    pullUp(item, height) {
      let upid = "up" + item.id;
      if (!dataSources[upid])
        this.loadGeoJSON(parse(item.geom), "#000000", upid, height, item.dkbm);
      else {
        let entities = dataSources[upid].entities.values;
        entities.forEach((entity, ei) => {
          if (height && entity.polygon) {
            entity.polygon.extrudedHeight = height;
            let center = this.getCentroid(parse(item.geom), ei);
            entity.position = Cesium.Cartesian3.fromDegrees(
              center[0],
              center[1],
              height
            );
          }
        });
        viewer.flyTo(dataSources[upid], {
          offset: new Cesium.HeadingPitchRange(0, -0.8),
        });
      }
    },
    pullClear(item) {
      let upid = "up" + item.id;
      if (dataSources[upid]) {
        viewer.dataSources.remove(dataSources[upid]);
        dataSources[upid] = null;
      }
    },
    // 加载GeoJSON数据
    loadGeoJSON(geojson, yanse, id, height, name) {
      let _this = this;
      let fcolor =
        id && id != "all"
          ? Cesium.Color.fromCssColorString(yanse)
          : Cesium.Color.WHITE;
      const dataSource = new Cesium.GeoJsonDataSource();
      dataSource
        .load(geojson, {
          clampToGround: true,
          stroke: Cesium.Color.fromCssColorString(yanse),
          fill: fcolor.withAlpha(0.4), //注意：颜色必须大写，即不能为blue
          strokeWidth: 5,
          // markerSymbol: "", //点图钉的默认符号
        })
        .then((data) => {
          viewer.dataSources.add(data);
          let entities = data.entities.values;
          // let addlabel = false;
          if (!geojson.type.includes("Polygon") || height) {
            entities.forEach((entity, ei) => {
              if (entity.billboard) {
                entity.billboard = undefined;
                entity.point = {
                  pixelsize: 20,
                  color: Cesium.Color.fromCssColorString(yanse),
                };
              }
              if (height && entity.polygon) {
                entity.polygon.extrudedHeight = height;
                entity.polygon.material =
                  Cesium.Color.fromCssColorString("#cdcdcd");
                entity.polygon.outlineColor = Cesium.Color.BLACK;
                entity.polygon.outlineWidth = 1.0;
                // if (!addlabel) {
                let center = this.getCentroid(geojson, ei);

                var polycenter = Cesium.Cartesian3.fromDegrees(
                  center[0],
                  center[1],
                  height
                );
                entity.position = polycenter;
                entity.label = {
                  font: "bolder 18px sans-serif",
                  style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                  text: name, //图标名称
                  fillColor: Cesium.Color.fromCssColorString("#fff000"),
                  pixelOffset: new Cesium.Cartesian2(0, -20),
                  zIndex: 3,
                };
                // addlabel = true;
                // }
              }
            });
          }
          var pitch = height ? -0.8 : -45; // Cesium.Math.toRadians(-45.0);-0.7853981633974483
          let range = height ? 3000 : 5000;
          viewer.flyTo(data, {
            offset: new Cesium.HeadingPitchRange(0, pitch),
          });
          // viewer.zoomTo(data);
          if (id) {
            dataSources[id] = data;
          }
          if (id == "all") _this.isshowAll = true;
        });
    },
    clear() {
      this.$refs.range.reset();
      // this.pullClear();
      this.removeEntities();
    },
    submit() {
      var _temp = this.$refs.range.getRange();
      _temp.geojson = parse(_temp.geom);
      // this.pullUp(_temp, this.form.BuildingHeight);
      this.onSubmit(_temp.geojson);
    },
    onSubmit(geojson) {
      let that = this;
      that.removeEntities();
      // if (!that.loutiInfo) {
      //   that.$message({
      //     message: "未查询到模型数据，请重试加载模型",
      //     type: "warning",
      //   });
      //   return;
      // }
      // const element = that.loutiInfo;
      // //基础高度（地形高度）加入地形后可删除
      let jcgd = 0;
      // //地块编码
      // let bm = element.data.find((c) => c.label == "LANDNO");
      // if (bm && bm.value) {
      //   //获取模型信息
      //   let queryBySQLParameters = {
      //     getFeatureMode: "SQL",
      //     datasetNames: [that.info.Minfo.datasourcename + ":项目范围"],
      //     queryParameter: {
      //       attributeFilter: " DKBM = '" + bm.value + "'",
      //     },
      //     hasGeometry: true,
      //   };
      //   let e = await mapQuery(
      //     that.info.Minfo.dataurl + "/featureResults.json?returnContent=true",
      //     queryBySQLParameters
      //   );

      //   debugger;
      //   if (e && e.totalCount > 0) {
      //     e.features.forEach((feature) => {
      //       feature.fieldNames.forEach((fieldName, i) => {
      //         if (
      //           fieldName == "BASEH" &&
      //           Number(feature.fieldValues[i]) > jcgd
      //         ) {
      //           jcgd = Number(feature.fieldValues[i]);
      //         }
      //       });
      //     });
      //   }
      // } else {
      //   that.$message({
      //     message: "未找到模型基础高度，默认高程为0",
      //     type: "warning",
      //   });
      // }

      //顶部高度，底部高度
      let maxH = jcgd,
        minH = jcgd;
      for (
        let FLOORindex = 1;
        FLOORindex <= Math.ceil(that.form.BuildingHeight / that.form.FLOORH);
        FLOORindex++
      ) {
        // debugger;
        maxH += that.form.FLOORH;
        minH = maxH - that.form.FLOORH;
        console.log("maxH:" + maxH + "----minH:" + minH);
        let ps = [];
        // for (let index = 0; index < element.geometry.points.length; index++) {
        //   const point = element.geometry.points[index];
        //   ps.push(point.x);
        //   ps.push(point.y);
        //   // ps.push(minH);
        // }
        geojson.coordinates[0].forEach((gom) => {
          ps.push(gom[0]);
          ps.push(gom[1]);
        });
        // let id = uuidv4();

        // 定义多边形的顶点（经纬度）
        var polygonHierarchy = new Cesium.PolygonHierarchy(
          Cesium.Cartesian3.fromDegreesArray(ps)
        );

        // 创建带有高度的多边形
        var extrudedPolygon = new Cesium.GeometryInstance({
          geometry: new Cesium.PolygonGeometry({
            polygonHierarchy: polygonHierarchy,
            height: minH, // 多边形底面的高度
            extrudedHeight: maxH, // 拉伸到的高度
          }),
          attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(
              Cesium.Color.CHARTREUSE.withAlpha(0.1)
            ),
          },
        });

        // 添加到场景中
        let Primitive = new Cesium.Primitive({
          geometryInstances: [extrudedPolygon],
          appearance: new Cesium.PerInstanceColorAppearance({
            flat: true,
          }),
          shadows: Cesium.ShadowMode.ENABLED, // 开启阴影
        });
        viewer.scene.primitives.add(Primitive);
        polygonids.push(Primitive);

        // 创建多边形的边界线

        let pss = [];
        // for (let index = 0; index < element.geometry.points.length; index++) {
        //   const point = element.geometry.points[index];
        //   pss.push(point.x);
        //   pss.push(point.y);
        //   pss.push(maxH);
        // }
        geojson.coordinates[0].forEach((gom) => {
          pss.push(gom[0]);
          pss.push(gom[1]);
          pss.push(maxH);
        });
        var boundaryPolyline = new Cesium.GeometryInstance({
          geometry: new Cesium.PolylineGeometry({
            positions: Cesium.Cartesian3.fromDegreesArrayHeights(pss), // 注意这里需要处理高度为0的情况，因为边界线通常在地表
            width: 1, // 边界线的宽度
          }),
          attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(
              Cesium.Color.CHARTREUSE.withAlpha(0.8)
            ),
          },
        });
        let boundaryPolylinePrimitive = new Cesium.Primitive({
          geometryInstances: [boundaryPolyline],
          appearance: new Cesium.PolylineColorAppearance({
            edgeWidth: 1,
            // vertexFormat: Cesium.PolylineVertexFormat.POSITION_AND_COLOR,
            vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
          }),
        });
        viewer.scene.primitives.add(boundaryPolylinePrimitive);
        polygonids.push(boundaryPolylinePrimitive);
        // viewer.entities.add({
        //   id: id,
        //   polygon: {
        //     hierarchy: Cesium.Cartesian3.fromDegreesArrayHeights(ps),
        //     extrudedHeight: Number(maxH),
        //     perPositionHeight: true,
        //     material: Cesium.Color.CHARTREUSE.withAlpha(0.1),
        //     outline: true,
        //     outlineColor: Cesium.Color.MEDIUMSPRINGGREEN,
        //     outlineWidth: 1.0,
        //     shadows: Cesium.ShadowMode.ENABLED,
        //   },
        // });
      }
    },
    removeEntities() {
      for (let index = 0; index < polygonids.length; index++) {
        const element = polygonids[index];
        viewer.scene.primitives.remove(element);
        // viewer.entities.removeById(element);
      }
      polygonids = [];
    },
  },
  watch: { modelStretchShow(newVal) {} },
};
</script>
  <style scoped lang="scss">
.sm-panel {
  max-width: 500px;
}
.modelStretch {
  width: 400px;
  height: 600px;
  .range {
    // flex: 1;
    text-align: left;
    width: 80%;
  }
  .xz_box {
    padding: 0;
  }
  .inputwidth {
    width: calc(100% - 20px);
  }

  .Btns {
    width: 100%;
    // display: -webkit-box;
    // display: -ms-flexbox;
    display: flex;
    padding: 20px 30px;
    // -webkit-box-pack: justify;
    // -ms-flex-pack: justify;
    justify-content: space-between;
    // text-align: center;
    // position: absolute;
    // bottom: 0px;
  }
}
</style>
<style lang="scss">
@import "../complianceAnalysis//ghzc.scss";
</style>
  