"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _react = require("react");
var _cesium = require("cesium");
var useTerrainClipPlan = function useTerrainClipPlan(props) {
  var viewer = props.viewer;
  var showResult = (0, _react.useRef)(true);
  var wellWall = (0, _react.useRef)();
  var bottomSurface = (0, _react.useRef)();
  var wellData = (0, _react.useRef)();
  var excavateMinHeight = (0, _react.useRef)(9999);
  var wallImgStr = (0, _react.useRef)();
  var bottomImgStr = (0, _react.useRef)();
  var splitNumber = (0, _react.useRef)();
  var heightNum = (0, _react.useRef)(0);
  var positionsCur = (0, _react.useRef)([]);

  // 设置是否显示
  var show = function show(isShow) {
    showResult.current = isShow;
    if (viewer.scene.globe.clippingPlanes) viewer.scene.globe.clippingPlanes.enabled = isShow;
    switchExcavate(isShow);
  };
  var switchExcavate = function switchExcavate(isSHow) {
    if (!bottomSurface.current) return;
    if (isSHow) {
      viewer.scene.globe.material = _cesium.Material.fromType("WaJue");
      if (wellWall.current) wellWall.current.show = isSHow;
      bottomSurface.current.show = isSHow;
    } else {
      viewer.globe.material = null;
      if (wellWall.current) wellWall.current.show = !isSHow;
      bottomSurface.current.show = !isSHow;
    }
  };
  var updateExcavateDepth = function updateExcavateDepth(height) {
    if (!wellData.current) return;
    if (bottomSurface.current) viewer.scene.primitives.remove(bottomSurface.current);
    if (wellWall.current) viewer.scene.primitives.remove(wellWall.current);
    var lerpos = wellData.current.lerp_pos;
    var res = [];
    for (var i = 0; i < lerpos.length; i++) {
      res.push(_cesium.Cartesian3.fromRadians(lerpos[i].latitude, excavateMinHeight.current - height));
    }
    heightNum.current = height;
    updateData(positionsCur.current);
  };

  // 开挖分析
  var start = function start(attrs) {
    var wallImg = attrs.wallImg,
      splitNum = attrs.splitNum,
      height = attrs.height,
      positions = attrs.positions,
      bottomImg = attrs.bottomImg;
    wallImgStr.current = wallImg;
    splitNumber.current = splitNum;
    heightNum.current = height;
    bottomImgStr.current = bottomImg;
    positionsCur.current = positions;
    updateData(positionsCur.current);
  };
  var createWell = function createWell(data) {
    if (viewer.terrainProvider._layers) {
      createBottomSurface(data.bottom_pos);
      var handleData = function handleData(arr) {
        var no_height_top = [];
        for (var i = 0; i < arr.length; i++) {
          var s = _cesium.Cartesian3.fromRadians(arr[i].longitude, arr[i].latitude, arr[i].height);
          no_height_top.push(s);
        }
        createWellWall(data.bottom_pos, no_height_top);
      };
      // 针对低于 1.90.0 版本
      if (_cesium.when) {
        (0, _cesium.when)((0, _cesium.sampleTerrainMostDetailed)(viewer.terrainProvider, data.lerp_pos), handleData);
      } else {
        (0, _cesium.sampleTerrainMostDetailed)(viewer.terrainProvider, data.lerp_pos).then(handleData);
      }
    } else {
      createBottomSurface(data.bottom_pos);
      createWellWall(data.bottom_pos, data.no_height_top);
    }
  };
  var createBottomSurface = function createBottomSurface(bottom_pos) {
    if (bottom_pos.length) {
      var minHeight = getMinHeight(bottom_pos);
      var points = [];
      for (var i = 0; i < bottom_pos.length; i++) {
        var p = ellipsoidToLonLat(bottom_pos[i]);
        points.push(p.longitude);
        points.push(p.latitude);
        points.push(minHeight);
      }
      if (!points) return;
      var polygon = new _cesium.PolygonGeometry({
        polygonHierarchy: new _cesium.PolygonHierarchy(_cesium.Cartesian3.fromDegreesArrayHeights(points)),
        perPositionHeight: true
      });
      var geometry = _cesium.PolygonGeometry.createGeometry(polygon);
      var material = new _cesium.Material({
        fabric: {
          type: 'Image',
          uniforms: {
            image: bottomImgStr.current
          }
        }
      });
      var appearance = new _cesium.MaterialAppearance({
        translucent: false,
        flat: true,
        material: material
      });
      if (!geometry) return;
      bottomSurface.current = new _cesium.Primitive({
        geometryInstances: new _cesium.GeometryInstance({
          geometry: geometry
        }),
        appearance: appearance,
        asynchronous: false
      });
      viewer.scene.primitives.add(bottomSurface.current);
    }
  };
  var createWellWall = function createWellWall(bottom_pos, no_height_topt) {
    var minHeight = getMinHeight(bottom_pos);
    var maxHeights = [];
    var minHeights = [];
    for (var i = 0; i < no_height_topt.length; i++) {
      maxHeights.push(ellipsoidToLonLat(no_height_topt[i]).altitude);
      minHeights.push(minHeight);
    }
    var wall = new _cesium.WallGeometry({
      positions: no_height_topt,
      maximumHeights: maxHeights,
      minimumHeights: minHeights
    });
    var geometry = _cesium.WallGeometry.createGeometry(wall);
    var material = new _cesium.Material({
      fabric: {
        type: 'Image',
        uniforms: {
          image: wallImgStr.current
        }
      }
    });
    var appearance = new _cesium.MaterialAppearance({
      translucent: false,
      flat: true,
      material: material
    });
    if (geometry) {
      var primitive = new _cesium.Primitive({
        geometryInstances: new _cesium.GeometryInstance({
          geometry: geometry,
          attributes: {
            color: _cesium.ColorGeometryInstanceAttribute.fromColor(_cesium.Color.GREY)
          },
          id: 'PitWall'
        }),
        appearance: appearance,
        asynchronous: false
      });
      wellWall.current = primitive;
      viewer.scene.primitives.add(primitive);
    }
  };
  var getMinHeight = function getMinHeight(cartesians) {
    var _minPoint;
    var minHeight = 5000000;
    var minPoint = null;
    for (var i = 0; i < cartesians.length; i++) {
      var height = cartesians[i]['z'];
      if (height < minHeight) {
        minHeight = height;
        minPoint = ellipsoidToLonLat(cartesians[i]);
      }
    }
    return (_minPoint = minPoint) === null || _minPoint === void 0 ? void 0 : _minPoint.altitude;
  };
  var ellipsoidToLonLat = function ellipsoidToLonLat(cartesian) {
    var ellipsoid = viewer.scene.globe.ellipsoid;
    var cartesian3 = new _cesium.Cartesian3(cartesian.x, cartesian.y, cartesian.z);
    var cartographic = ellipsoid.cartesianToCartographic(cartesian3);
    var latitude = _cesium.Math.toDegrees(cartographic.latitude);
    var longitude = _cesium.Math.toDegrees(cartographic.longitude);
    var altitude = cartographic.height;
    return {
      longitude: longitude,
      latitude: latitude,
      altitude: altitude
    };
  };

  // 更新开挖深度
  var updateData = function updateData(points) {
    clear();
    var planes = [];
    var pointsLength = points.length;
    // 计算分量差
    // const subtr = Cartesian3.subtract(positions[0], positions[1], new Cartesian3())
    excavateMinHeight.current = 9999;
    for (var i = 0; i < pointsLength; ++i) {
      var nextIndex = (i + 1) % pointsLength;
      // 计算中间值
      var midpoint = _cesium.Cartesian3.midpoint(points[i], points[nextIndex], new _cesium.Cartesian3());
      var catographic = _cesium.Cartographic.fromCartesian(points[i]);
      var height = viewer.scene.globe.getHeight(catographic) || catographic.height;
      height < excavateMinHeight.current && (excavateMinHeight.current = height);
      var up = _cesium.Cartesian3.normalize(midpoint, new _cesium.Cartesian3());
      var right = _cesium.Cartesian3.subtract(points[nextIndex], midpoint, new _cesium.Cartesian3());
      right = _cesium.Cartesian3.normalize(right, right);
      var cross = _cesium.Cartesian3.cross(right, up, new _cesium.Cartesian3());
      cross = _cesium.Cartesian3.normalize(cross, cross);
      var plane = new _cesium.Plane(cross, 0.0);
      var distance = _cesium.Plane.getPointDistance(plane, midpoint);
      planes.push(new _cesium.ClippingPlane(cross, distance));
    }
    viewer.scene.globe.clippingPlanes = new _cesium.ClippingPlaneCollection({
      planes: planes,
      edgeWidth: 1,
      edgeColor: _cesium.Color.WHITE,
      enabled: true,
      unionClippingRegions: false
    });
    prepareWell(points);
    if (wellData.current) {
      createWell(wellData.current);
    }
  };

  // 清除开挖分析结果
  var clear = function clear() {
    var _viewer$scene$globe$c;
    if (viewer.scene.globe.clippingPlanes) {
      viewer.scene.globe.clippingPlanes.enabled = !1;
      viewer.scene.globe.clippingPlanes.removeAll();
    }
    if (viewer.scene.globe.clippingPlanes && !((_viewer$scene$globe$c = viewer.scene.globe.clippingPlanes) !== null && _viewer$scene$globe$c !== void 0 && _viewer$scene$globe$c.isDestroyed)) {
      viewer.scene.globe.clippingPlanes.destroy();
    }
    viewer.scene.globe.clippingPlanes = undefined;
    if (bottomSurface.current) viewer.scene.primitives.remove(bottomSurface.current);
    if (wellWall.current) viewer.scene.primitives.remove(wellWall.current);
    bottomSurface.current = undefined;
    wellWall.current = undefined;
    viewer.scene.render();
  };
  var prepareWell = function prepareWell(points) {
    var len = points.length;
    if (len !== 0) {
      var no_height_top = [];
      var height_top = [];
      var bottom_pos = [];
      var lerp_pos = [];
      var diff = excavateMinHeight.current - heightNum.current;
      for (var i = 0; i < len; i++) {
        var nextIndex = i === len - 1 ? 0 : i + 1;
        var currentCattesian = _cesium.Cartographic.fromCartesian(points[i]);
        var nextCartorghic = _cesium.Cartographic.fromCartesian(points[nextIndex]);
        var currLonLat = [currentCattesian.longitude, currentCattesian.latitude];
        var nextLonLat = [nextCartorghic.longitude, nextCartorghic.latitude];
        if (i === 0) {
          lerp_pos.push(new _cesium.Cartographic(currLonLat[0], currLonLat[1]));
          bottom_pos.push(_cesium.Cartesian3.fromRadians(currLonLat[0], currLonLat[1], diff));
          no_height_top.push(_cesium.Cartesian3.fromRadians(currLonLat[0], currLonLat[1], 0));
          height_top.push(_cesium.Cartesian3.fromRadians(currLonLat[0], currLonLat[1], nextCartorghic.height));
        }
        if (!splitNumber.current) return;
        for (var p = 1; p <= splitNumber.current; p++) {
          var firstLerp = _cesium.Math.lerp(currLonLat[0], nextLonLat[0], p / splitNumber.current);
          var lastLerp = _cesium.Math.lerp(currLonLat[1], nextLonLat[1], p / splitNumber.current);
          if (i !== len - 1 || p !== splitNumber.current) {
            lerp_pos.push(new _cesium.Cartographic(firstLerp, lastLerp));
            bottom_pos.push(_cesium.Cartesian3.fromRadians(firstLerp, lastLerp, diff));
            no_height_top.push(_cesium.Cartesian3.fromRadians(firstLerp, lastLerp, 0));
            height_top.push(_cesium.Cartesian3.fromRadians(firstLerp, lastLerp, nextCartorghic.height));
          }
        }
      }
      wellData.current = {
        lerp_pos: lerp_pos,
        bottom_pos: bottom_pos,
        no_height_top: no_height_top,
        height_top: height_top
      };
    }
  };
  return {
    start: start,
    clear: clear,
    updateData: updateData,
    updateExcavateDepth: updateExcavateDepth,
    show: show
  };
};
var _default = exports["default"] = useTerrainClipPlan;
//# sourceMappingURL=useTerrainClipPlan.js.map
